0% found this document useful (0 votes)
2 views224 pages

UGC NET Data Structures and Algorithms

The document provides an overview of data structures and algorithms, emphasizing the importance of data structures in efficiently storing and organizing data in computer science. It covers various types of data structures, including linear (arrays, linked lists, stacks, queues) and non-linear (trees, graphs), along with their operations and advantages. Additionally, it discusses algorithms, their characteristics, and the complexity of operations related to arrays.

Uploaded by

Sarathi Goswami
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views224 pages

UGC NET Data Structures and Algorithms

The document provides an overview of data structures and algorithms, emphasizing the importance of data structures in efficiently storing and organizing data in computer science. It covers various types of data structures, including linear (arrays, linked lists, stacks, queues) and non-linear (trees, graphs), along with their operations and advantages. Additionally, it discusses algorithms, their characteristics, and the complexity of operations related to arrays.

Uploaded by

Sarathi Goswami
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DIWAKAR EDUCATION HUB

DATA STRUCTURES AND


ALGORITHMS UNIT – 7
AS PER UPDATED SYLLABUS
DIWAKAR EDUCATION HUB

THE LEARN WITH EXPERTIES


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Data Structures
Data Structure is a way to store and organize data so that it can
be used efficiently.
Data Structure can be defined as the group of data elements
which provides an efficient way of storing and organising data in
the computer so that it can be used efficiently. Some examples of
Data Structures are arrays, Linked List, Stack, Queue, etc. Data
Structures are widely used in almost every aspect of Computer
Science i.e. Operating System, Compiler Design, Artifical
intelligence, Graphics and many more.
Data Structures are the main part of many computer science
algorithms as they enable the programmers to handle the data in an efficient way. It plays a
vitle role in enhancing the performance of a software or a program as the main function of the
software is to store and retrieve the user's data as fast as possible
Basic Terminology
Data structures are the building blocks of any program or the software. Choosing the
appropriate data structure for a program is the most difficult task for a programmer. Following
terminology is used as far as data structures are concerned
Data: Data can be defined as an elementary value or the collection of values, for example,
student's name and its id are the data about the student.
Group Items: Data items which have subordinate data items are called Group item, for
example, name of a student can have first name and the last name.
Record: Record can be defined as the collection of various data items, for example, if we talk
about the student entity, then its name, address, course and marks can be grouped together
to form the record for the student.
File: A File is a collection of various records of one type of entity, for example, if there are 60
employees in the class, then there will be 20 records in the related file where each record
contains the data about each employee.
Attribute and Entity: An entity represents the class of certain objects. it contains various
attributes. Each attribute represents the particular property of that entity.
Field: Field is a single elementary unit of information representing the attribute of an entity.
Need of Data Structures
As applications are getting complexed and amount of data is increasing day by day, there may
arrise the following problems:
Processor speed: To handle very large amout of data, high speed processing is required, but as
the data is growing day by day to the billions of files per entity, processor may fail to deal with
that much amount of data.
Data Search: Consider an inventory size of 106 items in a store, If our application needs to
search for a particular item, it needs to traverse 106 items every time, results in slowing down
the search process.

DIWAKAR EDUCATION HUB Page 2


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Multiple requests: If thousands of users are searching the data simultaneously on a web
server, then there are the chances that a very large server can be failed during that process
in order to solve the above problems, data structures are used. Data is organized to form a
data structure in such a way that all items are not required to be searched and required data
can be searched instantly.
Advantages of Data Structures
Efficiency: Efficiency of a program depends upon the choice of data structures. For example:
suppose, we have some data and we need to perform the search for a perticular record. In
that case, if we organize our data in an array, we will have to search sequentially element by
element. hence, using array may not be very efficient here. There are better data structures
which can make the search process efficient like ordered array, binary search tree or hash
tables.
Reusability: Data structures are reusable, i.e. once we have implemented a particular data
structure, we can use it at any other place. Implementation of data structures can be compiled
into libraries which can be used by different clients.
Abstraction: Data structure is specified by the ADT which provides a level of abstraction. The
client program uses the data structure through interface only, without getting into the
implementation details.
Data Structure Classification

Linear Data Structures: A data structure is called linear if all of its elements are arranged in the
linear order. In linear data structures, the elements are stored in non-hierarchical way where
each element has the successors and predecessors except the first and last element.

DIWAKAR EDUCATION HUB Page 3


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Types of Linear Data Structures are given below:
Arrays: An array is a collection of similar type of data items and each data item is called an
element of the array. The data type of the element may be any valid data type like char, int,
float or double.
The elements of array share the same variable name but each one carries a different index
number known as subscript. The array can be one dimensional, two dimensional or
multidimensional.
The individual elements of the array age are:
age[0], age[1], age[2], age[3],......... age[98], age[99].
Linked List: Linked list is a linear data structure which is used to maintain a list in the memory.
It can be seen as the collection of nodes stored at non-contiguous memory locations. Each
node of the list contains a pointer to its adjacent node.
Stack: Stack is a linear list in which insertion and deletions are allowed only at one end,
called top.
A stack is an abstract data type (ADT), can be implemented in most of the programming
languages. It is named as stack because it behaves like a real-world stack, for example: - piles
of plates or deck of cards etc.
Queue: Queue is a linear list in which elements can be inserted only at one end called rear and
deleted only at the other end called front.
It is an abstract data structure, similar to stack. Queue is opened at both end therefore it
follows First-In-First-Out (FIFO) methodology for storing the data items.
Non Linear Data Structures: This data structure does not form a sequence i.e. each item or
element is connected with two or more other items in a non-linear arrangement. The data
elements are not arranged in sequential structure.
Types of Non Linear Data Structures are given below:
Trees: Trees are multilevel data structures with a hierarchical relationship among its elements
known as nodes. The bottommost nodes in the herierchy are called leaf node while the
topmost node is called root node. Each node contains pointers to point adjacent nodes.
Tree data structure is based on the parent-child relationship among the nodes. Each node in
the tree can have more than one children except the leaf nodes whereas each node can have
atmost one parent except the root node. Trees can be classfied into many categories which
will be discussed later in this tutorial.
Graphs: Graphs can be defined as the pictorial representation of the set of elements
(represented by vertices) connected by the links known as edges. A graph is different from
tree in the sense that a graph can have cycle while the tree cannot have the one.
Operations on data structure
1) Traversing: Every data structure contains the set of data elements. Traversing the data
structure means visiting each element of the data structure in order to perform some specific
operation like searching or sorting.

DIWAKAR EDUCATION HUB Page 4


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Example: If we need to calculate the average of the marks obtained by a student in 6 different
subject, we need to traverse the complete array of marks and calculate the total sum, then we
will devide that sum by the number of subjects i.e. 6, in order to find the average.
2) Insertion: Insertion can be defined as the process of adding the elements to the data
structure at any location.
If the size of data structure is n then we can only insert n-1 data elements into it.
3) Deletion:The process of removing an element from the data structure is called Deletion. We
can delete an element from the data structure at any random location.
If we try to delete an element from an empty data structure then underflow occurs.
4) Searching: The process of finding the location of an element within the data structure is
called Searching. There are two algorithms to perform searching, Linear Search and Binary
Search. We will discuss each one of them later in this tutorial.
5) Sorting: The process of arranging the data structure in a specific order is known as Sorting.
There are many algorithms that can be used to perform sorting, for example, insertion sort,
selection sort, bubble sort, etc.
6) Merging: When two lists List A and List B of size M and N respectively, of similar type of
elements, clubbed or joined to produce the third list, List C of size (M+N), then this process is
called merging
Algorithm
An algorithm is a procedure having well defined steps for solving a particular problem.
Algorithm is finite set of logic or instructions, written in order for accomplish the certain
predefined task. It is not the complete program or code, it is just a solution (logic) of a
problem, which can be represented either as an informal description using a Flowchart or
Pseudo code.
The major categories of algorithms are given below:
o Sort: Algorithm developed for sorting the items in certain order.
o Search: Algorithm developed for searching the items inside a data structure.
o Delete: Algorithm developed for deleting the existing element from the data structure.
o Insert: Algorithm developed for inserting an item inside a data structure.
o Update: Algorithm developed for updating the existing element inside a data structure.
The performance of algorithm is measured on the basis of following properties:
o Time complexity: It is a way of representing the amount of time needed by a program
to run to the completion.
o Space complexity: It is the amount of memory space required by an algorithm, during a
course of its execution. Space complexity is required in situations when limited memory
is available and for the multi user system.
Each algorithm must have:
o Specification: Description of the computational procedure.
o Pre-conditions: The condition(s) on input.
o Body of the Algorithm: A sequence of clear and unambiguous instructions.
o Post-conditions: The condition(s) on output.

DIWAKAR EDUCATION HUB Page 5


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Example: Design an algorithm to multiply the two numbers x and y and display the result in z.
o Step 1 START
o Step 2 declare three integers x, y & z
o Step 3 define values of x & y
o Step 4 multiply values of x & y
o Step 5 store the output of step 4 in z
o Step 6 print z
o Step 7 STOP
. Alternatively the algorithm can be written as ?
o Step 1 START MULTIPLY
o Step 2 get values of x & y
o Step 3 z← x * y
o Step 4 display z
o Step 5 STOP
Characteristics of an Algorithm
An algorithm must follow the mentioned below characteristics:
o Input: An algorithm must have 0 or well defined inputs.
o Output: An algorithm must have 1 or well defined outputs, and should match with the
desired output.
o Feasibility: An algorithm must be terminated after the finite number of steps.
o Independent: An algorithm must have step-by-step directions which is independent of
any programming code.
o Unambiguous: An algorithm must be unambiguous and clear. Each of their steps and
input/outputs must be clear and lead to only one meaning.
Array
o Arrays are defined as the collection of similar type of data items stored at contiguous
memory locations.
o Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc.
o Array is the simplest data structure where each data element can be randomly accessed
by using its index number.
o For example, if we want to store the marks of a student in 6 subjects, then we don't
need to define different variable for the marks in different subject. instead of that, we
can define an array which can store the marks in each subject at a the contiguous
memory locations.
The array marks[10] defines the marks of the student in 10 different subjects where each
subject marks are located at a particular subscript in the array i.e. marks[0] denotes the marks
in first subject, marks[1] denotes the marks in 2nd subject and so on.
Properties of the Array
1. Each element is of same data type and carries a same size i.e. int = 4 bytes.

DIWAKAR EDUCATION HUB Page 6


DATA STRUCTURES AND ALGORITHMS UNIT – 7
2. Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
3. Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of data element.
for example, in C language, the syntax of declaring an array is like following:
1. int arr[10]; char arr[10]; float arr[5]
Need of using Array
In computer programming, the most of the cases requires to store the large number of data of
similar type. To store such amount of data, we need to define a large number of variables. It
would be very difficult to remember names of all the variables while writing the programs.
Instead of naming all the variables with a different name, it is better to define an array and
store all the elements into it.
Following example illustrates, how array can be useful in writing code for a particular problem.
In the following example, we have marks of a student in six different subjects. The problem
intends to calculate the average of all the marks of the student.
In order to illustrate the importance of array, we have created two programs, one is without
using array and other involves the use of array to store marks.
Program without array:
1. #include <stdio.h>
2. void main ()
3. {
4. int marks_1 = 56, marks_2 = 78, marks_3 = 88, marks_4 = 76, marks_5 = 56, marks_6
= 89;
5. float avg = (marks_1 + marks_2 + marks_3 + marks_4 + marks_5 +marks_6) / 6 ;
6. printf(avg);
7. }
Program by using array:
1. #include <stdio.h>
2. void main ()
3. {
4. int marks[6] = {56,78,88,76,56,89);
5. int i;
6. float avg;
7. for (i=0; i<6; i++ )
8. {
9. avg = avg + marks[i];
10. }
11. printf(avg);
12. }
Complexity of Array operations
DIWAKAR EDUCATION HUB Page 7
DATA STRUCTURES AND ALGORITHMS UNIT – 7
Time and space complexity of various array operations are described in the following table.
Time Complexity
Algorithm Average Case Worst Case
Access O(1) O(1)
Search O(n) O(n)
Insertion O(n) O(n)
Deletion O(n) O(n)
Space Complexity
In array, space complexity for worst case is O(n).
Advantages of Array
o Array provides the single name for the group of variables of the same type therefore, it
is easy to remember the name of all the elements of an array.
o Traversing an array is a very simple process, we just need to increment the base address
of the array in order to visit each element one by one.
o Any element in the array can be directly accessed by using the index.
Memory Allocation of the array
As we have mentioned, all the data elements of an array are stored at contiguous locations in
the main memory. The name of the array represents the base address or the address of first
element in the main memory. Each element of the array is represented by a proper indexing.
The indexing of the array can be defined in three ways.
1. 0 (zero - based indexing) : The first element of the array will be arr[0].
2. 1 (one - based indexing) : The first element of the array will be arr[1].
3. n (n - based indexing) : The first element of the array can reside at any random index
number.
In the following image, we have shown the memory allocation of an array arr of size 5. The
array follows 0-based indexing approach. The base address of the array is 100th byte. This will
be the address of arr[0]. Here, the size of int is 4 bytes therefore each element will take 4
bytes in the memory.

DIWAKAR EDUCATION HUB Page 8


DATA STRUCTURES AND ALGORITHMS UNIT – 7
In 0 based indexing, If the size of an array is n then the maximum index number, an element
can have is n-1. However, it will be n if we use 1 based indexing.
Accessing Elements of an array
To access any random element of an array we need the following information:
1. Base Address of the array.
2. Size of an element in bytes.
3. Which type of indexing, array follows.
Address of any element of a 1D array can be calculated by using the following formula:
1. Byte address of element A[i] = base address + size * ( i - first index)
Example :
1. In an array, A[-10 ..... +2 ], Base address (BA) = 999, size of an element = 2 bytes,
2. find the location of A[-1].
3. L(A[-1]) = 999 + [(-1) - (-10)] x 2
4. = 999 + 18
5. = 1017
Passing array to the function :
As we have mentioned earlier that, the name of the array represents the starting address or
the address of the first element of the array. All the elements of the array can be traversed by
using the base address.
The following example illustrate, how the array can be passed to a function.
Example:
1. #include <stdio.h>
2. int summation(int[]);
3. void main ()
4. {
5. int arr[5] = {0,1,2,3,4};
6. int sum = summation(arr);
7. printf("%d",sum);
8. }
9.
10. int summation (int arr[])
11. {
12. int sum=0,i;
13. for (i = 0; i<5; i++)
14. {
15. sum = sum + arr[i];
16. }
17. return sum;
18. }

DIWAKAR EDUCATION HUB Page 9


DATA STRUCTURES AND ALGORITHMS UNIT – 7
The above program defines a function named as summation which accepts an array as an
argument. The function calculates the sum of all the elements of the array and returns it.
2D Array
2D array can be defined as an array of arrays. The 2D array is organized as matrices which can
be represented as the collection of rows and columns.
However, 2D arrays are created to implement a relational database look alike data structure. It
provides ease of holding bulk of data at once which can be passed to any number of functions
wherever required.
How to declare 2D Array
The syntax of declaring two dimensional array is very much similar to that of a one
dimensional array, given as follows.
1. int arr[max_rows][max_columns];
however, It produces the data structure which looks like following.

Above image shows the two dimensional array, the elements are organized in the form of
rows and columns. First element of the first row is represented by a[0][0] where the number
shown in the first index is the number of that row while the number shown in the second
index is the number of the column.
How do we access data in a 2D array
Due to the fact that the elements of 2D arrays can be random accessed. Similar to one
dimensional arrays, we can access the individual cells in a 2D array by using the indices of the
cells. There are two indices attached to a particular cell, one is its row number while the other
is its column number.

DIWAKAR EDUCATION HUB Page 10


DATA STRUCTURES AND ALGORITHMS UNIT – 7
However, we can store the value stored in any particular cell of a 2D array to some variable x
by using the following syntax.
1. int x = a[i][j];
where i and j is the row and column number of the cell respectively.
We can assign each cell of a 2D array to 0 by using the following code:
1. for ( int i=0; i<n ;i++)
2. {
3. for (int j=0; j<n; j++)
4. {
5. a[i][j] = 0;
6. }
7. }
Initializing 2D Arrays
We know that, when we declare and initialize one dimensional array in C programming
simultaneously, we don't need to specify the size of the array. However this will not work with
2D arrays. We will have to define at least the second dimension of the array.
The syntax to declare and initialize the 2D array is given as follows.
1. int arr[2][2] = {0,1,2,3};
The number of elements that can be present in a 2D array will always be equal to (number of
rows * number of columns).
Example : Storing User's data into a 2D array and printing it.
C Example :
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)

DIWAKAR EDUCATION HUB Page 11


DATA STRUCTURES AND ALGORITHMS UNIT – 7
{
printf("%d\t",arr[i][j]);
}
}
}
Java Example
import [Link];
publicclass TwoDArray {
publicstaticvoid main(String[] args) {
int[][] arr = newint[3][3];
Scanner sc = new Scanner([Link]);
for (inti =0;i<3;i++)
{
for(intj=0;j<3;j++)
{
[Link]("Enter Element");
arr[i][j]=[Link]();
[Link]();
}
}
[Link]("Printing Elements...");
for(inti=0;i<3;i++)
{
[Link]();
for(intj=0;j<3;j++)
{
[Link](arr[i][j]+"\t");
}
}
}
}
C# Example
using System;

public class Program


{
public static void Main()
{
int[,] arr = new int[3,3];
DIWAKAR EDUCATION HUB Page 12
DATA STRUCTURES AND ALGORITHMS UNIT – 7
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
[Link]("Enter Element");
arr[i,j]= Convert.ToInt32([Link]());
}
}
[Link]("Printing Elements...");
for (int i=0;i<3;i++)
{
[Link]();
for (int j=0;j<3;j++)
{
[Link](arr[i,j]+" ");
}
}
}
}
Mapping 2D array to 1D array
When it comes to map a 2 dimensional array, most of us might think that why this mapping is
required. However, 2 D arrays exists from the user point of view. 2D arrays are created to
implement a relational database table lookalike data structure, in computer memory, the
storage technique for 2D array is similar to that of an one dimensional array.
The size of a two dimensional array is equal to the multiplication of number of rows and the
number of columns present in the array. We do need to map two dimensional array to the one
dimensional array in order to store them in the memory.
A 3 X 3 two dimensional array is shown in the following image. However, this array needs to be
mapped to a one dimensional array in order to store it into the memory.

DIWAKAR EDUCATION HUB Page 13


DATA STRUCTURES AND ALGORITHMS UNIT – 7

There are two main techniques of storing 2D array elements into memory
1. Row Major ordering
In row major ordering, all the rows of the 2D array are stored into the memory contiguously.
Considering the array shown in the above image, its memory allocation according to row
major order is shown as follows.

first, the 1st row of the array is stored into the memory completely, then the 2 nd row of the
array is stored into the memory completely and so on till the last row.

2. Column Major ordering


According to the column major ordering, all the columns of the 2D array are stored into the
memory contiguously. The memory allocation of the array which is shown in in the above
image is given as follows.

DIWAKAR EDUCATION HUB Page 14


DATA STRUCTURES AND ALGORITHMS UNIT – 7
first, the 1st column of the array is stored into the memory completely, then the 2 nd row of the
array is stored into the memory completely and so on till the last column of the array.

Calculating the Address of the random element of a 2D array


Due to the fact that, there are two different techniques of storing the two dimensional array
into the memory, there are two different formulas to calculate the address of a random
element of the 2D array.
By Row Major Order
If array is declared by a[m][n] where m is the number of rows while n is the number of
columns, then address of an element a[i][j] of the array stored in row major order is calculated
as,
1. Address(a[i][j]) = B. A. + (i * n + j) * size
where, B. A. is the base address or the address of the first element of the array a[0][0] .
Example :
a[10...30, 55...75], base address of the array (BA) = 0, size of an element = 4 bytes .
Find the location of a[15][68].

Address(a[15][68]) = 0 +
((15 - 10) x (68 - 55 + 1) + (68 - 55)) x 4

= (5 x 14 + 13) x 4
= 83 x 4
= 332 answer
By Column major order
If array is declared by a[m][n] where m is the number of rows while n is the number of
columns, then address of an element a[i][j] of the array stored in row major order is calculated
as,
1. Address(a[i][j]) = ((j*m)+i)*Size + BA
where BA is the base address of the array.
Example:
A [-5 ... +20][20 ... 70], BA = 1020, Size of element = 8 bytes. Find the location of a[0][30].
DIWAKAR EDUCATION HUB Page 15
DATA STRUCTURES AND ALGORITHMS UNIT – 7

Address [A[0][30]) = ((30-20) x 24 + 5) x 8 + 1020 = 245 x 8 + 1020 = 2980 bytes


Linked List
o Linked List can be defined as collection of objects called nodes that are randomly stored
in the memory.
o A node contains two fields i.e. data stored at that particular address and the pointer
which contains the address of the next node in the memory.
o The last node of the list contains pointer to the null.

Uses of Linked List


o The list is not required to be contiguously present in the memory. The node can reside
any where in the memory and linked together to make a list. This achieves optimized
utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node can not be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.
Why use linked list over array?
Till now, we were using array data structure to organize the group of elements that are to be
stored individually in the memory. However, Array has several advantages and disadvantages
which must be known in order to decide the data structure which will be used throughout the
program.
Array contains following limitations:
1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to expand the
size of the array at run time.
3. All the elements in the array need to be contiguously stored in the memory. Inserting
any element in the array needs shifting of all its predecessors.
Linked list is the data structure which can overcome all the limitations of an array. Using linked
list is useful because,
1. It allocates the memory dynamically. All the nodes of linked list are non-contiguously
stored in the memory and linked together with the help of pointers.

DIWAKAR EDUCATION HUB Page 16


DATA STRUCTURES AND ALGORITHMS UNIT – 7
2. Sizing is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available
memory space.
Singly linked list or One way chain
Singly linked list can be defined as the collection of ordered set of elements. The number of
elements may vary according to need of the program. A node in the singly linked list consist of
two parts: data part and link part. Data part of the node stores actual information that is to be
represented by the node while the link part of the node stores the address of its immediate
successor.
One way chain or singly linked list can be traversed only in one direction. In other words, we
can say that each node contains only next pointer, therefore we can not traverse the list in the
reverse direction.
Consider an example where the marks obtained by the student in three subjects are stored in
a linked list as shown in the figure.

In the above figure, the arrow represents the links. The data part of every node contains the
marks obtained by the student in the different subject. The last node in the list is identified by
the null pointer which is present in the address part of the last node. We can have as many
elements we require, in the data part of the list.

Complexity

Data Time Complexity Spac


Struct e
ure Com
pleity

Average Worst Worst

Acce Sear Insert Delet Acc Sear Insert Delet


ss ch ion ion ess ch ion ion

DIWAKAR EDUCATION HUB Page 17


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Singly θ(n) θ(n) θ(1) θ(1) O(n) O(n) O(1) O(1) O(n)
Linked
List

Operations on Singly Linked List


There are various operations which can be performed on singly linked list. A list of all such
operations is given below.
Node Creation
1. struct node
2. {
3. int data;
4. struct node *next;
5. };
6. struct node *head, *ptr;
7. ptr = (struct node *)malloc(sizeof(struct node *));
Insertion
The insertion into a singly linked list can be performed at different positions. Based on the
position of the new node being inserted, the insertion is categorized into the following
categories.

SN Operation Description

1 Insertion at It involves inserting any element at the front of the list. We


beginning just need to a few link adjustments to make the new node as
the head of the list.

2 Insertion at It involves insertion at the last of the linked list. The new
end of the node can be inserted as the only node in the list or it can be
list inserted as the last one. Different logics are implemented in
each scenario.

3 Insertion It involves insertion after the specified node of the linked list.
after We need to skip the desired number of nodes in order to
specified reach the node after which the new node will be inserted. .
node

Deletion and Traversing


DIWAKAR EDUCATION HUB Page 18
DATA STRUCTURES AND ALGORITHMS UNIT – 7
The Deletion of a node from a singly linked list can be performed at different positions. Based
on the position of the node being deleted, the operation is categorized into the following
categories.

SN Operation Description

1 Deletion at It involves deletion of a node from the beginning of the list.


beginning This is the simplest operation among all. It just need a few
adjustments in the node pointers.

2 Deletion at It involves deleting the last node of the list. The list can
the end of either be empty or full. Different logic is implemented for
the list the different scenarios.

3 Deletion It involves deleting the node after the specified node in the
after list. we need to skip the desired number of nodes to reach
specified the node after which the node will be deleted. This
node requires traversing through the list.

4 Traversing In traversing, we simply visit each node of the list at least


once in order to perform some specific operation on it, for
example, printing data part of each node present in the
list.

5 Searching In searching, we match each element of the list with the


given element. If the element is found on any of the
location then location of that element is returned
otherwise null is returned. .

Linked List in C: Menu Driven Program


1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. int data;
6. struct node *next;
7. };
8. struct node *head;
9.

DIWAKAR EDUCATION HUB Page 19


DATA STRUCTURES AND ALGORITHMS UNIT – 7
10. void beginsert ();
11. void lastinsert ();
12. void randominsert();
13. void begin_delete();
14. void last_delete();
15. void random_delete();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;
21. while(choice != 9)
22. {
23. printf("\n\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\n");
26. printf("\[Link] in begining\[Link] at last\[Link] at any random location\n4.
Delete from Beginning\n
27. [Link] from last\[Link] node after specified location\[Link] for an element
\[Link]\[Link]\n");
28. printf("\nEnter your choice?\n");
29. scanf("\n%d",&choice);
30. switch(choice)
31. {
32. case 1:
33. beginsert();
34. break;
35. case 2:
36. lastinsert();
37. break;
38. case 3:
39. randominsert();
40. break;
41. case 4:
42. begin_delete();
43. break;
44. case 5:
45. last_delete();
46. break;

DIWAKAR EDUCATION HUB Page 20


DATA STRUCTURES AND ALGORITHMS UNIT – 7
47. case 6:
48. random_delete();
49. break;
50. case 7:
51. search();
52. break;
53. case 8:
54. display();
55. break;
56. case 9:
57. exit(0);
58. break;
59. default:
60. printf("Please enter valid choice..");
61. }
62. }
63. }
64. void beginsert()
65. {
66. struct node *ptr;
67. int item;
68. ptr = (struct node *) malloc(sizeof(struct node *));
69. if(ptr == NULL)
70. {
71. printf("\nOVERFLOW");
72. }
73. else
74. {
75. printf("\nEnter value\n");
76. scanf("%d",&item);
77. ptr->data = item;
78. ptr->next = head;
79. head = ptr;
80. printf("\nNode inserted");
81. }
82.
83. }
84. void lastinsert()
85. {
DIWAKAR EDUCATION HUB Page 21
DATA STRUCTURES AND ALGORITHMS UNIT – 7
86. struct node *ptr,*temp;
87. int item;
88. ptr = (struct node*)malloc(sizeof(struct node));
89. if(ptr == NULL)
90. {
91. printf("\nOVERFLOW");
92. }
93. else
94. {
95. printf("\nEnter value?\n");
96. scanf("%d",&item);
97. ptr->data = item;
98. if(head == NULL)
99. {
100. ptr -> next = NULL;
101. head = ptr;
102. printf("\nNode inserted");
103. }
104. else
105. {
106. temp = head;
107. while (temp -> next != NULL)
108. {
109. temp = temp -> next;
110. }
111. temp->next = ptr;
112. ptr->next = NULL;
113. printf("\nNode inserted");
114.
115. }
116. }
117. }
118. void randominsert()
119. {
120. int i,loc,item;
121. struct node *ptr, *temp;
122. ptr = (struct node *) malloc (sizeof(struct node));
123. if(ptr == NULL)
124. {
DIWAKAR EDUCATION HUB Page 22
DATA STRUCTURES AND ALGORITHMS UNIT – 7
125. printf("\nOVERFLOW");
126. }
127. else
128. {
129. printf("\nEnter element value");
130. scanf("%d",&item);
131. ptr->data = item;
132. printf("\nEnter the location after which you want to insert ");
133. scanf("\n%d",&loc);
134. temp=head;
135. for(i=0;i<loc;i++)
136. {
137. temp = temp->next;
138. if(temp == NULL)
139. {
140. printf("\ncan't insert\n");
141. return;
142. }
143.
144. }
145. ptr ->next = temp ->next;
146. temp ->next = ptr;
147. printf("\nNode inserted");
148. }
149. }
150. void begin_delete()
151. {
152. struct node *ptr;
153. if(head == NULL)
154. {
155. printf("\nList is empty\n");
156. }
157. else
158. {
159. ptr = head;
160. head = ptr->next;
161. free(ptr);
162. printf("\nNode deleted from the begining ...\n");
163. }
DIWAKAR EDUCATION HUB Page 23
DATA STRUCTURES AND ALGORITHMS UNIT – 7
164. }
165. void last_delete()
166. {
167. struct node *ptr,*ptr1;
168. if(head == NULL)
169. {
170. printf("\nlist is empty");
171. }
172. else if(head -> next == NULL)
173. {
174. head = NULL;
175. free(head);
176. printf("\nOnly node of the list deleted ...\n");
177. }
178.
179. else
180. {
181. ptr = head;
182. while(ptr->next != NULL)
183. {
184. ptr1 = ptr;
185. ptr = ptr ->next;
186. }
187. ptr1->next = NULL;
188. free(ptr);
189. printf("\nDeleted Node from the last ...\n");
190. }
191. }
192. void random_delete()
193. {
194. struct node *ptr,*ptr1;
195. int loc,i;
196. printf("\n Enter the location of the node after which you want to perform deleti
on \n");
197. scanf("%d",&loc);
198. ptr=head;
199. for(i=0;i<loc;i++)
200. {
201. ptr1 = ptr;

DIWAKAR EDUCATION HUB Page 24


DATA STRUCTURES AND ALGORITHMS UNIT – 7
202. ptr = ptr->next;
203.
204. if(ptr == NULL)
205. {
206. printf("\nCan't delete");
207. return;
208. }
209. }
210. ptr1 ->next = ptr ->next;
211. free(ptr);
212. printf("\nDeleted node %d ",loc+1);
213. }
214. void search()
215. {
216. struct node *ptr;
217. int item,i=0,flag;
218. ptr = head;
219. if(ptr == NULL)
220. {
221. printf("\nEmpty List\n");
222. }
223. else
224. {
225. printf("\nEnter item which you want to search?\n");
226. scanf("%d",&item);
227. while (ptr!=NULL)
228. {
229. if(ptr->data == item)
230. {
231. printf("item found at location %d ",i+1);
232. flag=0;
233. }
234. else
235. {
236. flag=1;
237. }
238. i++;
239. ptr = ptr -> next;
240. }
DIWAKAR EDUCATION HUB Page 25
DATA STRUCTURES AND ALGORITHMS UNIT – 7
241. if(flag==1)
242. {
243. printf("Item not found\n");
244. }
245. }
246.
247. }
248.
249. void display()
250. {
251. struct node *ptr;
252. ptr = head;
253. if(ptr == NULL)
254. {
255. printf("Nothing to print");
256. }
257. else
258. {
259. printf("\nprinting values . . . . .\n");
260. while (ptr!=NULL)
261. {
262. printf("\n%d",ptr->data);
263. ptr = ptr -> next;
264. }
265. }
266. }
267.

Output:
*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
DIWAKAR EDUCATION HUB Page 26
DATA STRUCTURES AND ALGORITHMS UNIT – 7
[Link]
[Link]
Enter your choice?
1
Enter value
1
Node inserted

*********Main Menu*********
Choose one option from the following list ..
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]
Enter your choice?
2
Enter value?
2
Node inserted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]
Enter your choice?
DIWAKAR EDUCATION HUB Page 27
DATA STRUCTURES AND ALGORITHMS UNIT – 7
3
Enter element value1
Enter the location after which you want to insert 1
Node inserted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]
Enter your choice?
8
printing values . . . . .
1
2
1

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]
Enter your choice?
2
Enter value?
DIWAKAR EDUCATION HUB Page 28
DATA STRUCTURES AND ALGORITHMS UNIT – 7
123
Node inserted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]
Enter your choice?
1
Enter value
1234
Node inserted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]
Enter your choice?
4
Node deleted from the begining ...

*********Main Menu*********

DIWAKAR EDUCATION HUB Page 29


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


5
Deleted Node from the last ...

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]
Enter your choice?
6
Enter the location of the node after which you want to perform deletion
1
Deleted node 2

*********Main Menu*********
Choose one option from the following list ...
===============================================
DIWAKAR EDUCATION HUB Page 30
DATA STRUCTURES AND ALGORITHMS UNIT – 7
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]
Enter your choice?
8
printing values . . . . .
1
1

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


7
Enter item which you want to search?
1
item found at location 1
item found at location 2

*********Main Menu*********

Choose one option from the following list ...


===============================================
DIWAKAR EDUCATION HUB Page 31
DATA STRUCTURES AND ALGORITHMS UNIT – 7

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


9
Doubly linked list
Doubly linked list is a complex type of linked list in which a node contains a pointer to the
previous as well as the next node in the sequence. Therefore, in a doubly linked list, a node
consists of three parts: node data, pointer to the next node in sequence (next pointer) ,
pointer to the previous node (previous pointer). A sample node in a doubly linked list is shown
in the figure.

A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is
shown in the following image.

In C, structure of a node in doubly linked list can be given as :

DIWAKAR EDUCATION HUB Page 32


DATA STRUCTURES AND ALGORITHMS UNIT – 7
1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. }
The prev part of the first node and the next part of the last node will always contain null
indicating end in each direction.
In a singly linked list, we could traverse only in one direction, because each node contains
address of the next node and it doesn't have any record of its previous nodes. However,
doubly linked list overcome this limitation of singly linked list. Due to the fact that, each node
of the list contains the address of its previous node, we can find all the details about the
previous node as well by using the previous address stored inside the previous part of each
node.
Memory Representation of a doubly linked list
Memory Representation of a doubly linked list is shown in the following image. Generally,
doubly linked list consumes more space for every node and therefore, causes more expansive
basic operations such as insertion and deletion. However, we can easily manipulate the
elements of the list since the list maintains pointers in both the directions (forward and
backward).
In the following image, the first element of the list that is i.e. 13 stored at address 1. The head
pointer points to the starting address 1. Since this is the first element being added to the list
therefore the prev of the list contains null. The next node of the list resides at address 4
therefore the first node contains 4 in its next pointer.
We can traverse the list in this way until we find any node containing null or -1 in its next part.

DIWAKAR EDUCATION HUB Page 33


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Operations on doubly linked list


Node Creation
1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. };
7. struct node *head;
All the remaining operations regarding doubly linked list are described in the following table.

SN Operation Description

1 Insertion at Adding the node into the linked list at beginning.


beginning

DIWAKAR EDUCATION HUB Page 34


DATA STRUCTURES AND ALGORITHMS UNIT – 7

2 Insertion at Adding the node into the linked list to the end.
end

3 Insertion Adding the node into the linked list after the specified
after node.
specified
node

4 Deletion at Removing the node from beginning of the list


beginning

5 Deletion at Removing the node from end of the list.


the end

6 Deletion of Removing the node which is present just after the node
the node containing the given data.
having
given data

7 Searching Comparing each node data with the item to be searched


and return the location of the item in the list if the item
found else return null.

8 Traversing Visiting each node of the list at least once in order to


perform some specific operation like searching, sorting,
display, etc.

Menu Driven Program in C to implement all the operations of doubly linked list
1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. struct node *prev;
6. struct node *next;
7. int data;
8. };
9. struct node *head;

DIWAKAR EDUCATION HUB Page 35


DATA STRUCTURES AND ALGORITHMS UNIT – 7
10. void insertion_beginning();
11. void insertion_last();
12. void insertion_specified();
13. void deletion_beginning();
14. void deletion_last();
15. void deletion_specified();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;
21. while(choice != 9)
22. {
23. printf("\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\n");
26. printf("\[Link] in begining\[Link] at last\[Link] at any random location\n4.
Delete from Beginning\n
27. [Link] from last\[Link] the node after the given data\[Link]\[Link]\n9.
Exit\n");
28. printf("\nEnter your choice?\n");
29. scanf("\n%d",&choice);
30. switch(choice)
31. {
32. case 1:
33. insertion_beginning();
34. break;
35. case 2:
36. insertion_last();
37. break;
38. case 3:
39. insertion_specified();
40. break;
41. case 4:
42. deletion_beginning();
43. break;
44. case 5:
45. deletion_last();
46. break;

DIWAKAR EDUCATION HUB Page 36


DATA STRUCTURES AND ALGORITHMS UNIT – 7
47. case 6:
48. deletion_specified();
49. break;
50. case 7:
51. search();
52. break;
53. case 8:
54. display();
55. break;
56. case 9:
57. exit(0);
58. break;
59. default:
60. printf("Please enter valid choice..");
61. }
62. }
63. }
64. void insertion_beginning()
65. {
66. struct node *ptr;
67. int item;
68. ptr = (struct node *)malloc(sizeof(struct node));
69. if(ptr == NULL)
70. {
71. printf("\nOVERFLOW");
72. }
73. else
74. {
75. printf("\nEnter Item value");
76. scanf("%d",&item);
77.
78. if(head==NULL)
79. {
80. ptr->next = NULL;
81. ptr->prev=NULL;
82. ptr->data=item;
83. head=ptr;
84. }
85. else
DIWAKAR EDUCATION HUB Page 37
DATA STRUCTURES AND ALGORITHMS UNIT – 7
86. {
87. ptr->data=item;
88. ptr->prev=NULL;
89. ptr->next = head;
90. head->prev=ptr;
91. head=ptr;
92. }
93. printf("\nNode inserted\n");
94. }
95.
96. }
97. void insertion_last()
98. {
99. struct node *ptr,*temp;
100. int item;
101. ptr = (struct node *) malloc(sizeof(struct node));
102. if(ptr == NULL)
103. {
104. printf("\nOVERFLOW");
105. }
106. else
107. {
108. printf("\nEnter value");
109. scanf("%d",&item);
110. ptr->data=item;
111. if(head == NULL)
112. {
113. ptr->next = NULL;
114. ptr->prev = NULL;
115. head = ptr;
116. }
117. else
118. {
119. temp = head;
120. while(temp->next!=NULL)
121. {
122. temp = temp->next;
123. }
124. temp->next = ptr;
DIWAKAR EDUCATION HUB Page 38
DATA STRUCTURES AND ALGORITHMS UNIT – 7
125. ptr ->prev=temp;
126. ptr->next = NULL;
127. }
128.
129. }
130. printf("\nnode inserted\n");
131. }
132. void insertion_specified()
133. {
134. struct node *ptr,*temp;
135. int item,loc,i;
136. ptr = (struct node *)malloc(sizeof(struct node));
137. if(ptr == NULL)
138. {
139. printf("\n OVERFLOW");
140. }
141. else
142. {
143. temp=head;
144. printf("Enter the location");
145. scanf("%d",&loc);
146. for(i=0;i<loc;i++)
147. {
148. temp = temp->next;
149. if(temp == NULL)
150. {
151. printf("\n There are less than %d elements", loc);
152. return;
153. }
154. }
155. printf("Enter value");
156. scanf("%d",&item);
157. ptr->data = item;
158. ptr->next = temp->next;
159. ptr -> prev = temp;
160. temp->next = ptr;
161. temp->next->prev=ptr;
162. printf("\nnode inserted\n");
163. }
DIWAKAR EDUCATION HUB Page 39
DATA STRUCTURES AND ALGORITHMS UNIT – 7
164. }
165. void deletion_beginning()
166. {
167. struct node *ptr;
168. if(head == NULL)
169. {
170. printf("\n UNDERFLOW");
171. }
172. else if(head->next == NULL)
173. {
174. head = NULL;
175. free(head);
176. printf("\nnode deleted\n");
177. }
178. else
179. {
180. ptr = head;
181. head = head -> next;
182. head -> prev = NULL;
183. free(ptr);
184. printf("\nnode deleted\n");
185. }
186.
187. }
188. void deletion_last()
189. {
190. struct node *ptr;
191. if(head == NULL)
192. {
193. printf("\n UNDERFLOW");
194. }
195. else if(head->next == NULL)
196. {
197. head = NULL;
198. free(head);
199. printf("\nnode deleted\n");
200. }
201. else
202. {
DIWAKAR EDUCATION HUB Page 40
DATA STRUCTURES AND ALGORITHMS UNIT – 7
203. ptr = head;
204. if(ptr->next != NULL)
205. {
206. ptr = ptr -> next;
207. }
208. ptr -> prev -> next = NULL;
209. free(ptr);
210. printf("\nnode deleted\n");
211. }
212. }
213. void deletion_specified()
214. {
215. struct node *ptr, *temp;
216. int val;
217. printf("\n Enter the data after which the node is to be deleted : ");
218. scanf("%d", &val);
219. ptr = head;
220. while(ptr -> data != val)
221. ptr = ptr -> next;
222. if(ptr -> next == NULL)
223. {
224. printf("\nCan't delete\n");
225. }
226. else if(ptr -> next -> next == NULL)
227. {
228. ptr ->next = NULL;
229. }
230. else
231. {
232. temp = ptr -> next;
233. ptr -> next = temp -> next;
234. temp -> next -> prev = ptr;
235. free(temp);
236. printf("\nnode deleted\n");
237. }
238. }
239. void display()
240. {
241. struct node *ptr;
DIWAKAR EDUCATION HUB Page 41
DATA STRUCTURES AND ALGORITHMS UNIT – 7
242. printf("\n printing values...\n");
243. ptr = head;
244. while(ptr != NULL)
245. {
246. printf("%d\n",ptr->data);
247. ptr=ptr->next;
248. }
249. }
250. void search()
251. {
252. struct node *ptr;
253. int item,i=0,flag;
254. ptr = head;
255. if(ptr == NULL)
256. {
257. printf("\nEmpty List\n");
258. }
259. else
260. {
261. printf("\nEnter item which you want to search?\n");
262. scanf("%d",&item);
263. while (ptr!=NULL)
264. {
265. if(ptr->data == item)
266. {
267. printf("\nitem found at location %d ",i+1);
268. flag=0;
269. break;
270. }
271. else
272. {
273. flag=1;
274. }
275. i++;
276. ptr = ptr -> next;
277. }
278. if(flag==1)
279. {
280. printf("\nItem not found\n");
DIWAKAR EDUCATION HUB Page 42
DATA STRUCTURES AND ALGORITHMS UNIT – 7
281. }
282. }
283.
284. }

Output
*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
8
printing values...

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
1
Enter Item value12
Node inserted

DIWAKAR EDUCATION HUB Page 43


DATA STRUCTURES AND ALGORITHMS UNIT – 7
*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
1
Enter Item value123
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
1
Enter Item value1234
Node inserted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
DIWAKAR EDUCATION HUB Page 44
DATA STRUCTURES AND ALGORITHMS UNIT – 7
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
8
printing values...
1234
123
12

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
2
Enter value89
node inserted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
DIWAKAR EDUCATION HUB Page 45
DATA STRUCTURES AND ALGORITHMS UNIT – 7
[Link]
[Link]
[Link]
Enter your choice?
3
Enter the location1
Enter value12345
node inserted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
8
printing values...
1234
123
12345
12
89

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
DIWAKAR EDUCATION HUB Page 46
DATA STRUCTURES AND ALGORITHMS UNIT – 7
[Link]
[Link]
[Link]
Enter your choice?
4
node deleted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
5
node deleted

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
8
printing values...
123
DIWAKAR EDUCATION HUB Page 47
DATA STRUCTURES AND ALGORITHMS UNIT – 7
12345

*********Main Menu*********

Choose one option from the following list ...


===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
6
Enter the data after which the node is to be deleted : 123

*********Main Menu*********
Choose one option from the following list ...

===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
8
printing values...
123
*********Main Menu*********
Choose one option from the following list ...
DIWAKAR EDUCATION HUB Page 48
DATA STRUCTURES AND ALGORITHMS UNIT – 7
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
7
Enter item which you want to search?
123
item found at location 1
*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
6
Enter the data after which the node is to be deleted : 123
Can't delete

*********Main Menu*********
Choose one option from the following list ...
===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
DIWAKAR EDUCATION HUB Page 49
DATA STRUCTURES AND ALGORITHMS UNIT – 7
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]
Enter your choice?
9
Exited..

Circular Singly Linked List


In a circular Singly linked list, the last node of the list contains a pointer to the first node of the
list. We can have circular singly linked list as well as circular doubly linked list.
We traverse a circular singly linked list until we reach the same node where we started. The
circular singly liked list has no beginning and no ending. There is no null value present in the
next part of any of the nodes.
The following image shows a circular singly linked list.

Circular linked list are mostly used in task maintenance in operating systems. There are many
examples where circular linked list are being used in computer science including browser
surfing where a record of pages visited in the past by the user, is maintained in the form of
circular linked lists and can be accessed again on clicking the previous button.
Memory Representation of circular linked list:
In the following image, memory representation of a circular linked list containing marks of a
student in 4 subjects. However, the image shows a glimpse of how the circular list is being
stored in the memory. The start or head of the list is pointing to the element with the index 1
and containing 13 marks in the data part and 4 in the next part. Which means that it is linked
with the node that is being stored at 4th index of the list.
However, due to the fact that we are considering circular linked list in the memory therefore
the last node of the list contains the address of the first node of the list.
DIWAKAR EDUCATION HUB Page 50
DATA STRUCTURES AND ALGORITHMS UNIT – 7

We can also have more than one number of linked list in the memory with the different start
pointers pointing to the different start nodes in the list. The last node is identified by its next
part which contains the address of the start node of the list. We must be able to identify the
last node of any linked list so that we can find out the number of iterations which need to be
performed while traversing the list.
Operations on Circular Singly linked list:
Insertion

SN Operation Description

1 Insertion at Adding a node into circular singly linked list at the


beginning beginning.

2 Insertion at the Adding a node into circular singly linked list at the
end end.

Deletion & Traversing

DIWAKAR EDUCATION HUB Page 51


DATA STRUCTURES AND ALGORITHMS UNIT – 7

SN Operation Description

1 Deletion at Removing the node from circular singly linked list at the
beginning beginning.

2 Deletion at Removing the node from circular singly linked list at the
the end end.

3 Searching Compare each element of the node with the given item
and return the location at which the item is present in the
list otherwise return null.

4 Traversing Visiting each element of the list at least once in order to


perform some specific operation.

Circular Doubly Linked List


Circular doubly linked list is a more complexed type of data structure in which a node contain
pointers to its previous node as well as the next node. Circular doubly linked list doesn't
contain NULL in any of the node. The last node of the list contains the address of the first node
of the list. The first node of the list also contain address of the last node in its previous pointer.
A circular doubly linked list is shown in the following figure.

Due to the fact that a circular doubly linked list contains three parts in its structure therefore,
it demands more space per node and more expensive basic operations. However, a circular
doubly linked list provides easy manipulation of the pointers and the searching becomes twice
as efficient.
Memory Management of Circular Doubly linked list
The following figure shows the way in which the memory is allocated for a circular doubly
linked list. The variable head contains the address of the first element of the list i.e. 1 hence
the starting node of the list contains data A is stored at address 1. Since, each node of the list

DIWAKAR EDUCATION HUB Page 52


DATA STRUCTURES AND ALGORITHMS UNIT – 7
is supposed to have three parts therefore, the starting node of the list contains address of the
last node i.e. 8 and the next node i.e. 4. The last node of the list that is stored at address 8 and
containing data as 6, contains address of the first node of the list as shown in the image i.e. 1.
In circular doubly linked list, the last node is identified by the address of the first node which is
stored in the next part of the last node therefore the node which contains the address of the
first node, is actually the last node of the list.

Operations on circular doubly linked list :


There are various operations which can be performed on circular doubly linked list. The node
structure of a circular doubly linked list is similar to doubly linked list. However, the operations
on circular doubly linked list is described in the following table.

SN Operation Description

1 Insertion at Adding a node in circular doubly linked list at the


beginning beginning.

2 Insertion at end Adding a node in circular doubly linked list at the end.

3 Deletion at Removing a node in circular doubly linked list from


beginning beginning.

DIWAKAR EDUCATION HUB Page 53


DATA STRUCTURES AND ALGORITHMS UNIT – 7

4 Deletion at end Removing a node in circular doubly linked list at the


end.
Traversing and searching in circular doubly linked list is similar to that in the circular singly
linked list.
Stack
1. Stack is an ordered list in which, insertion and deletion can be performed only at one
end that is called top.
2. Stack is a recursive data structure having pointer to its top element.
3. Stacks are sometimes called as Last-In-First-Out (LIFO) lists i.e. the element which is
inserted first in the stack, will be deleted last from the stack.
Applications of Stack
1. Recursion
2. Expression evaluations and conversions
3. Parsing
4. Browsers
5. Editors
6. Tree Traversals
Operations on Stack
There are various operations which can be performed on stack.

1. Push : Adding an element onto the stack

DIWAKAR EDUCATION HUB Page 54


DATA STRUCTURES AND ALGORITHMS UNIT – 7

2. Pop : Removing an element from the stack

3. Peek : Look all the elements of stack without removing them.


How the stack grows?
Scenario 1 : Stack is empty
The stack is called empty if it doesn't contain any element inside it. At this stage, the value of
variable top is -1.

DIWAKAR EDUCATION HUB Page 55


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Scenario 2 : Stack is not empty


Value of top will get increased by 1 every time when we add any element to the stack. In the
following stack, After adding first element, top = 2.

Scenario 3 : Deletion of an element


Value of top will get decreased by 1 whenever an element is deleted from the stack.
In the following stack, after deleting 10 from the stack, top = 1.

DIWAKAR EDUCATION HUB Page 56


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Top and its value :

Top position Status of stack

-1 Empty

0 Only one element in the stack

N-1 Stack is full

N Overflow

Array implementation of Stack


In array implementation, the stack is formed by using the array. All the operations regarding
the stack are performed using arrays. see how each operation can be implemented on the
stack using array data structure.
Adding an element onto the stack (push operation)
Adding an element into the top of the stack is referred to as push operation. Push operation
involves following two steps.
1. Increment the variable Top so that it can now refere to the next memory location.
2. Add element at the position of incremented top. This is referred to as adding new
element at the top of the stack.
Stack is overflown when we try to insert an element into a completely filled stack therefore,
our main function must always avoid stack overflow condition.
Algorithm:

DIWAKAR EDUCATION HUB Page 57


DATA STRUCTURES AND ALGORITHMS UNIT – 7
1. begin
2. if top = n then stack full
3. top = top + 1
4. stack (top) : = item;
5. end
Time Complexity : o(1)
implementation of push algorithm in C language
1. void push (int val,int n) //n is size of the stack
2. {
3. if (top == n )
4. printf("\n Overflow");
5. else
6. {
7. top = top +1;
8. stack[top] = val;
9. }
10. }
Deletion of an element from a stack (Pop operation)
Deletion of an element from the top of the stack is called pop operation. The value of the
variable top will be incremented by 1 whenever an item is deleted from the stack. The top
most element of the stack is stored in an another variable and then the top is decremented by
1. the operation returns the deleted value that was stored in another variable as the result.
The underflow condition occurs when we try to delete an element from an already empty
stack.
Algorithm :
1. begin
2. if top = 0 then stack empty;
3. item := stack(top);
4. top = top - 1;
5. end;
Time Complexity : o(1)
Implementation of POP algorithm using C language
1. int pop ()
2. {
3. if(top == -1)
4. {
5. printf("Underflow");
6. return 0;
7. }

DIWAKAR EDUCATION HUB Page 58


DATA STRUCTURES AND ALGORITHMS UNIT – 7
8. else
9. {
10. return stack[top - - ];
11. }
12. }
Visiting each element of the stack (Peek operation)
Peek operation involves returning the element which is present at the top of the stack without
deleting it. Underflow condition can occur if we try to return the top element in an already
empty stack.
Algorithm :
PEEK (STACK, TOP)
1. Begin
2. if top = -1 then stack empty
3. item = stack[top]
4. return item
5. End
Time complexity: o(n)
Implementation of Peek algorithm in C language
1. int peek()
2. {
3. if (top == -1)
4. {
5. printf("Underflow");
6. return 0;
7. }
8. else
9. {
10. return stack [top];
11. }
12. }

Linked list implementation of stack


Instead of using array, we can also use linked list to implement stack. Linked list allocates the
memory dynamically. However, time complexity in both the scenario is same for all the
operations i.e. push, pop and peek.
In linked list implementation of stack, the nodes are maintained non-contiguously in the
memory. Each node contains a pointer to its immediate successor node in the stack. Stack is
said to be overflown if the space left in the memory heap is not enough to create a node.

DIWAKAR EDUCATION HUB Page 59


DATA STRUCTURES AND ALGORITHMS UNIT – 7

The top most node in the stack always contains null in its address field. Lets discuss the way in
which, each operation is performed in linked list implementation of stack.
Adding a node to the stack (Push operation)
Adding a node to the stack is referred to as push operation. Pushing an element to a stack in
linked list implementation is different from that of an array implementation. In order to push
an element onto the stack, the following steps are involved.
1. Create a node first and allocate memory to it.
2. If the list is empty then the item is to be pushed as the start node of the list. This
includes assigning value to the data part of the node and assign null to the address part
of the node.
3. If there are some nodes in the list already, then we have to add the new element in the
beginning of the list (to not violate the property of the stack). For this purpose, assign
the address of the starting element to the address field of the new node and make the
new node, the starting node of the list.
Time Complexity : o(1)

DIWAKAR EDUCATION HUB Page 60


DATA STRUCTURES AND ALGORITHMS UNIT – 7

C implementation :
1. void push ()
2. {
3. int val;
4. struct node *ptr =(struct node*)malloc(sizeof(struct node));
5. if(ptr == NULL)
6. {
7. printf("not able to push the element");
8. }
9. else
10. {
11. printf("Enter the value");

DIWAKAR EDUCATION HUB Page 61


DATA STRUCTURES AND ALGORITHMS UNIT – 7
12. scanf("%d",&val);
13. if(head==NULL)
14. {
15. ptr->val = val;
16. ptr -> next = NULL;
17. head=ptr;
18. }
19. else
20. {
21. ptr->val = val;
22. ptr->next = head;
23. head=ptr;
24.
25. }
26. printf("Item pushed");
27.
28. }
29. }
Deleting a node from the stack (POP operation)
Deleting a node from the top of stack is referred to as pop operation. Deleting a node from the
linked list implementation of stack is different from that in the array implementation. In order
to pop an element from the stack, we need to follow the following steps :
30. Check for the underflow condition: The underflow condition occurs when we try
to pop from an already empty stack. The stack will be empty if the head pointer of
the list points to null.
31. Adjust the head pointer accordingly: In stack, the elements are popped only from
one end, therefore, the value stored in the head pointer must be deleted and the
node must be freed. The next node of the head node now becomes the head
node.
Time Complexity : o(n)
C implementation
1. void pop()
2. {
3. int item;
4. struct node *ptr;
5. if (head == NULL)
6. {
7. printf("Underflow");
8. }
9. else
DIWAKAR EDUCATION HUB Page 62
DATA STRUCTURES AND ALGORITHMS UNIT – 7
10. {
11. item = head->val;
12. ptr = head;
13. head = head->next;
14. free(ptr);
15. printf("Item popped");
16.
17. }
18. }
Display the nodes (Traversing)
Displaying all the nodes of a stack needs traversing all the nodes of the linked list organized in
the form of stack. For this purpose, we need to follow the following steps.
19. Copy the head pointer into a temporary pointer.
20. Move the temporary pointer through all the nodes of the list and print the value
field attached to every node.
Time Complexity : o(n)
C Implementation
1. void display()
2. {
3. int i;
4. struct node *ptr;
5. ptr=head;
6. if(ptr == NULL)
7. {
8. printf("Stack is empty\n");
9. }
10. else
11. {
12. printf("Printing Stack elements \n");
13. while(ptr!=NULL)
14. {
15. printf("%d\n",ptr->val);
16. ptr = ptr->next;
17. }
18. }
19. }
Queue
1. A queue can be defined as an ordered list which enables insert operations to be performed
at one end called REAR and delete operations to be performed at another end called FRONT.

DIWAKAR EDUCATION HUB Page 63


DATA STRUCTURES AND ALGORITHMS UNIT – 7
2. Queue is referred to be as First In First Out list.
3. For example, people waiting in line for a rail ticket form a queue.

Applications of Queue
Due to the fact that queue performs actions on first in first out basis which is quite fair for the
ordering of actions. There are various applications of queues discussed as below.
1. Queues are widely used as waiting lists for a single shared resource like printer, disk,
CPU.
2. Queues are used in asynchronous transfer of data (where data is not being transferred
at the same rate between two processes) for eg. pipes, file IO, sockets.
3. Queues are used as buffers in most of the applications like MP3 media player, CD player,
etc.
4. Queue are used to maintain the play list in media players in order to add and remove
the songs from the play-list.
Queues are used in operating systems for handling interrupts.
Complexity

Data Time Complexity Space


Structur Compleit
e y

Average Worst Worst

Acces Searc Insertio Deletio Acces Searc Insertio Deletio


s h n n s h n n

Queue θ(n) θ(n) θ(1) θ(1) O(n) O(n) O(1) O(1) O(n)

Array representation of Queue


We can easily represent queue by using linear arrays. There are two variables i.e. front and
rear, that are implemented in the case of every queue. Front and rear variables point to the
position from where insertions and deletions are performed in a queue. Initially, the value of
DIWAKAR EDUCATION HUB Page 64
DATA STRUCTURES AND ALGORITHMS UNIT – 7
front and queue is -1 which represents an empty queue. Array representation of a queue
containing 5 elements along with the respective values of front and rear, is shown in the
following figure.

The above figure shows the queue of characters forming the English word "HELLO". Since, No
deletion is performed in the queue till now, therefore the value of front remains -1 . However,
the value of rear increases by one every time an insertion is performed in the queue. After
inserting an element into the queue shown in the above figure, the queue will look something
like following. The value of rear will become 5 while the value of front remains same.

After deleting an element, the value of front will increase from -1 to 0. however, the queue
will look something like following.

DIWAKAR EDUCATION HUB Page 65


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Algorithm to insert any element in a queue


Check if the queue is already full by comparing rear to max - 1. if so, then return an overflow
error.
If the item is to be inserted as the first element in the list, in that case set the value of front
and rear to 0 and insert the element at the rear end.
Otherwise keep increasing the value of rear and insert each element one by one having rear as
the index.
Algorithm
o Step 1: IF REAR = MAX - 1
Write OVERFLOW
Go to step
[END OF IF]
o Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
o Step 3: Set QUEUE[REAR] = NUM
o Step 4: EXIT
C Function
1. void insert (int queue[], int max, int front, int rear, int item)
2. {
3. if (rear + 1 == max)
4. {
5. printf("overflow");
6. }
7. else

DIWAKAR EDUCATION HUB Page 66


DATA STRUCTURES AND ALGORITHMS UNIT – 7
8. {
9. if(front == -1 && rear == -1)
10. {
11. front = 0;
12. rear = 0;
13. }
14. else
15. {
16. rear = rear + 1;
17. }
18. queue[rear]=item;
19. }
20. }
Algorithm to delete an element from the queue
If, the value of front is -1 or value of front is greater than rear , write an underflow message
and exit.
Otherwise, keep increasing the value of front and return the item stored at the front end of
the queue at each time.
Algorithm
o Step 1: IF FRONT = -1 or FRONT > REAR
Write UNDERFLOW
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
o Step 2: EXIT
C Function
1. int delete (int queue[], int max, int front, int rear)
2. {
3. int y;
4. if (front == -1 || front > rear)
5.
6. {
7. printf("underflow");
8. }
9. else
10. {
11. y = queue[front];
12. if(front == rear)
13. {
DIWAKAR EDUCATION HUB Page 67
DATA STRUCTURES AND ALGORITHMS UNIT – 7
14. front = rear = -1;
15. else
16. front = front + 1;
17.
18. }
19. return y;
20. }
21. }
Drawback of array implementation
Although, the technique of creating a queue is easy, but there are some drawbacks of using
this technique to implement a queue.
o Memory wastage : The space of the array, which is used to store queue elements, can
never be reused to store the elements of that queue because the elements can only be
inserted at front end and the value of front might be so high so that, all the space before
that, can never be filled.

The above figure shows how the memory space is wasted in the array representation of
queue. In the above figure, a queue of size 10 having 3 elements, is shown. The value of the
front variable is 5, therefore, we can not reinsert the values in the place of already deleted
element before the position of front. That much space of the array is wasted and can not be
used in the future (for this queue).
o Deciding the array size
On of the most common problem with array implementation is the size of the array which
requires to be declared in advance. Due to the fact that, the queue can be extended at
runtime depending upon the problem, the extension in the array size is a time taking process
and almost impossible to be performed at runtime since a lot of reallocations take place. Due
to this reason, we can declare the array large enough so that we can store queue elements as
enough as possible but the main problem with this declaration is that, most of the array slots
(nearly half) can never be reused. It will again lead to memory wastage.
Linked List implementation of Queue
Due to the drawbacks discussed in the previous section of this tutorial, the array
implementation can not be used for the large scale applications where the queues are

DIWAKAR EDUCATION HUB Page 68


DATA STRUCTURES AND ALGORITHMS UNIT – 7
implemented. One of the alternative of array implementation is linked list implementation of
queue.
The storage requirement of linked representation of a queue with n elements is o(n) while the
time requirement for operations is o(1).
In a linked queue, each node of the queue consists of two parts i.e. data part and the link part.
Each element of the queue points to its immediate next element in the memory.
In the linked queue, there are two pointers maintained in the memory i.e. front pointer and
rear pointer. The front pointer contains the address of the starting element of the queue while
the rear pointer contains the address of the last element of the queue.
Insertion and deletions are performed at rear and front end respectively. If front and rear both
are NULL, it indicates that the queue is empty.
The linked representation of queue is shown in the following figure.

Operation on Linked Queue


There are two basic operations which can be implemented on the linked queues. The
operations are Insertion and Deletion.
Insert operation
The insert operation append the queue by adding an element to the end of the queue. The
new element will be the last element of the queue.
Firstly, allocate the memory for the new node ptr by using the following statement.
1. Ptr = (struct node *) malloc (sizeof(struct node));
There can be the two scenario of inserting this new node ptr into the linked queue.
In the first scenario, we insert element into an empty queue. In this case, the condition front =
NULL becomes true. Now, the new element will be added as the only element of the queue
and the next pointer of front and rear pointer both, will point to NULL.
1. ptr -> data = item;
2. if(front == NULL)
3. {
4. front = ptr;
5. rear = ptr;
6. front -> next = NULL;
7. rear -> next = NULL;

DIWAKAR EDUCATION HUB Page 69


DATA STRUCTURES AND ALGORITHMS UNIT – 7
8. }
In the second case, the queue contains more than one element. The condition front = NULL
becomes false. In this scenario, we need to update the end pointer rear so that the next
pointer of rear will point to the new node ptr. Since, this is a linked queue, hence we also need
to make the rear pointer point to the newly added node ptr. We also need to make the next
pointer of rear point to NULL.
1. rear -> next = ptr;
2. rear = ptr;
3. rear->next = NULL;
In this way, the element is inserted into the queue. The algorithm and the C implementation is
given as follows.
Algorithm
o Step 1: Allocate the space for the new node PTR
o Step 2: SET PTR -> DATA = VAL
o Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
o Step 4: END
C Function
1. void insert(struct node *ptr, int item; )
2. {
3.
4.
5. ptr = (struct node *) malloc (sizeof(struct node));
6. if(ptr == NULL)
7. {
8. printf("\nOVERFLOW\n");
9. return;
10. }
11. else
12. {
13. ptr -> data = item;
14. if(front == NULL)
15. {
16. front = ptr;

DIWAKAR EDUCATION HUB Page 70


DATA STRUCTURES AND ALGORITHMS UNIT – 7
17. rear = ptr;
18. front -> next = NULL;
19. rear -> next = NULL;
20. }
21. else
22. {
23. rear -> next = ptr;
24. rear = ptr;
25. rear->next = NULL;
26. }
27. }
28. }
Deletion
Deletion operation removes the element that is first inserted among all the queue elements.
Firstly, we need to check either the list is empty or not. The condition front == NULL becomes
true if the list is empty, in this case , we simply write underflow on the console and make exit.
Otherwise, we will delete the element that is pointed by the pointer front. For this purpose,
copy the node pointed by the front pointer into the pointer ptr. Now, shift the front pointer,
point to its next node and free the node pointed by the node ptr. This is done by using the
following statements.
1. ptr = front;
2. front = front -> next;
3. free(ptr);
The algorithm and C function is given as follows.
Algorithm
o Step 1: IF FRONT = NULL
Write " Underflow "
Go to Step 5
[END OF IF]
o Step 2: SET PTR = FRONT
o Step 3: SET FRONT = FRONT -> NEXT
o Step 4: FREE PTR
o Step 5: END
C Function
1. void delete (struct node *ptr)
2. {
3. if(front == NULL)
4. {
5. printf("\nUNDERFLOW\n");
6. return;
DIWAKAR EDUCATION HUB Page 71
DATA STRUCTURES AND ALGORITHMS UNIT – 7
7. }
8. else
9. {
10. ptr = front;
11. front = front -> next;
12. free(ptr);
13. }
14. }

Circular Queue
Deletions and insertions can only be performed at front and rear end respectively, as far as
linear queue is concerned.
Consider the queue shown in the following figure.

The Queue shown in above figure is completely filled and there can't be inserted any more
element due to the condition rear == max - 1 becomes true.
However, if we delete 2 elements at the front end of the queue, we still can not insert any
element since the condition rear = max -1 still holds.
This is the main problem with the linear queue, although we have space available in the array,
but we can not insert any more element in the queue. This is simply the memory wastage and
we need to overcome this problem.

DIWAKAR EDUCATION HUB Page 72


DATA STRUCTURES AND ALGORITHMS UNIT – 7
One of the solution of this problem is circular queue. In the circular queue, the first index
comes right after the last index. You can think of a circular queue as shown in the following
figure.

Circular queue will be full when front = -1 and rear = max-1. Implementation of circular queue
is similar to that of a linear queue. Only the logic part that is implemented in the case of
insertion and deletion is different from that in a linear queue.
Complexity
Time Complexity

Front O(1)

Rear O(1)

enQueue() O(1)

deQueue() O(1)

Insertion in Circular queue


There are three scenario of inserting an element in a queue.
1. If (rear + 1)%maxsize = front, the queue is full. In that case, overflow occurs and
therefore, insertion can not be performed in the queue.
2. If rear != max - 1, then rear will be incremented to the mod(maxsize) and the new value
will be inserted at the rear end of the queue.
3. If front != 0 and rear = max - 1, then it means that queue is not full therefore, set the
value of rear to 0 and insert the new element there.
Algorithm to insert an element in circular queue
o Step 1: IF (REAR+1)%MAX = FRONT
Write " OVERFLOW "
Goto step 4
[End OF IF]

DIWAKAR EDUCATION HUB Page 73


DATA STRUCTURES AND ALGORITHMS UNIT – 7
o Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE IF REAR = MAX - 1 and FRONT ! = 0
SET REAR = 0
ELSE
SET REAR = (REAR + 1) % MAX
[END OF IF]
o Step 3: SET QUEUE[REAR] = VAL
o Step 4: EXIT
C Function
1. void insert(int item, int queue[])
2. {
3. if((rear+1)%maxsize == front)
4. {
5. printf("\nOVERFLOW");
6. return;
7. }
8. else if(front == -1 && rear == -1)
9. {
10. front = 0;
11. rear = 0;
12. }
13. else if(rear == maxsize -1 && front != 0)
14. {
15. rear = 0;
16. }
17. else
18. {
19. rear = (rear+1)%maxsize;
20. }
21. queue[rear] = item;
22. }
Algorithm to delete an element from a circular queue
To delete an element from the circular queue, we must check for the three following
conditions.
1. If front = -1, then there are no elements in the queue and therefore this will be the case
of an underflow condition.
2. If there is only one element in the queue, in this case, the condition rear = front holds
and therefore, both are set to -1 and the queue is deleted completely.

DIWAKAR EDUCATION HUB Page 74


DATA STRUCTURES AND ALGORITHMS UNIT – 7
3. If front = max -1 then, the value is deleted from the front end the value of front is set to
0.
4. Otherwise, the value of front is incremented by 1 and then delete the element at the
front end.
Algorithm
o Step 1: IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
[END of IF]
o Step 2: SET VAL = QUEUE[FRONT]
o Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
o Step 4: EXIT
Tree
o A Tree is a recursive data structure containing the set of one or more data nodes where
one node is designated as the root of the tree while the remaining nodes are called as
the children of the root.
o The nodes other than the root node are partitioned into the non empty sets where each
one of them is to be called sub-tree.
o Nodes of a tree either maintain a parent-child relationship between them or they are
sister nodes.
o In a general tree, A node can have any number of children nodes but it can have only a
single parent.
o The following image shows a tree, where the node A is the root node of the tree while
the other nodes can be seen as the children of A.

DIWAKAR EDUCATION HUB Page 75


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Basic terminology
o Root Node :- The root node is the topmost node in the tree hierarchy. In other words,
the root node is the one which doesn't have any parent.
o Sub Tree :- If the root node is not null, the tree T1, T2 and T3 is called sub-trees of the
root node.
o Leaf Node :- The node of tree, which doesn't have any child node, is called leaf node.
Leaf node is the bottom most node of the tree. There can be any number of leaf nodes
present in a general tree. Leaf nodes can also be called external nodes.
o Path :- The sequence of consecutive edges is called path. In the tree shown in the above
image, path to the node E is A→ B → E.
o Ancestor node :- An ancestor of a node is any predecessor node on a path from root to
that node. The root node doesn't have any ancestors. In the tree shown in the above
image, the node F have the ancestors, B and A.
o Degree :- Degree of a node is equal to number of children, a node have. In the tree
shown in the above image, the degree of node B is 2. Degree of a leaf node is always 0
while in a complete binary tree, degree of each node is equal to 2.
o Level Number :- Each node of the tree is assigned a level number in such a way that
each node is present at one level higher than its parent. Root node of the tree is always
present at level 0.
Static representation of tree
1. #define MAXNODE 500
2. struct treenode {
3. int root;
4. int father;
5. int son;
6. int next;
7. }

DIWAKAR EDUCATION HUB Page 76


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Dynamic representation of tree
1. struct treenode
2. {
3. int root;
4. struct treenode *father;
5. struct treenode *son
6. struct treenode *next;
7. }
Types of Tree
The tree data structure can be classified into six different categories.

General Tree
General Tree stores the elements in a hierarchical order in which the top level element is
always present at level 0 as the root element. All the nodes except the root node are present
at number of levels. The nodes which are present on the same level are called siblings while
the nodes which are present on the different levels exhibit the parent-child relationship
among them. A node may contain any number of sub-trees. The tree in which each node
contain 3 sub-tree, is called ternary tree.
Forests
Forest can be defined as the set of disjoint trees which can be obtained by deleting the root
node and the edges which connects root node to the first level node.

DIWAKAR EDUCATION HUB Page 77


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Binary Tree
Binary tree is a data structure in which each node can have at most 2 children. The node
present at the top most level is called the root node. A node with the 0 children is called leaf
node. Binary Trees are used in the applications like expression evaluation and many more. We
will discuss binary tree in detail, later in this tutorial.
Binary Search Tree
Binary search tree is an ordered binary tree. All the elements in the left sub-tree are less than
the root while elements present in the right sub-tree are greater than or equal to the root
node element. Binary search trees are used in most of the applications of computer science
domain like searching, sorting, etc.
Expression Tree
Expression trees are used to evaluate the simple arithmetic expressions. Expression tree is
basically a binary tree where internal nodes are represented by operators while the leaf nodes
are represented by operands. Expression trees are widely used to solve algebraic expressions
like (a+b)*(a-b). Consider the following example.
Q. Construct an expression tree by using the following algebraic expression.
(a + b) / (a*b - c) + d

DIWAKAR EDUCATION HUB Page 78


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Tournament Tree
Tournament tree are used to record the winner of the match in each round being played
between two players. Tournament tree can also be called as selection tree or winner tree.
External nodes represent the players among which a match is being played while the internal
nodes represent the winner of the match played. At the top most level, the winner of the
tournament is present as the root node of the tree.
For example, tree .of a chess tournament being played among 4 players is shown as follows.
However, the winner in the left sub-tree will play against the winner of right sub-tree.

Binary Tree
Binary Tree is a special type of generic tree in which, each node can have at most two children.
Binary tree is generally partitioned into three disjoint subsets.
1. Root of the node
2. left sub-tree which is also a binary tree.
3. Right binary sub-tree
A binary Tree is shown in the following image.

DIWAKAR EDUCATION HUB Page 79


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Types of Binary Tree


1. Strictly Binary Tree
In Strictly Binary Tree, every non-leaf node contain non-empty left and right sub-trees. In other
words, the degree of every non-leaf node will always be 2. A strictly binary tree with n leaves,
will have (2n - 1) nodes.
A strictly binary tree is shown in the following figure.

2. Complete Binary Tree


A Binary Tree is said to be a complete binary tree if all of the leaves are located at the same
level d. A complete binary tree is a binary tree that contains exactly 2^l nodes at each level
between level 0 and d. The total number of nodes in a complete binary tree with depth d is
2d+1-1 where leaf nodes are 2d while non-leaf nodes are 2d-1.

DIWAKAR EDUCATION HUB Page 80


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Binary Tree Traversal

SN Traversal Description

1 Pre-order Traverse the root first then traverse into the left sub-
Traversal tree and right sub-tree respectively. This procedure will
be applied to each sub-tree of the tree recursively.

2 In-order Traverse the left sub-tree first, and then traverse the
Traversal root and the right sub-tree respectively. This procedure
will be applied to each sub-tree of the tree recursively.

3 Post-order Traverse the left sub-tree and then traverse the right
Traversal sub-tree and root respectively. This procedure will be
applied to each sub-tree of the tree recursively.

Binary Tree representation


There are two types of representation of a binary tree:
1. Linked Representation
In this representation, the binary tree is stored in the memory, in the form of a linked list
where the number of nodes are stored at non-contiguous memory locations and linked
together by inheriting parent child relationship like a tree. every node contains three parts :
pointer to the left node, data element and pointer to the right node. Each binary tree has a
root pointer which points to the root node of the binary tree. In an empty binary tree, the root
pointer will point to null.
DIWAKAR EDUCATION HUB Page 81
DATA STRUCTURES AND ALGORITHMS UNIT – 7
Consider the binary tree given in the figure below.

In the above figure, a tree is seen as the collection of nodes where each node contains three
parts : left pointer, data element and right pointer. Left pointer stores the address of the left
child while the right pointer stores the address of the right child. The leaf node contains null in
its left and right pointers.
The following image shows about how the memory will be allocated for the binary tree by
using linked representation. There is a special pointer maintained in the memory which points
to the root node of the tree. Every node in the tree contains the address of its left and right
child. Leaf node contains null in its left and right pointers.

2. Sequential Representation
This is the simplest memory allocation technique to store the tree elements but it is an
inefficient technique since it requires a lot of space to store the tree elements. A binary tree is
shown in the following figure along with its memory allocation.

DIWAKAR EDUCATION HUB Page 82


DATA STRUCTURES AND ALGORITHMS UNIT – 7

In this representation, an array is used to store the tree elements. Size of the array will be
equal to the number of nodes present in the tree. The root node of the tree will be present at
the 1st index of the array. If a node is stored at ith index then its left and right children will be
stored at 2i and 2i+1 location. If the 1st index of the array i.e. tree[1] is 0, it means that the tree
is empty.
Binary Search Tree
1. Binary Search tree can be defined as a class of binary trees, in which the nodes are
arranged in a specific order. This is also called ordered binary tree.
2. In a binary search tree, the value of all the nodes in the left sub-tree is less than the
value of the root.
3. Similarly, value of all the nodes in the right sub-tree is greater than or equal to the value
of the root.
4. This rule will be recursively applied to all the left and right sub-trees of the root.

DIWAKAR EDUCATION HUB Page 83


DATA STRUCTURES AND ALGORITHMS UNIT – 7

A Binary search tree is shown in the above figure. As the constraint applied on the BST, we can
see that the root node 30 doesn't contain any value greater than or equal to 30 in its left sub-
tree and it also doesn't contain any value less than 30 in its right sub-tree.
Advantages of using binary search tree
1. Searching become very efficient in a binary search tree since, we get a hint at each step,
about which sub-tree contains the desired element.
2. The binary search tree is considered as efficient data structure in compare to arrays and
linked lists. In searching process, it removes half sub-tree at every step. Searching for an
element in a binary search tree takes o(log 2n) time. In worst case, the time it takes to
search an element is 0(n).
3. It also speed up the insertion and deletion operations as compare to that in array and
linked list.
Q. Create the binary search tree using the following data elements.
43, 10, 79, 90, 12, 54, 11, 9, 50
1. Insert 43 into the tree as the root of the tree.
2. Read the next element, if it is lesser than the root node element, insert it as the root of
the left sub-tree.
3. Otherwise, insert it as the root of the right of the right sub-tree.

DIWAKAR EDUCATION HUB Page 84


DATA STRUCTURES AND ALGORITHMS UNIT – 7
The process of creating BST by using the given elements, is shown in the image below.

Operations on Binary Search Tree


There are many operations which can be performed on a binary search tree.

SN Operation Description

1 Searching in Finding the location of some specific element in a binary search

DIWAKAR EDUCATION HUB Page 85


DATA STRUCTURES AND ALGORITHMS UNIT – 7

BST tree.

2 Insertion in Adding a new element to the binary search tree at the appropriate
BST location so that the property of BST do not violate.

3 Deletion in Deleting some specific node from a binary search tree. However,
BST there can be various cases in deletion depending upon the number
of children, the node have.

AVL Tree
AVL Tree is invented by GM Adelson - Velsky and EM Landis in 1962. The tree is named AVL in
honour of its inventors.
AVL Tree can be defined as height balanced binary search tree in which each node is
associated with a balance factor which is calculated by subtracting the height of its right sub-
tree from that of its left sub-tree.
Tree is said to be balanced if balance factor of each node is in between -1 to 1, otherwise, the
tree will be unbalanced and need to be balanced.
Balance Factor (k) = height (left(k)) - height (right(k))
If balance factor of any node is 1, it means that the left sub-tree is one level higher than the
right sub-tree.
If balance factor of any node is 0, it means that the left sub-tree and right sub-tree contain
equal height.
If balance factor of any node is -1, it means that the left sub-tree is one level lower than the
right sub-tree.
An AVL tree is given in the following figure. We can see that, balance factor associated with
each node is in between -1 and +1. therefore, it is an example of AVL tree.

DIWAKAR EDUCATION HUB Page 86


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Complexity

Algorithm Average case Worst case

Space o(n) o(n)

Search o(log n) o(log n)

Insert o(log n) o(log n)

Delete o(log n) o(log n)

Operations on AVL tree


Due to the fact that, AVL tree is also a binary search tree therefore, all the operations are
performed in the same way as they are performed in a binary search tree. Searching and
traversing do not lead to the violation in property of AVL tree. However, insertion and deletion
are the operations which can violate this property and therefore, they need to be revisited.

SN Operation Description

DIWAKAR EDUCATION HUB Page 87


DATA STRUCTURES AND ALGORITHMS UNIT – 7

1 Insertion Insertion in AVL tree is performed in the same way as it is performed


in a binary search tree. However, it may lead to violation in the AVL
tree property and therefore the tree may need balancing. The tree
can be balanced by applying rotations.

2 Deletion Deletion can also be performed in the same way as it is performed in


a binary search tree. Deletion may also disturb the balance of the
tree therefore, various types of rotations are used to rebalance the
tree.

Why AVL Tree ?


AVL tree controls the height of the binary search tree by not letting it to be skewed. The time
taken for all operations in a binary search tree of height h is O(h). However, it can be extended
to O(n) if the BST becomes skewed (i.e. worst case). By limiting this height to log n, AVL tree
imposes an upper bound on each operation to be O(log n) where n is the number of nodes.
B Tree
B Tree is a specialized m-way tree that can be widely used for disk access. A B-Tree of order m
can have at most m-1 keys and m children. One of the main reason of using B tree is its
capability to store large number of keys in a single node and large key values by keeping the
height of the tree relatively small.
A B tree of order m contains all the properties of an M way tree. In addition, it contains the
following properties.
1. Every node in a B-Tree contains at most m children.
2. Every node in a B-Tree except the root node and the leaf node contain at least m/2
children.
3. The root nodes must have at least 2 nodes.
4. All leaf nodes must be at the same level.
It is not necessary that, all the nodes contain the same number of children but, each node
must have m/2 number of nodes.
A B tree of order 4 is shown in the following image.

DIWAKAR EDUCATION HUB Page 88


DATA STRUCTURES AND ALGORITHMS UNIT – 7
While performing some operations on B Tree, any property of B Tree may violate such as
number of minimum children a node can have. To maintain the properties of B Tree, the tree
may split or join.
Operations
Searching :
Searching in B Trees is similar to that in Binary search tree. For example, if we search for an
item 49 in the following B Tree. The process will something like following :
1. Compare item 49 with root node 78. since 49 < 78 hence, move to its left sub-tree.
2. Since, 40<49<56, traverse right sub-tree of 40.
3. 49>45, move to right. Compare 49.
4. match found, return.
Searching in a B tree depends upon the height of the tree. The search algorithm takes O(log n)
time to search any element in a B tree.

Inserting
Insertions are done at the leaf node level. The following algorithm needs to be followed in
order to insert an item into B Tree.
1. Traverse the B Tree in order to find the appropriate leaf node at which the node can be
inserted.
2. If the leaf node contain less than m-1 keys then insert the element in the increasing
order.
3. Else, if the leaf node contains m-1 keys, then follow the following steps.
o Insert the new element in the increasing order of elements.
o Split the node into the two nodes at the median.
o Push the median element upto its parent node.
o If the parent node also contain m-1 number of keys, then split it too by following
the same steps.
Example:
Insert the node 8 into the B Tree of order 5 shown in the following image.

DIWAKAR EDUCATION HUB Page 89


DATA STRUCTURES AND ALGORITHMS UNIT – 7

8 will be inserted to the right of 5, therefore insert 8.

The node, now contain 5 keys which is greater than (5 -1 = 4 ) keys. Therefore split the node
from the median i.e. 8 and push it up to its parent node shown as follows.

Deletion
Deletion is also performed at the leaf nodes. The node which is to be deleted can either be a
leaf node or an internal node. Following algorithm needs to be followed in order to delete a
node from a B tree.
1. Locate the leaf node.

DIWAKAR EDUCATION HUB Page 90


DATA STRUCTURES AND ALGORITHMS UNIT – 7
2. If there are more than m/2 keys in the leaf node then delete the desired key from the
node.
3. If the leaf node doesn't contain m/2 keys then complete the keys by taking the element
from eight or left sibling.
o If the left sibling contains more than m/2 elements then push its largest element
up to its parent and move the intervening element down to the node where the
key is deleted.
o If the right sibling contains more than m/2 elements then push its smallest
element up to the parent and move intervening element down to the node where
the key is deleted.
4. If neither of the sibling contain more than m/2 elements then create a new leaf node by
joining two leaf nodes and the intervening element of the parent node.
5. If parent is left with less than m/2 nodes then, apply the above process on the parent
too.
If the the node which is to be deleted is an internal node, then replace the node with its in-
order successor or predecessor. Since, successor or predecessor will always be on the leaf
node hence, the process will be similar as the node is being deleted from the leaf node.
Example 1
Delete the node 53 from the B Tree of order 5 shown in the following figure.

53 is present in the right child of element 49. Delete it.

DIWAKAR EDUCATION HUB Page 91


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Now, 57 is the only element which is left in the node, the minimum number of elements that
must be present in a B tree of order 5, is 2. it is less than that, the elements in its left and right
sub-tree are also not sufficient therefore, merge it with the left sibling and intervening
element of parent i.e. 49.
The final B tree is shown as follows.

Application of B tree
B tree is used to index the data and provides fast access to the actual data stored on the disks
since, the access to value stored in a large database that is stored on a disk is a very time
consuming process.
Searching an un-indexed and unsorted database containing n key values needs O(n) running
time in worst case. However, if we use B Tree to index this database, it will be searched in
O(log n) time in worst case.
B+ Tree
B+ Tree is an extension of B Tree which allows efficient insertion, deletion and search
operations.

DIWAKAR EDUCATION HUB Page 92


DATA STRUCTURES AND ALGORITHMS UNIT – 7
In B Tree, Keys and records both can be stored in the internal as well as leaf nodes. Whereas,
in B+ tree, records (data) can only be stored on the leaf nodes while internal nodes can only
store the key values.
The leaf nodes of a B+ tree are linked together in the form of a singly linked lists to make the
search queries more efficient.
B+ Tree are used to store the large amount of data which can not be stored in the main
memory. Due to the fact that, size of main memory is always limited, the internal nodes (keys
to access records) of the B+ tree are stored in the main memory whereas, leaf nodes are
stored in the secondary memory.
The internal nodes of B+ tree are often called index nodes. A B+ tree of order 3 is shown in the
following figure.

Advantages of B+ Tree
1. Records can be fetched in equal number of disk accesses.
2. Height of the tree remains balanced and less as compare to B tree.
3. We can access the data stored in a B+ tree sequentially as well as directly.
4. Keys are used for indexing.
5. Faster search queries as the data is stored only on the leaf nodes.

DIWAKAR EDUCATION HUB Page 93


DATA STRUCTURES AND ALGORITHMS UNIT – 7

B Tree VS B+ Tree

SN B Tree B+ Tree

1 Search keys can not be repeatedly Redundant search keys can be present.
stored.

2 Data can be stored in leaf nodes as well Data can only be stored on the leaf
as internal nodes nodes.

3 Searching for some data is a slower Searching is comparatively faster as


process since data can be found on data can only be found on the leaf
internal nodes as well as on the leaf nodes.
nodes.

4 Deletion of internal nodes are so Deletion will never be a complexed


complicated and time consuming. process since element will always be
deleted from the leaf nodes.

DIWAKAR EDUCATION HUB Page 94


DATA STRUCTURES AND ALGORITHMS UNIT – 7

5 Leaf nodes can not be linked together. Leaf nodes are linked together to
make the search operations more
efficient.

Insertion in B+ Tree
Step 1: Insert the new node as a leaf node
Step 2: If the leaf doesn't have required space, split the node and copy the middle node to the
next index node.
Step 3: If the index node doesn't have required space, split the node and copy the middle
element to the next index page.
Example :
Insert the value 195 into the B+ tree of order 5 shown in the following figure.

195 will be inserted in the right sub-tree of 120 after 190. Insert it at the desired position.

The node contains greater than the maximum number of elements i.e. 4, therefore split it and
place the median node up to the parent.

DIWAKAR EDUCATION HUB Page 95


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Now, the index node contains 6 children and 5 keys which violates the B+ tree properties,
therefore we need to split it, shown as follows.

Deletion in B+ Tree
Step 1: Delete the key and data from the leaves.
Step 2: if the leaf node contains less than minimum number of elements, merge down the
node with its sibling and delete the key in between them.
Step 3: if the index node contains less than minimum number of elements, merge the node
with the sibling and move down the key in between them.
Example
Delete the key 200 from the B+ Tree shown in the following figure.

200 is present in the right sub-tree of 190, after 195. delete it.

DIWAKAR EDUCATION HUB Page 96


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Merge the two nodes by using 195, 190, 154 and 129.

Now, element 120 is the single element present in the node which is violating the B+ Tree
properties. Therefore, we need to merge it by using 60, 78, 108 and 120.
Now, the height of B+ tree will be decreased by 1.

Graph
A graph can be defined as group of vertices and edges that are used to connect these vertices.
A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any complex
relationship among them instead of having parent child relationship.
Definition

DIWAKAR EDUCATION HUB Page 97


DATA STRUCTURES AND ALGORITHMS UNIT – 7
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices
and E(G) represents the set of edges which are used to connect these vertices.
A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E), (E,D), (D,B),
(D,A)) is shown in the following figure.

Directed and Undirected Graph


A graph can be directed or undirected. However, in an undirected graph, edges are not
associated with the directions with them. An undirected graph is shown in the above figure
since its edges are not attached with any of the directions. If an edge exists between vertex A
and B then the vertices can be traversed from B to A as well as A to B.
In a directed graph, edges form an ordered pair. Edges represent a specific path from some
vertex A to another vertex B. Node A is called initial node while node B is called terminal node.
A directed graph is shown in the following figure.

Graph Terminology
Path
A path can be defined as the sequence of nodes that are followed in order to reach some
terminal node V from the initial node U.
Closed Path

DIWAKAR EDUCATION HUB Page 98


DATA STRUCTURES AND ALGORITHMS UNIT – 7
A path will be called as closed path if the initial node is same as terminal node. A path will be
closed path if V0=VN.
Simple Path
If all the nodes of the graph are distinct with an exception V 0=VN, then such path P is called as
closed simple path.
Cycle
A cycle can be defined as the path which has no repeated edges or vertices except the first and
last vertices.
Connected Graph
A connected graph is the one in which some path exists between every two vertices (u, v) in V.
There are no isolated nodes in connected graph.
Complete Graph
A complete graph is the one in which every node is connected with all other nodes. A
complete graph contain n(n-1)/2 edges where n is the number of nodes in the graph.
Weighted Graph
In a weighted graph, each edge is assigned with some data such as length or weight. The
weight of an edge e can be given as w(e) which must be a positive (+) value indicating the cost
of traversing the edge.
Digraph
A digraph is a directed graph in which each edge of the graph is associated with some direction
and the traversing can be done only in the specified direction.
Loop
An edge that is associated with the similar end points can be called as Loop.
Adjacent Nodes
If two nodes u and v are connected via an edge e, then the nodes u and v are called as
neighbours or adjacent nodes.
Degree of the Node
A degree of a node is the number of edges that are connected with that node. A node with
degree 0 is called as isolated node.

Graph Representation
By Graph representation, we simply mean the technique which is to be used in order to store
some graph into the computer's memory.
There are two ways to store Graph into the computer's memory. In this part of this tutorial,
we discuss each one of them in detail.
1. Sequential Representation
In sequential representation, we use adjacency matrix to store the mapping represented by
vertices and edges. In adjacency matrix, the rows and columns are represented by the graph
vertices. A graph having n vertices, will have a dimension n x n.

DIWAKAR EDUCATION HUB Page 99


DATA STRUCTURES AND ALGORITHMS UNIT – 7
An entry Mij in the adjacency matrix representation of an undirected graph G will be 1 if there
exists an edge between Vi and Vj.
An undirected graph and its adjacency matrix representation is shown in the following figure.

in the above figure, we can see the mapping among the vertices (A, B, C, D, E) is represented
by using the adjacency matrix which is also shown in the figure.
There exists different adjacency matrices for the directed and undirected graph. In directed
graph, an entry Aij will be 1 only when there is an edge directed from V i to Vj.
A directed graph and its adjacency matrix representation is shown in the following figure.

Representation of weighted directed graph is different. Instead of filling the entry by 1, the
Non- zero entries of the adjacency matrix are represented by the weight of respective edges.
The weighted directed graph along with the adjacency matrix representation is shown in the
following figure.

DIWAKAR EDUCATION HUB Page 100


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Linked Representation
In the linked representation, an adjacency list is used to store the Graph into the computer's
memory.
Consider the undirected graph shown in the following figure and check the adjacency list
representation.

An adjacency list is maintained for each node present in the graph which stores the node value
and a pointer to the next adjacent node to the respective node. If all the adjacent nodes are
traversed then store the NULL in the pointer field of last node of the list. The sum of the
lengths of adjacency lists is equal to the twice of the number of edges present in an undirected
graph.
Consider the directed graph shown in the following figure and check the adjacency list
representation of the graph.

DIWAKAR EDUCATION HUB Page 101


DATA STRUCTURES AND ALGORITHMS UNIT – 7

In a directed graph, the sum of lengths of all the adjacency lists is equal to the number of
edges present in the graph.
In the case of weighted directed graph, each node contains an extra field that is called the
weight of the node. The adjacency list representation of a directed graph is shown in the
following figure.

Graph Traversal Algorithm


In this part of the tutorial we will discuss the techniques by using which, we can traverse all
the vertices of the graph.
Traversing the graph means examining all the nodes and vertices of the graph. There are two
standard methods by using which, we can traverse the graphs. Lets discuss each one of them
in detail.
o Breadth First Search
o Depth First Search
Breadth First Search (BFS) Algorithm
Breadth first search is a graph traversal algorithm that starts traversing the graph from root
node and explores all the neighbouring nodes. Then, it selects the nearest node and explore all

DIWAKAR EDUCATION HUB Page 102


DATA STRUCTURES AND ALGORITHMS UNIT – 7
the unexplored nodes. The algorithm follows the same process for each of the nearest node
until it finds the goal.
The algorithm of breadth first search is given below. The algorithm starts with examining the
node A and all of its neighbours. In the next step, the neighbours of the nearest node of A are
explored and process continues in the further steps. The algorithm explores all neighbours of
all the nodes and ensures that each node is visited exactly once and no node is visited twice.
Algorithm
o Step 1: SET STATUS = 1 (ready state)
for each node in G
o Step 2: Enqueue the starting node A
and set its STATUS = 2
(waiting state)
o Step 3: Repeat Steps 4 and 5 until
QUEUE is empty
o Step 4: Dequeue a node N. Process it
and set its STATUS = 3
(processed state).
o Step 5: Enqueue all the neighbours of
N that are in the ready state
(whose STATUS = 1) and set
their STATUS = 2
(waiting state)
[END OF LOOP]
o Step 6: EXIT
Example
Consider the graph G shown in the following image, calculate the minimum path p from node
A to node E. Given that each edge has a length of 1.

Solution:

DIWAKAR EDUCATION HUB Page 103


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Minimum Path P can be found by applying breadth first search algorithm that will begin at
node A and will end at E. the algorithm uses two queues,
namely QUEUE1 and QUEUE2. QUEUE1 holds all the nodes that are to be processed
while QUEUE2 holds all the nodes that are processed and deleted from QUEUE1.
Lets start examining the graph from Node A.
1. Add A to QUEUE1 and NULL to QUEUE2.
1. QUEUE1 = {A}
2. QUEUE2 = {NULL}
2. Delete the Node A from QUEUE1 and insert all its neighbours. Insert Node A into QUEUE2
1. QUEUE1 = {B, D}
2. QUEUE2 = {A}
3. Delete the node B from QUEUE1 and insert all its neighbours. Insert node B into QUEUE2.
1. QUEUE1 = {D, C, F}
2. QUEUE2 = {A, B}
4. Delete the node D from QUEUE1 and insert all its neighbours. Since F is the only neighbour
of it which has been inserted, we will not insert it again. Insert node D into QUEUE2.
1. QUEUE1 = {C, F}
2. QUEUE2 = { A, B, D}
5. Delete the node C from QUEUE1 and insert all its neighbours. Add node C to QUEUE2.
1. QUEUE1 = {F, E, G}
2. QUEUE2 = {A, B, D, C}
6. Remove F from QUEUE1 and add all its neighbours. Since all of its neighbours has already
been added, we will not add them again. Add node F to QUEUE2.
1. QUEUE1 = {E, G}
2. QUEUE2 = {A, B, D, C, F}
7. Remove E from QUEUE1, all of E's neighbours has already been added to QUEUE1 therefore
we will not add them again. All the nodes are visited and the target node i.e. E is encountered
into QUEUE2.
1. QUEUE1 = {G}
2. QUEUE2 = {A, B, D, C, F, E}
Now, backtrack from E to A, using the nodes available in QUEUE2.
The minimum path will be A → B → C → E.
Depth First Search (DFS) Algorithm
Depth first search (DFS) algorithm starts with the initial node of the graph G, and then goes to
deeper and deeper until we find the goal node or the node which has no children. The
algorithm, then backtracks from the dead end towards the most recent node that is yet to be
completely unexplored.
The data structure which is being used in DFS is stack. The process is similar to BFS algorithm.
In DFS, the edges that leads to an unvisited node are called discovery edges while the edges
that leads to an already visited node are called block edges.

DIWAKAR EDUCATION HUB Page 104


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Algorithm
o Step 1: SET STATUS = 1 (ready state) for each node in G
o Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
o Step 3: Repeat Steps 4 and 5 until STACK is empty
o Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
o Step 5: Push on the stack all the neighbours of N that are in the ready state (whose
STATUS = 1) and set their
STATUS = 2 (waiting state)
[END OF LOOP]
o Step 6: EXIT
Example :
Consider the graph G along with its adjacency list, given in the figure below. Calculate the
order to print all the nodes of the graph starting from node H, by using depth first search (DFS)
algorithm.

Solution :
Push H onto the stack
1. STACK : H
POP the top element of the stack i.e. H, print it and push all the neighbours of H onto the stack
that are is ready state.
1. Print H
2. STACK : A
Pop the top element of the stack i.e. A, print it and push all the neighbours of A onto the stack
that are in ready state.
1. Print A
2. Stack : B, D

DIWAKAR EDUCATION HUB Page 105


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Pop the top element of the stack i.e. D, print it and push all the neighbours of D onto the stack
that are in ready state.
1. Print D
2. Stack : B, F
Pop the top element of the stack i.e. F, print it and push all the neighbours of F onto the stack
that are in ready state.
1. Print F
2. Stack : B
Pop the top of the stack i.e. B and push all the neighbours
1. Print B
2. Stack : C
Pop the top of the stack i.e. C and push all the neighbours.
1. Print C
2. Stack : E, G
Pop the top of the stack i.e. G and push all its neighbours.
1. Print G
2. Stack : E
Pop the top of the stack i.e. E and push all its neighbours.
1. Print E
2. Stack :
Hence, the stack now becomes empty and all the nodes of the graph have been traversed.
The printing sequence of the graph will be :
1. H → A → D → F → B → C → G → E
Spanning Tree
Spanning tree can be defined as a sub-graph of connected, undirected graph G that is a
tree produced by removing the desired number of edges from a graph. In other words,
Spanning tree is a non-cyclic sub-graph of a connected and undirected graph G that
connects all the vertices together. A graph G can have multiple spanning trees.
Minimum Spanning Tree
There can be weights assigned to every edge in a weighted graph. However, A minimum
spanning tree is a spanning tree which has minimal total weight. In other words,
minimum spanning tree is the one which contains the least weight among all other
spanning tree of some particular graph.
Shortest path algorithms
In this section, algorithms will be discussed to calculate the shortest path between two
nodes in a graph.
There are two algorithms which are being used for this purpose.
Prim's Algorithm

DIWAKAR EDUCATION HUB Page 106


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Prim's Algorithm is used to find the minimum spanning tree from a graph. Prim's
algorithm finds the subset of edges that includes every vertex of the graph such that the
sum of the weights of the edges can be minimized.
Prim's algorithm starts with the single node and explore all the adjacent nodes with all
the connecting edges at every step. The edges with the minimal weights causing no
cycles in the graph got selected.
The algorithm is given as follows.
Algorithm
o Step 1: Select a starting vertex
o Step 2: Repeat Steps 3 and 4 until there are fringe vertices
o Step 3: Select an edge e connecting the tree vertex and fringe vertex that has minimum
weight
o Step 4: Add the selected edge and the vertex to the minimum spanning tree T
[END OF LOOP]
o Step 5: EXIT
Example :
Construct a minimum spanning tree of the graph given in the following figure by using
prim's algorithm.

Solution
o Step 1 : Choose a starting vertex B.
o Step 2: Add the vertices that are adjacent to A. the edges that connecting the vertices
are shown by dotted lines.
o Step 3: Choose the edge with the minimum weight among all. i.e. BD and add it to MST.
Add the adjacent vertices of D i.e. C and E.
o Step 3: Choose the edge with the minimum weight among all. In this case, the edges DE
and CD are such edges. Add them to MST and explore the adjacent of C i.e. E and A.
o Step 4: Choose the edge with the minimum weight i.e. CA. We can't choose CE as it
would cause cycle in the graph.
The graph produces in the step 4 is the minimum spanning tree of the graph shown in
the above figure.
The cost of MST will be calculated as;

DIWAKAR EDUCATION HUB Page 107


DATA STRUCTURES AND ALGORITHMS UNIT – 7
cost(MST) = 4 + 2 + 1 + 3 = 10 units.

Kruskal's Algorithm
Kruskal's Algorithm is used to find the minimum spanning tree for a connected weighted
graph. The main target of the algorithm is to find the subset of edges by using which, we
can traverse every vertex of the graph. Kruskal's algorithm follows greedy approach
which finds an optimum solution at every stage instead of focusing on a global
optimum.
The Kruskal's algorithm is given as follows.
Algorithm
o Step 1: Create a forest in such a way that each graph is a separate tree.
o Step 2: Create a priority queue Q that contains all the edges of the graph.
o Step 3: Repeat Steps 4 and 5 while Q is NOT EMPTY
o Step 4: Remove an edge from Q
o Step 5: IF the edge obtained in Step 4 connects two different trees, then Add it to the
forest (for combining two trees into one tree).
ELSE
Discard the edge
o Step 6: END
Example :
Apply the Kruskal's algorithm on the graph given as follows.

DIWAKAR EDUCATION HUB Page 108


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Solution:
the weight of the edges given as :

Ed A A A A B C D
ge E D C B C D E

Wei 5 10 7 1 3 4 2
ght

Sort the edges according to their weights.

Ed A D B C A A A
ge B E C D E C D

Wei 1 2 3 4 5 7 10
ght

Start constructing the tree;


Add AB to the MST;

Add DE to the MST;

DIWAKAR EDUCATION HUB Page 109


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Add BC to the MST;

The next step is to add AE, but we can't add that as it will cause a cycle.
The next edge to be added is AC, but it can't be added as it will cause a cycle.
The next edge to be added is AD, but it can't be added as it will contain a cycle.
Hence, the final MST is the one which is shown in the step 4.
the cost of MST = 1 + 2 + 3 + 4 = 10.
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list elements according to a
comparison operator on the elements. The comparison operator is used to decide the new
order of element in the respective data structure.
Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to
arrange data in a particular order. Most common orders are in numerical or lexicographical
order.
The importance of sorting lies in the fact that data searching can be optimized to a very high
level, if data is stored in a sorted manner. Sorting is also used to represent data in more
readable formats. Following are some of the examples of sorting in real-life scenarios −

DIWAKAR EDUCATION HUB Page 110


DATA STRUCTURES AND ALGORITHMS UNIT – 7
 Telephone Directory − The telephone directory stores the telephone numbers of people
sorted by their names, so that the names can be searched easily.
 Dictionary − The dictionary stores words in an alphabetical order so that searching of
any word becomes easy.
In-place Sorting and Not-in-place Sorting
Sorting algorithms may require some extra space for comparison and temporary storage of
few data elements. These algorithms do not require any extra space and sorting is said to
happen in-place, or for example, within the array itself. This is called in-place sorting. Bubble
sort is an example of in-place sorting.
However, in some sorting algorithms, the program requires space which is more than or equal
to the elements being sorted. Sorting which uses equal or more space is called not-in-place
sorting. Merge-sort is an example of not-in-place sorting.
Stable and Not Stable Sorting
If a sorting algorithm, after sorting the contents, does not change the sequence of similar
content in which they appear, it is called stable sorting.

If a sorting algorithm, after sorting the contents, changes the sequence of similar content in
which they appear, it is called unstable sorting.

Stability of an algorithm matters when we wish to maintain the sequence of original elements,
like in a tuple for example.
Adaptive and Non-Adaptive Sorting Algorithm
A sorting algorithm is said to be adaptive, if it takes advantage of already 'sorted' elements in
the list that is to be sorted. That is, while sorting if the source list has some element already
sorted, adaptive algorithms will take this into account and will try not to re-order them.

DIWAKAR EDUCATION HUB Page 111


DATA STRUCTURES AND ALGORITHMS UNIT – 7
A non-adaptive algorithm is one which does not take into account the elements which are
already sorted. They try to force every single element to be re-ordered to confirm their
sortedness.
Important Terms
Some terms are generally coined while discussing sorting techniques, here is a brief
introduction to them −
Increasing Order
A sequence of values is said to be in increasing order, if the successive element is greater than
the previous one. For example, 1, 3, 4, 6, 8, 9 are in increasing order, as every next element is
greater than the previous element.
Decreasing Order
A sequence of values is said to be in decreasing order, if the successive element is less than
the current one. For example, 9, 8, 6, 4, 3, 1 are in decreasing order, as every next element is
less than the previous element.
Non-Increasing Order
A sequence of values is said to be in non-increasing order, if the successive element is less
than or equal to its previous element in the sequence. This order occurs when the sequence
contains duplicate values. For example, 9, 8, 6, 3, 3, 1 are in non-increasing order, as every
next element is less than or equal to (in case of 3) but not greater than any previous element.
Non-Decreasing Order
A sequence of values is said to be in non-decreasing order, if the successive element is greater
than or equal to its previous element in the sequence. This order occurs when the sequence
contains duplicate values. For example, 1, 3, 3, 6, 8, 9 are in non-decreasing order, as every
next element is greater than or equal to (in case of 3) but not less than the previous one.
Bubble sort
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm
in which each pair of adjacent elements is compared and the elements are swapped if they are
not in order. This algorithm is not suitable for large data sets as its average and worst case
complexity are of Ο(n2) where n is the number of items.
How Bubble Sort Works?
We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it
short and precise.

Bubble sort starts with very first two elements, comparing them to check which one is greater.

In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare
33 with 27.

DIWAKAR EDUCATION HUB Page 112


DATA STRUCTURES AND ALGORITHMS UNIT – 7

We find that 27 is smaller than 33 and these two values must be swapped.

The new array should look like this −

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to the next two values, 35 and 10.

We know then that 10 is smaller 35. Hence they are not sorted.

We swap these values. We find that we have reached the end of the array. After one iteration,
the array should look like this −

To be precise, we are now showing how an array should look like after each iteration. After the
second iteration, it should look like this −

Notice that after each iteration, at least one value moves at the end.

And when there's no swap required, bubble sorts learns that an array is completely sorted.

Now we should look into some practical aspects of bubble sort.


Algorithm
We assume list is an array of n elements. We further assume that swap function swaps the
values of the given array elements.
begin BubbleSort(list)

DIWAKAR EDUCATION HUB Page 113


DATA STRUCTURES AND ALGORITHMS UNIT – 7
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the
whole array is completely sorted in an ascending order. This may cause a few complexity
issues like what if the array needs no more swapping as all the elements are already
ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any swap has
happened or not. If no swap has occurred, i.e. the array requires no more processing to be
sorted, it will come out of the loop.
Pseudocode of BubbleSort algorithm can be written as follows −
procedure bubbleSort( list : array of items )
loop = [Link];
for i = 0 to loop-1 do:
swapped = false
for j = 0 to loop-1 do:
/* compare the adjacent elements */
if list[j] > list[j+1] then
/* swap them */
swap( list[j], list[j+1] )
swapped = true
end if
end for

/*if no number was swapped that means


array is sorted now, break the loop.*/
if(not swapped) then
break
end if
end for
end procedure return list
Implementation
One more issue we did not address in our original algorithm and its improvised pseudocode, is
that, after every iteration the highest values settles down at the end of the array. Hence, the

DIWAKAR EDUCATION HUB Page 114


DATA STRUCTURES AND ALGORITHMS UNIT – 7
next iteration need not include already sorted elements. For this purpose, in our
implementation, we restrict the inner loop to avoid already sorted values.
Quick Sort
Quick sort is the widely used sorting algorithm that makes n log n comparisons in average case
for sorting of an array of n elements. This algorithm follows divide and conquer approach. The
algorithm processes the array in the following way.
1. Set the first index of the array to left and loc variable. Set the last index of the array to
right variable. i.e. left = 0, loc = 0, en d = n - 1, where n is the length of the array.
2. Start from the right of the array and scan the complete array from right to beginning
comparing each element of the array with the element pointed by loc.
Ensure that, a[loc] is less than a[right].
1. If this is the case, then continue with the comparison until right becomes equal to
the loc.
2. If a[loc] > a[right], then swap the two values. And go to step 3.
3. Set, loc = right
1. start from element pointed by left and compare each element in its way with the
element pointed by the variable loc. Ensure that a[loc] > a[left]
1. if this is the case, then continue with the comparison until loc becomes equal to
left.
2. [loc] < a[right], then swap the two values and go to step 2.
3. Set, loc = left.
Complexity

Complexity Best Case Average Worst


Case Case

Time O(n) for 3 way partition or O(n O(n log n) O(n2)


Complexity log n) simple partition

Space O(log n)
Complexity

Algorithm
PARTITION (ARR, BEG, END, LOC)
o Step 1: [INITIALIZE] SET LEFT = BEG, RIGHT = END, LOC = BEG, FLAG =
o Step 2: Repeat Steps 3 to 6 while FLAG =
o Step 3: Repeat while ARR[LOC] <=ARR[RIGHT]
AND LOC != RIGHT
SET RIGHT = RIGHT - 1
[END OF LOOP]

DIWAKAR EDUCATION HUB Page 115


DATA STRUCTURES AND ALGORITHMS UNIT – 7
o Step 4: IF LOC = RIGHT
SET FLAG = 1
ELSE IF ARR[LOC] > ARR[RIGHT]
SWAP ARR[LOC] with ARR[RIGHT]
SET LOC = RIGHT
[END OF IF]
o Step 5: IF FLAG = 0
Repeat while ARR[LOC] >= ARR[LEFT] AND LOC != LEFT
SET LEFT = LEFT + 1
[END OF LOOP]
o Step 6:IF LOC = LEFT
SET FLAG = 1
ELSE IF ARR[LOC] < ARR[LEFT]
SWAP ARR[LOC] with ARR[LEFT]
SET LOC = LEFT
[END OF IF]
[END OF IF]
o Step 7: [END OF LOOP]
o Step 8: END
QUICK_SORT (ARR, BEG, END)
Quick Sort
Quick sort is the widely used sorting algorithm that makes n log n comparisons in average case
for sorting of an array of n elements. This algorithm follows divide and conquer approach. The
algorithm processes the array in the following way.
1. Set the first index of the array to left and loc variable. Set the last index of the array to
right variable. i.e. left = 0, loc = 0, en d = n - 1, where n is the length of the array.
2. Start from the right of the array and scan the complete array from right to beginning
comparing each element of the array with the element pointed by loc.
Ensure that, a[loc] is less than a[right].
1. If this is the case, then continue with the comparison until right becomes equal to
the loc.
2. If a[loc] > a[right], then swap the two values. And go to step 3.
3. Set, loc = right
1. start from element pointed by left and compare each element in its way with the
element pointed by the variable loc. Ensure that a[loc] > a[left]
1. if this is the case, then continue with the comparison until loc becomes equal to
left.
2. [loc] < a[right], then swap the two values and go to step 2.
3. Set, loc = left.
Complexity

DIWAKAR EDUCATION HUB Page 116


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Complexity Best Case Average Worst Case


Case

Time O(n) for 3 way partition or O(n log n) O(n log n) O(n2)
Complexity simple partition

Space O(log n)
Complexity

Algorithm
PARTITION (ARR, BEG, END, LOC)
o Step 1: [INITIALIZE] SET LEFT = BEG, RIGHT = END, LOC = BEG, FLAG =
o Step 2: Repeat Steps 3 to 6 while FLAG =
o Step 3: Repeat while ARR[LOC] <=ARR[RIGHT]
AND LOC != RIGHT
SET RIGHT = RIGHT - 1
[END OF LOOP]
o Step 4: IF LOC = RIGHT
SET FLAG = 1
ELSE IF ARR[LOC] > ARR[RIGHT]
SWAP ARR[LOC] with ARR[RIGHT]
SET LOC = RIGHT
[END OF IF]
o Step 5: IF FLAG = 0
Repeat while ARR[LOC] >= ARR[LEFT] AND LOC != LEFT
SET LEFT = LEFT + 1
[END OF LOOP]
o Step 6:IF LOC = LEFT
SET FLAG = 1
ELSE IF ARR[LOC] < ARR[LEFT]
SWAP ARR[LOC] with ARR[LEFT]
SET LOC = LEFT
[END OF IF]
[END OF IF]
o Step 7: [END OF LOOP]
o Step 8: END
QUICK_SORT (ARR, BEG, END)
Heap Sort
Heap sort processes the elements by creating the min heap or max heap using the elements of
the given array. Min heap or max heap represents the ordering of the array in which root

DIWAKAR EDUCATION HUB Page 117


DATA STRUCTURES AND ALGORITHMS UNIT – 7
element represents the minimum or maximum element of the array. At each step, the root
element of the heap gets deleted and stored into the sorted array and the heap will again be
heapified.
The heap sort basically recursively performs two main operations.
o Build a heap H, using the elements of ARR.
o Repeatedly delete the root element of the heap formed in phase 1.
Complexity

Complexity Best Case Average Case Worst case

Time Complexity Ω(n log (n)) θ(n log (n)) O(n log (n))

Space Complexity O(1)

Algorithm
HEAP_SORT(ARR, N)
o Step 1: [Build Heap H]
Repeat for i=0 to N-1
CALL INSERT_HEAP(ARR, N, ARR[i])
[END OF LOOP]
o Step 2: Repeatedly Delete the root element
Repeat while N > 0
CALL Delete_Heap(ARR,N,VAL)
SET N = N+1
[END OF LOOP]
o Step 3: END
Dijkstra's Algorithm
Dijkstra's algorithm has many variants but the most common one is to find the shortest paths
from the source vertex to all other vertices in the graph.
Algorithm Steps:
 Set all vertices distances = infinity except for the source vertex, set the source distance
= 0.
 Push the source vertex in a min-priority queue in the form (distance , vertex), as the
comparison in the min-priority queue will be according to vertices distances.
 Pop the vertex with the minimum distance from the priority queue (at first the popped
vertex = source).
 Update the distances of the connected vertices to the popped vertex in case of "current
vertex distance + edge weight < next vertex distance", then push the vertex
with the new distance to the priority queue.

DIWAKAR EDUCATION HUB Page 118


DATA STRUCTURES AND ALGORITHMS UNIT – 7
If the popped vertex is visited before, just continue without using it.

 Apply the same algorithm again until the priority queue is empty.
Implementation:
Assume the source vertex = 1.
#define SIZE 100000 + 1

vector < pair < int , int > > v [SIZE]; // each vertex has all the connected vertices with the
edges weights
int dist [SIZE];
bool vis [SIZE];

void dijkstra(){
// set the vertices distances as infinity
memset(vis, false , sizeof vis); // set all vertex as unvisited
dist[1] = 0;
multiset < pair < int , int > > s; // multiset do the job as a min-priority queue

[Link]({0 , 1}); // insert the source node with distance = 0

while(![Link]()){

pair <int , int> p = *[Link](); // pop the vertex with the minimum distance
[Link]([Link]());

int x = p.s; int wei = p.f;


if( vis[x] ) continue; // check if the popped vertex is visited before
vis[x] = true;

for(int i = 0; i < v[x].size(); i++){


int e = v[x][i].f; int w = v[x][i].s;
if(dist[x] + w < dist[e] ){ // check if the next vertex distance could be minimized
dist[e] = dist[x] + w;
[Link]({dist[e], e} ); // insert the next vertex with the updated distance
}
}
}
}
Time Complexity of Dijkstra's Algorithm is O(V2) but with min-priority queue it drops down
to O(V+ElogV).

DIWAKAR EDUCATION HUB Page 119


DATA STRUCTURES AND ALGORITHMS UNIT – 7
However, if we have to find the shortest path between all pairs of vertices, both of the above
methods would be expensive in terms of time. Discussed below is another alogorithm
designed for this case.
Floyd\u2013Warshall's Algorithm
Floyd\u2013Warshall's Algorithm is used to find the shortest paths between between all pairs
of vertices in a graph, where each edge in the graph has a weight which is positive or negative.
The biggest advantage of using this algorithm is that all the shortest distances between
any 2 vertices could be calculated in O(V3), where V is the number of vertices in a graph.
The Algorithm Steps:
For a graph with N vertices:
 Initialize the shortest paths between any 2 vertices with Infinity.
 Find all pair shortest paths that use 0 intermediate vertices, then find the shortest paths
that use 1 intermediate vertex and so on.. until using all N vertices as intermediate
nodes.
 Minimize the shortest paths between any 2 pairs in the previous operation.
 For any 2 vertices (i,j) , one should actually minimize the distances between this pair
using the first K nodes, so the shortest path will be: min(dist[i][k]+dist[k][j],dist[i][j]).
dist[i][k] represents the shortest path that only uses the first K vertices, dist[k][j] represents
the shortest path between the pair k,j. As the shortest path will be a concatenation of the
shortest path from i to k, then from k to j.
for(int k = 1; k <= n; k++){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
dist[i][j] = min( dist[i][j], dist[i][k] + dist[k][j] );
}
}
}
Time Complexity of Floyd\u2013Warshall's Algorithm is O(V3), where V is the number of
vertices in a graph.
Maximum flow
In graph theory, a flow network is defined as a directed graph involving a source(S) and a
sink(T) and several other nodes connected with edges. Each edge has an individual capacity
which is the maximum limit of flow that edge could allow.
Flow in the network should follow the following conditions:
 For any non-source and non-sink node, the input flow is equal to output flow.
 For any edge(Ei) in the network, 0≤flow(Ei)≤Capacity(Ei).
 Total flow out of the source node is equal total to flow in to the sink node.
 Net flow in the edges follows skew symmetry i.e. F(u,v)=−F(v,u) where F(u,v) is flow
from node u to node v. This leads to a conclusion where you have to sum up all the
flows between two nodes(either directions) to find net flow between the nodes initially.

DIWAKAR EDUCATION HUB Page 120


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Maximum Flow:
It is defined as the maximum amount of flow that the network would allow to flow from
source to sink. Multiple algorithms exist in solving the maximum flow problem. Two major
algorithms to solve these kind of problems are Ford-Fulkerson algorithm and Dinic's Algorithm.
They are explained below.
Ford-Fulkerson Algorithm:
It was developed by L. R. Ford, Jr. and D. R. Fulkerson in 1956. A pseudocode for this algorithm
is given below,
Inputs required are network graph G, source node S and sink node T.
function: FordFulkerson(Graph G,Node S,Node T):
Initialise flow in all edges to 0
while (there exists an augmenting path(P) between S and T in residual network graph):
Augment flow between S to T along the path P
Update residual network graph
return
An augmenting path is a simple path from source to sink which do not include any cycles and
that pass only through positive weighted edges. A residual network graph indicates how much
more flow is allowed in each edge in the network graph. If there are no augmenting paths
possible from S to T, then the flow is maximum. The result i.e. the maximum flow will be the
total flow out of source node which is also equal to total flow in to the sink node.
A demonstration of working of Ford-Fulkerson algorithm is shown below with the help of
diagrams.

DIWAKAR EDUCATION HUB Page 121


DATA STRUCTURES AND ALGORITHMS UNIT – 7

DIWAKAR EDUCATION HUB Page 122


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Implementation:
 An augmenting path in residual graph can be found using DFS or BFS.
 Updating residual graph includes following steps: (refer the diagrams for better
understanding)
o For every edge in the augmenting path, a value of minimum capacity in the path is
subtracted from all the edges of that path.
o An edge of equal amount is added to edges in reverse direction for every
successive nodes in the augmenting path.
The complexity of Ford-Fulkerson algorithm cannot be accurately computed as it all depends
on the path from source to sink. For example, considering the network shown below, if each
time, the path chosen are S−A−B−T and S−B−A−T alternatively, then it can take a very long
time. Instead, if path chosen are only S−A−T and S−B−T, would also generate the maximum
flow.

Dinic's Algorithm
In 1970, Y. A. Dinitz developed a faster algorithm for calculating maximum flow over the
networks. It includes construction of level graphs and residual graphs and finding of
augmenting paths along with blocking flow.
Level graph is one where value of each node is its shortest distance from source.
Blocking flow includes finding the new path from the bottleneck node.
Residual graph and augmenting paths are previously discussed.
Pseudocode for Dinic's algorithm is given below.
Inputs required are network graph G, source node S and sink node T.
function: DinicMaxFlow(Graph G,Node S,Node T):
Initialize flow in all edges to 0, F = 0
Construct level graph
while (there exists an augmenting path in level graph):
find blocking flow f in level graph
F=F+f
Update level graph
return F
Update of level graph includes removal of edges with full capacity. Removal of nodes that are
not sink and are dead ends. A demonstration of working of Dinic's algorithm is shown below
with the help of diagrams.

DIWAKAR EDUCATION HUB Page 123


DATA STRUCTURES AND ALGORITHMS UNIT – 7

DIWAKAR EDUCATION HUB Page 124


DATA STRUCTURES AND ALGORITHMS UNIT – 7
P and NP Class Problems
In Computer Science, many problems are solved where the objective is to maximize or
minimize some values, whereas in other problems we try to find whether there is a solution or
not. Hence, the problems can be categorized as follows −
Optimization Problem
Optimization problems are those for which the objective is to maximize or minimize some
values. For example,
 Finding the minimum number of colors needed to color a given graph.
 Finding the shortest path between two vertices in a graph.
Decision Problem
There are many problems for which the answer is a Yes or a No. These types of problems are
known as decision problems. For example,
 Whether a given graph can be colored by only 4-colors.
 Finding Hamiltonian cycle in a graph is not a decision problem, whereas checking a
graph is Hamiltonian or not is a decision problem.
What is Language?
Every decision problem can have only two answers, yes or no. Hence, a decision problem may
belong to a language if it provides an answer ‘yes’ for a specific input. A language is the totality
of inputs for which the answer is Yes. Most of the algorithms discussed in the previous
chapters are polynomial time algorithms.
For input size n, if worst-case time complexity of an algorithm is O(nk), where k is a constant,
the algorithm is a polynomial time algorithm.
Algorithms such as Matrix Chain Multiplication, Single Source Shortest Path, All Pair Shortest
Path, Minimum Spanning Tree, etc. run in polynomial time. However there are many
problems, such as traveling salesperson, optimal graph coloring, Hamiltonian cycles, finding
the longest path in a graph, and satisfying a Boolean formula, for which no polynomial time
algorithms is known. These problems belong to an interesting class of problems, called the NP-
Complete problems, whose status is unknown.
In this context, we can categorize the problems as follows −
P-Class
The class P consists of those problems that are solvable in polynomial time, i.e. these problems
can be solved in time O(nk) in worst-case, where k is constant.
These problems are called tractable, while others are called intractable or superpolynomial.
Formally, an algorithm is polynomial time algorithm, if there exists a polynomial p(n) such that
the algorithm can solve any instance of size n in a time O(p(n)).
Problem requiring Ω(n50) time to solve are essentially intractable for large n. Most known
polynomial time algorithm run in time O(nk) for fairly low value of k.
The advantages in considering the class of polynomial-time algorithms is that all
reasonable deterministic single processor model of computation can be simulated on each
other with at most a polynomial slow-d
NP-Class
DIWAKAR EDUCATION HUB Page 125
DATA STRUCTURES AND ALGORITHMS UNIT – 7
The class NP consists of those problems that are verifiable in polynomial time. NP is the class
of decision problems for which it is easy to check the correctness of a claimed answer, with
the aid of a little extra information. Hence, we aren’t asking for a way to find a solution, but
only to verify that an alleged solution really is correct.
Every problem in this class can be solved in exponential time using exhaustive search.
P versus NP
Every decision problem that is solvable by a deterministic polynomial time algorithm is also
solvable by a polynomial time non-deterministic algorithm.
All problems in P can be solved with polynomial time algorithms, whereas all problems in NP -
P are intractable.
It is not known whether P = NP. However, many problems are known in NP with the property
that if they belong to P, then it can be proved that P = NP.
If P ≠ NP, there are problems in NP that are neither in P nor in NP-Complete.
The problem belongs to class P if it’s easy to find a solution for the problem. The problem
belongs to NP, if it’s easy to check a solution that may have been very tedious to find.
NP-Completeness
A problem is in the class NPC if it is in NP and is as hard as any problem in NP. A problem is NP-
hard if all problems in NP are polynomial time reducible to it, even though it may not be in NP
itself.

If a polynomial time algorithm exists for any of these problems, all problems in NP would be
polynomial time solvable. These problems are called NP-complete. The phenomenon of NP-
completeness is important for both theoretical and practical reasons.
Definition of NP-Completeness
A language B is NP-complete if it satisfies two conditions
 B is in NP
 Every A in NP is polynomial time reducible to B.
If a language satisfies the second property, but not necessarily the first one, the language B is
known as NP-Hard. Informally, a search problem B is NP-Hard if there exists some NP-
Complete problem A that Turing reduces to B.
The problem in NP-Hard cannot be solved in polynomial time, until P = NP. If a problem is
proved to be NPC, there is no need to waste time on trying to find an efficient algorithm for it.
Instead, we can focus on design approximation algorithm.
NP-Complete Problems
Following are some NP-Complete problems, for which no polynomial time algorithm is known.
 Determining whether a graph has a Hamiltonian cycle

DIWAKAR EDUCATION HUB Page 126


DATA STRUCTURES AND ALGORITHMS UNIT – 7
 Determining whether a Boolean formula is satisfiable, etc.
NP-Hard Problems
The following problems are NP-Hard
 The circuit-satisfiability problem
 Set Cover
 Vertex Cover
 Travelling Salesman Problem
In this context, now we will discuss TSP is NP-Complete
TSP is NP-Complete
The traveling salesman problem consists of a salesman and a set of cities. The salesman has to
visit each one of the cities starting from a certain one and returning to the same city. The
challenge of the problem is that the traveling salesman wants to minimize the total length of
the trip
Proof
To prove TSP is NP-Complete, first we have to prove that TSP belongs to NP. In TSP, we find a
tour and check that the tour contains each vertex once. Then the total cost of the edges of the
tour is calculated. Finally, we check if the cost is minimum. This can be completed in
polynomial time. Thus TSP belongs to NP.
Secondly, we have to prove that TSP is NP-hard. To prove this, one way is to show
that Hamiltonian cycle ≤p TSP (as we know that the Hamiltonian cycle problem is
NPcomplete).
Assume G = (V, E) to be an instance of Hamiltonian cycle.
Hence, an instance of TSP is constructed. We create the complete graph G' = (V, E'), where
E′={(i,j):i,j∈Vandi≠j
Thus, the cost function is defined as follows −

Now, suppose that a Hamiltonian cycle h exists in G. It is clear that the cost of each edge
in h is 0 in G' as each edge belongs to E. Therefore, h has a cost of 0 in G'. Thus, if graph G has a
Hamiltonian cycle, then graph G' has a tour of 0 cost.
Conversely, we assume that G' has a tour h' of cost at most 0. The cost of edges
in E' are 0 and 1 by definition. Hence, each edge must have a cost of 0 as the cost of h' is 0. We
therefore conclude that h' contains only edges in E.
We have thus proven that G has a Hamiltonian cycle, if and only if G' has a tour of cost at
most 0. TSP is NP-complete.
Reducibility
Intuitively, a problem Q can be reduced to another problem Q′ if any instance of Q can be
"easily rephrased" as an instance of Q′, the solution to which provides a solution to the
instance of Q. For example, the problem of solving linear equations in an
indeterminate x reduces to the problem of solving quadratic equations. Given an

DIWAKAR EDUCATION HUB Page 127


DATA STRUCTURES AND ALGORITHMS UNIT – 7
instance ax + b = 0, we transform it to 0x2 + ax + b = 0, whose solution provides a solution
to ax + b = 0. Thus, if a problem Q reduces to another problem Q′, then Q is, in a sense, "no
harder to solve" than Q′.
Returning to our formal-language framework for decision problems, we say that a
language L1 is polynomial-time reducible to a language L2, written L1 ≤P L2, if there exists a
polynomial-time computable function f : {0, 1}* → {0,1}* such that for all x {0, 1}*,
(34.1)

We call the function f the reduction function, and a polynomial-time algorithm F that
computes f is called a reduction algorithm.
Figure illustrates the idea of a polynomial-time reduction from a language L1 to another
language L2. Each language is a subset of {0, 1}*. The reduction function f provides a
polynomial-time mapping such that if x ∈ L1, then f(x) ∈ L2. Moreover, if x ∉ L1, then f (x) ∉ L2.
Thus, the reduction function maps any instance x of the decision problem represented by the
language L1 to an instance f (x) of the problem represented by L2. Providing an answer to
whether f(x) ∈ L2 directly provides the answer to whether x ∈ L1.

Figure
An illustration of a polynomial-time reduction from a language L1 to a language L2 via a
reduction function f. For any input x ∈ {0, 1}*, the question of whether x ∈ L1 has the same
answer as the question of whether f(x) ∈ L2.
Polynomial-time reductions give us a powerful tool for proving that various languages belong
to P.
What is Reduction?
Let L1 and L2 be two decision problems. Suppose algorithm A 2 solves L2. That is, if y is an input
for L2 then algorithm A2 will answer Yes or No depending upon whether y belongs to L 2 or not.
The idea is to find a transformation from L1 to L2 so that the algorithm A2 can be part of an
algorithm A1 to solve L1.

Learning reduction in general is very important. For example, if we have library functions to
solve certain problem and if we can reduce a new problem to one of the solved problems, we
DIWAKAR EDUCATION HUB Page 128
DATA STRUCTURES AND ALGORITHMS UNIT – 7
save a lot of time. Consider the example of a problem where we have to find minimum
product path in a given directed graph where product of path is multiplication of weights of
edges along the path. If we have code for Dijkstra’s algorithm to find shortest path, we can
take log of all weights and use Dijkstra’s algorithm to find the minimum product path rather
than writing a fresh code for this new problem.
How to prove that a given problem is NP complete?
From the definition of NP-complete, it appears impossible to prove that a problem L is NP-
Complete. By definition, it requires us to that show every problem in NP is polynomial time
reducible to L. Fortunately, there is an alternate way to prove it. The idea is to take a known
NP-Complete problem and reduce it to L. If polynomial time reduction is possible, we can
prove that L is NP-Complete by transitivity of reduction (If a NP-Complete problem is reducible
to L in polynomial time, then all problems are reducible to L in polynomial time).
What was the first problem proved as NP-Complete?
There must be some first NP-Complete problem proved by definition of NP-Complete
problems. SAT (Boolean satisfiability problem) is the first NP-Complete problem proved by
Cook.
It is always useful to know about NP-Completeness even for engineers. Suppose you are asked
to write an efficient algorithm to solve an extremely important problem for your company.
After a lot of thinking, you can only come up exponential time approach which is impractical. If
you don’t know about NP-Completeness, you can only say that I could not come with an
efficient algorithm. If you know about NP-Completeness and prove that the problem as NP-
complete, you can proudly say that the polynomial time solution is unlikely to exist. If there is
a polynomial time solution possible, then that solution solves a big problem of computer
science many scientists have been trying for years.
The Fast Fourier Transform
The fast Fourier transform (FFT) is an algorithm which can take the discrete Fourier transform
of a array of size n = 2N in Θ(n ln(n)) time. This algorithm is generally performed in place and
this implementation continues in that tradition. Two implementations are provided:
 The first implementation, [Link].h, emphasizes the algorithm; consequently, to
simplify the presentation, it allocates additional memory when dividing the vector into
even and odd entries and explicit recursion is used, and
 The second implementation, [Link].h, demonstrates how the FFT algorithm can be
performed with only O(1) additional memory and without recursive function calls.
Reference, Maple 8, Waterloo Maple Inc., Waterloo, Ontario.
Some comments on the code:
The value π is found using double const PI = 4.0*std::atan( 1.0 ); The inverse tangent function
of 1 returns π/4 and and multiplication by a power of 2 does not affect the relative error of a
floating point number: in this case, multiplication by four simply adds two to the exponent.
The testing function applies the fast Fourier transform to the vector (2, 2, 0, 0, 0, 0, 0, 0)T. It
prints the vector, the fast Fourier transform of the vector, and the inverse fast Fourier
transform of that result. The output is
(1,0) (1,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0)

DIWAKAR EDUCATION HUB Page 129


DATA STRUCTURES AND ALGORITHMS UNIT – 7
(2,0) (1.70711,-0.707107) (1,-1) (0.292893,-0.707107) (0,0) (0.292893,0.707107) (1,1)
(1.70711,0.707107)
(1,0) (1,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0)
You will note that 1/√2 ≈ 0.707107, and 1 − 1/√2 ≈ 0.292893 .
The function printing the complex array will print 0 in place of either component being less
than 10-15. This is to make aid in the visualization of the result.
The Discrete Fourier Transform
The discrete Fourier transform maps a vector from the space domain to the complex
frequency domain. To describe this, recall that a vector of n dimensions represents
coordinates in space: the basis vectors are the n unit vectors (1, 0, 0, ···), (0, 1, 0, ···), etc. These
are shown in Figure 1.

Figure 1. The unit basis vectors for a vector of dimension 8.


While these unit vectors are exceelent for representing the specific location of a vector, they
do not suggest any periodicity. The discrete Fourier transforms is a linear transformation from
a basis of unit vectors to a basis of vectors which are capture the periodic behaviour of the
unit vector: if the copies of the vector were laid end-to-end, what periodicity would there be in
the patterns and what are the periods thereof.

Figure 2. The basis vectors of the frequency space of dimension 8.


template <typename T> class complex<T>
This code uses the STL complex class which has a constructor which takes the real and
imaginary parts as arguments. The following functions are friends of the class and for the
argument z = a + jb:
Function Returns

double abs(z) |z| = √(a2 + b2)

double arg(z) atan2(ℑ(z), ℜ(z)) = atan2(b, a)


complex conj(z) z* = a − jb

double imag(z) ℑ(z) = b

double norm(z) |z|2 = a2 + b2

DIWAKAR EDUCATION HUB Page 130


DATA STRUCTURES AND ALGORITHMS UNIT – 7

complex polar(r, θ) rejθ

double real(z) ℜ(z) = a

complex exp(z) ez

complex log(z) ln(z)

complex pow(w, z) wz

complex sqrt(z) √z

complex sin(z) sin(z)

complex cos(z) cos(z)


complex sinh(z) sinh(z)

complex cosh(z) cosh(z)


A complex number a + jb is printed as the ordered pair (a,b).
Determining Powers of Two
The assertion assert( n > 0 && (n & (~n + 1)) == n ); checks to ensure that the argument n is
both positive and a power of two. The operation n & (~n + 1) selects the least significant one in
the integer. If the least significant one is also the most significant one, then the bitwise and
will return that value; otherwise, the result will not equal the original value n. This is shown in
Figure 3 with both a power of two (64) and a number which is not a power of two (84).

Figure 3. Selecting the least significant one (1) bit in a binary number.
String Matching Algorithms
A string is a sequence of characters. In our model we are going to represent a string as a 0-
indexed array. So a string S = ”Galois” is indeed an array [‘G’, ’a’, ’l’, ’o’, ’i’, ’s’]. The number of
characters of a string is called its length and is denoted by |S|. If we want to reference the
character of the string at position i, we will use S[i].
A substring is a sequence of consecutive contiguous elements of a string, we will denote the
substring starting at i and ending at j of string S by S[i...j].
A prefix of a string S is a substring that starts at position 0, and a suffix a substring that ends at
|S|-1. A proper prefix of a S is a prefix that is different to S. Similarly, a proper suffix of S is a
suffix that is different to S. The + operator will represent string concatenation.
Example:
S="Galois"
DIWAKAR EDUCATION HUB Page 131
DATA STRUCTURES AND ALGORITHMS UNIT – 7
|S|=6
S[0]='G', S[1]='a', S[2]='l',...,S[5]='s'
S[1...4]="aloi"
W="Evariste"
W+S="EvaristeGalois"
A Needle in the haystack (KMP algorithm)
Given a text T we are interested in calculating all the occurrences of a pattern P.
This simple problem has a lot of applications. For example, the text can be the nucleotide
sequence of the human DNA and the pattern a genomic sequence of some genetic disease, or
the text can be all the internet, and the pattern a query (the Google problem), etc.
We are going to study the exact string matching problem, that is given two strings T and P we
want to find all substrings of T that are equal to P. Formally, we want to calculate all indices i
such that T[i+s] = P[s] for each 0 ≤ s ≤ |P|-1.
In the following example, you are given a string T and a pattern P, and all the occurrences of P
in T are highlighted in red.

One easy way to solve the problem, is to iterate over all i from 0to |T| - |P|, and check if there
is a substring of T that starts at i and matches with P:
def find_occurrences(t,p):
lt,lp=len(t),len(p)
for i in range(lt-lp+1):
match=True
for l in range(lp):
if t[i+l]!=p[l]:
match=False
break
if match: print i
Unfortunately this solution is very slow, its time complexity is O(|T|·|P|), however it gives us
some insights.
Suppose that we are finding a match starting at position i on the text, then there are two
possibilities:
We don’t find a match. Then there exists at least one index in which the text is not equal to
the pattern. Let i+j be the smallest of such indices: T[i...i+j-1] = P[0...j-1] and T[i+j] ≠ P[j]

DIWAKAR EDUCATION HUB Page 132


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Since there is no match at position i, we should start finding a match from another position,
but the question is from where? Our previous algorithm always selects as next position i+1,
but if we start from i+1, it is probable that we could end up finding a mismatch in a position
even before than i+j-1. At least, we could want to start from a position that guarantees that
the strings matches until i+j-1. Therefore, we should start finding for a match starting from the
smallest i+k such that T[i+k...i+j-1] matches with some prefix of P (look at the picture above).
Since we already know that T matches with P from i to i+j-1, then T[i+k...i+j-1] is a suffix of
P[0...j-1].
That means that if we find a mismatch at position j, we should start from the smallest k such
that P[k...j-1] is a prefix of P. k is the smallest, so P[k...j-1] is the largest proper suffix that is
also a proper prefix. From now on we will call “border” to the proper prefixes that are also
proper suffixes (e.g the string ABCDABCDAB have two borders ABCDAB and AB).
We find a match. Using the same argument, it’s easy to see that we have to start finding for a
match from the smallest k such that P[k...j-1]is a proper prefix of P
the above two cases with an example:

In the picture above we are finding occurrences starting from position 4, but there is a
mismatch at position 12. Before getting a mismatch we have already matched the string
HACKHACK, and the largest proper prefix that is also a proper suffix (border) of HACKHACK is
HACK, so we should start finding occurrences again from position 8 and taking into account
that all characters from 8 to 11 are already matched. It turns out that there is an occurrence
starting at position 8, so all characters of the pattern have matched, since HACKHACKIT does
not have any border, then we start finding occurrences again starting from position 18.
According to the previous analysis we need to know for each i, the the largest border of
P[0...i]. Let f[i] be the length of the largest border of P[0...i]. Function f is known as failure
function, because it says from where start if we find a mismatch.

DIWAKAR EDUCATION HUB Page 133


DATA STRUCTURES AND ALGORITHMS UNIT – 7
How can we calculate f[i] efficiently? One approach is to think in an inductive way: suppose
that we have already calculated the function f for for all indices less than i. Using that
information how can we calculate f[i]?

Note that if P[0...j] is a border of P[0...i], then P[0...j-1] is a border of P[0...i-1] and P[j] = P[i].
The previous argument suggest this algorithm for finding f[i]: Iterate over all borders of P[0...i-
1], in decreasing order of length, until find a border P[0...j-1] such that P[j] = P[i]. How can we
iterate over all the borders of a string? That can be easily done using this observation: if B is a
border of P, then a border of B is also a border of P, that implies that the borders of P[0...i] are
prefixes of P that ends at f[i]-1, f[f[i]-1]-1, f[f[...f[i]-1...]-1]-1, ... (at most how many borders can
have a string?).
What is the complexity of our algorithm? Let P[j...i-1] be the largest border of P[0...i-1]. If
P[k...i] is the largest border of P[0...i], then k ≥ j (Why?). So when we iterate over the borders
of P[0...i-1], we are moving the index j to k. Since j is moving always to the right, in the worst
case it will touch all the elements of the array. That means that we are calculating function f in
O(|P|).
Using function f it is easy to search for the occurrences of a pattern on a text in O(|T|+|P|):
def failure_function(p):
l=len(p)
f=[0]*l
j=0
for i in range(1,l):
while j>=0 and p[j]!=p[i]:
if j-1>=0: j=f[j-1]
else: j=-1
j+=1
f[i]=j
return f

def find_occurrences(t,p):
f=failure_function(p)
lt,lp=len(t),len(p)
j=0
for i in range(lt):

DIWAKAR EDUCATION HUB Page 134


DATA STRUCTURES AND ALGORITHMS UNIT – 7
while j>=0 and t[i]!=p[j]:
if j-1>=0: j=f[j-1]
else: j=-1
j+=1
if j==lp:
j=f[lp-1]
print i-lp+1
As you can note from the pseudo code (it is python code indeed), find_occurrences is almost
equal to failure_function, that is because in some sense failure_function is like matching a
string with itself.
The algorithm described above is known as Knut-Morris-Pratt (or KMP for short). Note that
with KMP algorithm we don’t need to have all the string T in memory, we can read it character
by character, and determine all the occurrences of a pattern P in an online way.
The Z function
Given a string S, let z[i] be the longest substring of S that starts at i and is also a prefix of S.
Example:

z[ 3 ] = 4 because starting from position 3, the largest string that is also a prefix of S is ABRA.
If we can calculate the function Z efficiently, then how can we find all the occurrences of a
pattern P on a text T? Since z[i] gives matches with a prefix, a good idea is to observe how the
z function behaves when P is concatenated with T. So let’s calculate the function z on S = P+T.
It turns out that if for certain i, z[i] ≥ |P| then there is an occurrence of P starting at i.
Now only remains to find a way of calculate that powerful z function.
The naive approach for calculate z in every i is to iterate over all j ≥ i until we find a mismatch (
z[i...j] ≠ z[0...j-i] ), then z[i] = j-i. This algorithm is of quadratic time, so we need a better
solution.

The z function applied at position i of a string determines an interval [i, i+z[i]-1] known as z-
box, that interval is special, because by the definition of z, S[ i...i+z[i]-1 ] = S[0...z[i]-1].
Now let’s think again in a inductive way, and calculate z[i] given that we already know
z[0],...,z[i-1].
Let [L,R] be the z-box with largest R that we have seen until now.

DIWAKAR EDUCATION HUB Page 135


DATA STRUCTURES AND ALGORITHMS UNIT – 7
If i is inside [L,R], then S[i...R] = S[i-L...R-L] (look at the picture above), so we can use the value
of z[i-L] that we have already calculated. If z[i-L] Is less than R-i+1, then z[i] = z[i-L], otherwise
since we already know that S[i...R] is a prefix of S, it remains to check if we can expand S[i...R]
starting from R+1.
On the other hand If i is outside [L...R], then we can calculate z[i] using the naive approach.
This algorithm is linear because the pointer R traverses the array at most once.
def zeta(s):
n=len(s)
z=[0]*n
L,R=-1,-1
for i in range(1,n):
j,k=0,i
if L<=i<=R:
ii = i-L
j=min(ii+z[ii], R-L+1)-ii
k=i+j
while k<n and s[j]==s[k]:
j+=1
k+=1
z[i]=k-i
if z[i]>0 and i+z[i]-1>R:
L,R=i,i+z[i]-1
return z

def find_occurrences(p,t):
lp,lt=len(p),len(t)
z=zeta(p+t)
for i in range(lp,lp+lt):
if z[i]>=lp: print i-lp
Hashing strikes back (Rabin-Karp algorithm)
Pattern P matches with text T at position i, if and only if there is a substring of T that starts at i
and is equal to P. So if we can compare quickly two strings ( T[i...i +|P|-1] with P ), then we can
use our naive algorithm (iterate over all i, and check if there is a match). One way of checking if
two strings are not equal is to find a property that is different in those strings. Let h be a black-
box that have as input a string, and outputs certain property of the string, that property is
defined in such a way that if two strings are different, the value of that property is also
different: if S1 ≠ S2 then h(S1) ≠ h(S2). Note that with this definition, we can’t assert if two
strings are equal, because two different strings can have the same value of the chosen
property.

DIWAKAR EDUCATION HUB Page 136


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Since numbers are easy to compare it will be nice if h outputs a number. So the question is
how to represent a string as a number. Note that strings are like numbers, because we can
consider its characters as digits. Since the alphabet have 26 letters, we could say that a string
is a number in a numeration system of base 27. The problem is that strings can be very large,
and we can represent integers in a very limited range (from 0 to 18446744073709551615
using a 64 bit unsigned integer), in order to keep the output of h in a small range, let’s apply
the modulo operation (is because of this last necessary operation that two different strings
can map to the same integer i.e there is a hash collision).
Example: if S=”hack”, then h(S) = (8 · 283 + 1 · 282 + 3 · 281 + 11 · 280) %M.
Note that we are considering the value of the digit “a” as 1 instead of 0, that is to prevent
cases with leading zeroes (e.g “aab” and “b” are different, but if a = 0 they are equal).
A function like h, that converts elements from a very large range (like strings) to elements in a
small range (64 bit integers) are called hash functions The value of the hash function applied to
certain element is called it’s hash.
In order to reduce hash collisions, M is usually chosen as a large prime. However if we use an
unsigned 32 bits integer we could just let the value overflow (in this case the modulo is 232).
It remains to solve this problem: if we know the hash of the substring (of length |P|) that
starts at i, how to calculate the hash of the substring that starts at i+1? (see figure below)

Let h be the hash of the substring of length |P| that starts at i. We can calculate the hash of
the substring that starts at i+1 in two steps:
Remove the character at position i:

Add the character at position i+|P|:

The idea of calculate the hash that starts at position i+1 using the hash at i is called rolling
hash.
def val(ch): #maps a character to a digit e.g a = 1, b = 2,...
return ord(ch)-ord("a")+1
def find_occurrences(p,t):
lp,lt=len(p),len(t)
m=10**9+7 #modulo (a "big" prime)
b=30 #numeration system base
hp=0 #hash of the pattern
ht=0 #hash of a substring of length |P| of the text
for i in range(lp):
hp=(hp*b+val(p[i]))%m

DIWAKAR EDUCATION HUB Page 137


DATA STRUCTURES AND ALGORITHMS UNIT – 7
ht=(ht*b+val(t[i]))%m
pwr=1
for i in range(lp-1):
pwr=pwr*b%m

if hp==ht: print 0
for i in range(1,lt-lp+1):
#rolling hash
#remove character i-1:
ht=(ht-val(t[i-1])*pwr)%m
ht=(ht+m)%m
#add character i+|P|-1
ht=(ht*b+val(t[i+lp-1]))%m
if ht==hp: print i
Note that in the code above, we are finding matches with high probability (because of hash
collision). It is possible to increase the probability using two modulos, but in programming
contests usually one modulo is enough (given a modulo how to generate two different strings
with the same hash?).
What is Parallelism?
Parallelism is the process of processing several set of instructions simultaneously. It reduces
the total computational time. Parallelism can be implemented by using parallel computers, i.e.
a computer with many processors. Parallel computers require parallel algorithm, programming
languages, compilers and operating system that support multitasking.
In this tutorial, we will discuss only about parallel algorithms. Before moving further, let us
first discuss about algorithms and their types.
What is an Algorithm?
An algorithm is a sequence of instructions followed to solve a problem. While designing an
algorithm, we should consider the architecture of computer on which the algorithm will be
executed. As per the architecture, there are two types of computers −
 Sequential Computer
 Parallel Computer
Depending on the architecture of computers, we have two types of algorithms −
 Sequential Algorithm − An algorithm in which some consecutive steps of instructions
are executed in a chronological order to solve a problem.
 Parallel Algorithm − The problem is divided into sub-problems and are executed in
parallel to get individual outputs. Later on, these individual outputs are combined
together to get the final desired output.
It is not easy to divide a large problem into sub-problems. Sub-problems may have data
dependency among them. Therefore, the processors have to communicate with each other to
solve the problem.

DIWAKAR EDUCATION HUB Page 138


DATA STRUCTURES AND ALGORITHMS UNIT – 7
It has been found that the time needed by the processors in communicating with each other is
more than the actual processing time. So, while designing a parallel algorithm, proper CPU
utilization should be considered to get an efficient algorithm.
To design an algorithm properly, we must have a clear idea of the basic model of
computation in a parallel computer.
Model of Computation
Both sequential and parallel computers operate on a set (stream) of instructions called
algorithms. These set of instructions (algorithm) instruct the computer about what it has to do
in each step.
Depending on the instruction stream and data stream, computers can be classified into four
categories −
 Single Instruction stream, Single Data stream (SISD) computers
 Single Instruction stream, Multiple Data stream (SIMD) computers
 Multiple Instruction stream, Single Data stream (MISD) computers
 Multiple Instruction stream, Multiple Data stream (MIMD) computers
SISD Computers
SISD computers contain one control unit, one processing unit, and one memory unit.

In this type of computers, the processor receives a single stream of instructions from the
control unit and operates on a single stream of data from the memory unit. During
computation, at each step, the processor receives one instruction from the control unit and
operates on a single data received from the memory unit.
SIMD Computers
SIMD computers contain one control unit, multiple processing units, and shared memory or
interconnection network.

DIWAKAR EDUCATION HUB Page 139


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Here, one single control unit sends instructions to all processing units. During computation, at
each step, all the processors receive a single set of instructions from the control unit and
operate on different set of data from the memory unit.
Each of the processing units has its own local memory unit to store both data and instructions.
In SIMD computers, processors need to communicate among themselves. This is done
by shared memory or by interconnection network.
While some of the processors execute a set of instructions, the remaining processors wait for
their next set of instructions. Instructions from the control unit decides which processor will
be active (execute instructions) or inactive (wait for next instruction).
MISD Computers
As the name suggests, MISD computers contain multiple control units, multiple processing
units, and one common memory unit.

Here, each processor has its own control unit and they share a common memory unit. All the
processors get instructions individually from their own control unit and they operate on a
single stream of data as per the instructions they have received from their respective control
units. This processor operates simultaneously.
MIMD Computers
MIMD computers have multiple control units, multiple processing units, and a shared
memory or interconnection network.

DIWAKAR EDUCATION HUB Page 140


DATA STRUCTURES AND ALGORITHMS UNIT – 7

Here, each processor has its own control unit, local memory unit, and arithmetic and logic
unit. They receive different sets of instructions from their respective control units and operate
on different sets of data.
Note
 An MIMD computer that shares a common memory is known as multiprocessors, while
those that uses an interconnection network is known as multicomputers.
 Based on the physical distance of the processors, multicomputers are of two types −
o Multicomputer − When all the processors are very close to one another (e.g., in
the same room).
o Distributed system − When all the processors are far away from one another
(e.g.- in the different cities)

Parallel Algorithm - Sorting


Sorting is a process of arranging elements in a group in a particular order, i.e., ascending order,
descending order, alphabetic order, etc. Here we will discuss the following −
 Enumeration Sort
 Odd-Even Transposition Sort
 Parallel Merge Sort
 Hyper Quick Sort
Sorting a list of elements is a very common operation. A sequential sorting algorithm may not
be efficient enough when we have to sort a huge volume of data. Therefore, parallel
algorithms are used in sorting.
Enumeration Sort
Enumeration sort is a method of arranging all the elements in a list by finding the final position
of each element in a sorted list. It is done by comparing each element with all other elements
and finding the number of elements having smaller value.
Therefore, for any two elements, ai and aj any one of the following cases must be true −
 ai < a j

DIWAKAR EDUCATION HUB Page 141


DATA STRUCTURES AND ALGORITHMS UNIT – 7
 ai > a j
 ai = a j
Algorithm
procedure ENUM_SORTING (n)
begin
for each process P1,j do
C[j] := 0;
for each process Pi, j do
if (A[i] < A[j]) or A[i] = A[j] and i < j) then
C[j] := 1;
else
C[j] := 0;
for each process P1, j do
A[C[j]] := A[j];
end ENUM_SORTING
Odd-Even Transposition Sort
Odd-Even Transposition Sort is based on the Bubble Sort technique. It compares two adjacent
numbers and switches them, if the first number is greater than the second number to get an
ascending order list. The opposite case applies for a descending order series. Odd-Even
transposition sort operates in two phases − odd phase and even phase. In both the phases,
processes exchange numbers with their adjacent number in the right.

Algorithm

DIWAKAR EDUCATION HUB Page 142


DATA STRUCTURES AND ALGORITHMS UNIT – 7
procedure ODD-EVEN_PAR (n)

begin
id := process's label
for i := 1 to n do
begin
if i is odd and id is odd then
compare-exchange_min(id + 1);
else
compare-exchange_max(id - 1);

if i is even and id is even then


compare-exchange_min(id + 1);
else
compare-exchange_max(id - 1);
end for

end ODD-EVEN_PAR
Parallel Merge Sort
Merge sort first divides the unsorted list into smallest possible sub-lists, compares it with the
adjacent list, and merges it in a sorted order. It implements parallelism very nicely by following
the divide and conquer algorithm.

Algorithm
procedureparallelmergesort(id, n, data, newdata)

DIWAKAR EDUCATION HUB Page 143


DATA STRUCTURES AND ALGORITHMS UNIT – 7
begin
data = sequentialmergesort(data)

for dim = 1 to n
data = parallelmerge(id, dim, data)
endfor

newdata = data
end
Hyper Quick Sort
Hyper quick sort is an implementation of quick sort on hypercube. Its steps are as follows −
 Divide the unsorted list among each node.
 Sort each node locally.
 From node 0, broadcast the median value.
 Split each list locally, then exchange the halves across the highest dimension.
 Repeat steps 3 and 4 in parallel until the dimension reaches 0.
Algorithm
procedure HYPERQUICKSORT (B, n)
begin
id := process’s label;
for i := 1 to d do
begin
x := pivot;
partition B into B1 and B2 such that B1 ≤ x < B2;
if ith bit is 0 then

begin
send B2 to the process along the ith communication link;
C := subsequence received along the ith communication link;
B := B1 U C;
endif

else
send B1 to the process along the ith communication link;
C := subsequence received along the ith communication link;
B := B2 U C;
end else
end for

DIWAKAR EDUCATION HUB Page 144


DATA STRUCTURES AND ALGORITHMS UNIT – 7
sort B using sequential quicksort;
end HYPERQUICKSORT
Approximate Algorithms
An Approximate Algorithm is a way of approach NP-COMPLETENESS for the optimization
problem. This technique does not guarantee the best solution. The goal of an approximation
algorithm is to come as close as possible to the optimum value in a reasonable amount of time
which is at the most polynomial time. Such algorithms are called approximation algorithm or
heuristic algorithm.
o For the traveling salesperson problem, the optimization problem is to find the shortest
cycle, and the approximation problem is to find a short cycle.
o For the vertex cover problem, the optimization problem is to find the vertex cover with
fewest vertices, and the approximation problem is to find the vertex cover with few
vertices.
Performance Ratios
Suppose we work on an optimization problem where every solution carries a cost. An
Approximate Algorithm returns a legal solution, but the cost of that legal solution may not be
optimal.
For Example, suppose we are considering for a minimum size vertex-cover (VC). An
approximate algorithm returns a VC for us, but the size (cost) may not be minimized.
Another Example is we are considering for a maximum size Independent set (IS). An
approximate Algorithm returns an IS for us, but the size (cost) may not be maximum. Let C be
the cost of the solution returned by an approximate algorithm, and C* is the cost of the
optimal solution.
We say the approximate algorithm has an approximate ratio P (n) for an input size n, where

Intuitively, the approximation ratio measures how bad the approximate solution is
distinguished with the optimal solution. A large (small) approximation ratio measures the
solution is much worse than (more or less the same as) an optimal solution.
Observe that P (n) is always ≥ 1, if the ratio does not depend on n, we may write P.
Therefore, a 1-approximation algorithm gives an optimal solution. Some problems have
polynomial-time approximation algorithm with small constant approximate ratios, while
others have best-known polynomial time approximation algorithms whose approximate ratios
grow with
Randomized Algorithms
An algorithm that uses random numbers to decide what to do next anywhere in its logic is
called Randomized Algorithm. For example, in Randomized Quick Sort, we use random number
to pick the next pivot (or we randomly shuffle the array). Typically, this randomness is used to
reduce time complexity or space complexity in other standard algorithms.
What is a Randomized Algorithm?

DIWAKAR EDUCATION HUB Page 145


DATA STRUCTURES AND ALGORITHMS UNIT – 7
An algorithm that uses random numbers to decide what to do next anywhere in its logic is
called Randomized Algorithm.. For example, in Randomized Quick Sort, we use random
number to pick the next pivot (or we randomly shuffle the array). And in Karger’s algorithm,
we randomly pick an edge.
How to analyse Randomized Algorithms?
Some randomized algorithms have deterministic time complexity. For
example, this implementation of Karger’s algorithm has time complexity as O(E). Such
algorithms are called Monte Carlo Algorithms and are easier to analyse for worst case.
On the other hand, time complexity of other randomized algorithms (other than Las Vegas) is
dependent on value of random variable. Such Randomized algorithms are called Las Vegas
Algorithms. These algorithms are typically analysed for expected worst case. To compute
expected time taken in worst case, all possible values of the used random variable needs to be
considered in worst case and time taken by every possible value needs to be evaluated.
Average of all evaluated times is the expected worst case time complexity. Below facts are
generally helpful in analysis os such algorithms.
Linearity of Expectatio
Expected Number of Trials until Success.
For example consider below a randomized version of QuickSort.
A Central Pivot is a pivot that divides the array in such a way that one side has at-least 1/4
elements.
// Sorts an array arr[low..high]
randQuickSort(arr[], low, high)

1. If low >= high, then EXIT.

2. While pivot 'x' is not a Central Pivot.


(i) Choose uniformly at random a number from [low..high].
Let the randomly picked number number be x.
(ii) Count elements in arr[low..high] that are smaller
than arr[x]. Let this count be sc.
(iii) Count elements in arr[low..high] that are greater
than arr[x]. Let this count be gc.
(iv) Let n = (high-low+1). If sc >= n/4 and
gc >= n/4, then x is a central pivot.

3. Partition arr[low..high] around the pivot x.

4. // Recur for smaller elements


randQuickSort(arr, low, sc-1)

DIWAKAR EDUCATION HUB Page 146


DATA STRUCTURES AND ALGORITHMS UNIT – 7
5. // Recur for greater elements
randQuickSort(arr, high-gc+1, high)
The important thing in our analysis is, time taken by step 2 is O(n).
How many times while loop runs before finding a central pivot?
The probability that the randomly chosen element is central pivot is 1/2.
Therefore, expected number of times the while loop runs is 2
Thus, the expected time complexity of step 2 is O(n).
What is overall Time Complexity in Worst Case?
In worst case, each partition divides array such that one side has n/4 elements and other side
has 3n/4 elements. The worst case height of recursion tree is Log 3/4 n which is O(Log n).
T(n) < T(n/4) + T(3n/4) + O(n)
T(n) < 2T(3n/4) + O(n)
Solution of above recurrence is O(n Log n)
Note that the above randomized algorithm is not the best way to implement randomized
Quick Sort. The idea here is to simplify the analysis as it is simple to analyse.
Typically, randomized Quick Sort is implemented by randomly picking a pivot (no loop). Or by
shuffling array elements.
Searching
Searching is the process of finding some particular element in the list. If the element is present
in the list, then the process is called successful and the process returns the location of that
element, otherwise the search is called unsuccessful.
There are two popular search methods that are widely used in order to search some item into
the list. However, choice of the algorithm depends upon the arrangement of the list.
o Linear Search
o Binary Search
Linear Search
Linear search is the simplest search algorithm and often called sequential search. In this type
of searching, we simply traverse the list completely and match each element of the list with
the item whose location is to be found. If the match found then location of the item is
returned otherwise the algorithm return NULL.
Linear search is mostly used to search an unordered list in which the items are not sorted. The
algorithm of linear search is given as follows.
Algorithm
o LINEAR_SEARCH(A, N, VAL)
o Step 1: [INITIALIZE] SET POS = -1
o Step 2: [INITIALIZE] SET I = 1
o Step 3: Repeat Step 4 while I<=N
o Step 4: IF A[I] = VAL
SET POS = I
PRINT POS

DIWAKAR EDUCATION HUB Page 147


DATA STRUCTURES AND ALGORITHMS UNIT – 7
Go to Step 6
[END OF IF]
SET I = I + 1
[END OF LOOP]
o Step 5: IF POS = -1
PRINT " VALUE IS NOT PRESENTIN THE ARRAY "
[END OF IF]
o Step 6: EXIT
Complexity of algorithm
Complexity Best Case Average Case Worst Case
Time O(1) O(n) O(n)
Space O(1)
Binary Search
Binary search is the search technique which works efficiently on the sorted lists. Hence, in
order to search an element into some list by using binary search technique, we must ensure
that the list is sorted.
Binary search follows divide and conquer approach in which, the list is divided into two halves
and the item is compared with the middle element of the list. If the match is found then, the
location of middle element is returned otherwise, we search into either of the halves
depending upon the result produced through the match.
Binary search algorithm is given below.
BINARY_SEARCH(A, lower_bound, upper_bound, VAL)
o Step 1: [INITIALIZE] SET BEG = lower_bound
END = upper_bound, POS = - 1
o Step 2: Repeat Steps 3 and 4 while BEG <=END
o Step 3: SET MID = (BEG + END)/2
o Step 4: IF A[MID] = VAL
SET POS = MID
PRINT POS
Go to Step 6
ELSE IF A[MID] > VAL
SET END = MID - 1
ELSE
SET BEG = MID + 1
[END OF IF]
[END OF LOOP]
o Step 5: IF POS = -1
PRINT "VALUE IS NOT PRESENT IN THE ARRAY"
[END OF IF]
o Step 6: EXIT
Complexity
DIWAKAR EDUCATION HUB Page 148
DATA STRUCTURES AND ALGORITHMS UNIT – 7
SN Performance Complexity
1 Worst case O(log n)
2 Best case O(1)
3 Average Case O(log n)
4 Worst case space complexity O(1)
Example
Let us consider an array arr = {1, 5, 7, 8, 13, 19, 20, 23, 29}. Find the location of the item 23 in
the array.
In 1st step :
1. BEG = 0
2. END = 8ron
3. MID = 4
4. a[mid] = a[4] = 13 < 23, therefore
in Second step:
1. Beg = mid +1 = 5
2. End = 8
3. mid = 13/2 = 6
4. a[mid] = a[6] = 20 < 23, therefore;
in third step:
1. beg = mid + 1 = 7
2. End = 8
3. mid = 15/2 = 7
4. a[mid] = a[7]
5. a[7] = 23 = item;
6. therefore, set location = mid;
7. The location of the item will be 7.

DIWAKAR EDUCATION HUB Page 149


DATA STRUCTURES AND ALGORITHMS UNIT – 7

DIWAKAR EDUCATION HUB Page 150


DIWAKAR EDUCATION HUB

DATA STRUCTURES AND


ALGORITHMS UNIT – 7 MCQS
AS PER UPDATED SYLLABUS
DIWAKAR EDUCATION HUB

THE LEARN WITH EXPERTIES


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
1. Which line should be inserted in the blank programming implementation of the
to complete the following dynamic maximum sub-array sum problem?

a) max_num(sum[idx – 1] + arr[idx], arr[idx])


b) sum[idx – 1] + arr[idx].
c) min_num(sum[idx – 1] + arr[idx], arr[idx])
d) arr[idx].
Answer: a
Explanation: The array “sum” is used to store
the maximum sub-array sum. The
appropriate way to do this is by using:
sum[idx] = max_num(sum[idx – 1] + arr[idx],
arr[idx]).

DIWAKAR EDUCATION HUB Page 2


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
2. What is the space complexity of the used to find the maximum sub-array sum?
following dynamic programming algorithm

a) O(n) the length of the array to store the sum


b) O(1) values. So, the space complexity is O(n).
c) O(n!)
d) O(n2)
Answer: a
Explanation: The above dynamic
programming algorithm uses space equal to

DIWAKAR EDUCATION HUB Page 3


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
3. Consider the following code snippet:

Which method is used by line 4 of the above Answer: b


code snippet? Explanation: Array contains elements only of
a) Divide and conquer the same type.
b) Recursion 6. How do you initialize an array in C?
c) Both memoization and divide and conquer a) int arr[3] = (1,2,3);
d) Memoization b) int arr(3) = {1,2,3};
Answer: d c) int arr[3] = {1,2,3};
Explanation: The array “sum” is used to store d) int arr(3) = (1,2,3);
the previously calculated values, so that they Answer: c
aren’t recalculated. So, line 4 uses the Explanation: This is the syntax to initialize an
memoization technique. array in C.
4. Find the maximum sub-array sum for the 7. How do you instantiate an array in Java?
following array: a) int arr[] = new int(3);
{3, 6, 7, 9, 3, 8} b) int arr[];
a) 33 c) int arr[] = new int[3];
b) 36 d) int arr() = new int(3);
c) 23 Answer: c
d) 26 Explanation: Note that option b is declaration
Answer: b whereas option c is to instantiate an array.
Explanation: All the elements of the array are 8. Which of the following is a correct way to
positive. So, the maximum sub-array sum is declare a multidimensional array in Java?
equal to the sum of all the elements, which is a) int[] arr;
36. b) int arr[[]];
5. Which of these best describes an array? c) int[][]arr;
a) A data structure that shows a hierarchical d) int[[]] arr;
behaviour Answer: c
b) Container of objects of similar types Explanation: The syntax to declare
c) Arrays are immutable once initialised multidimensional array in java is either int[][]
d) Array is not a data structure arr; or int arr[][];
9. What is the output of the following piece
of code?
DIWAKAR EDUCATION HUB Page 4
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
public class array time exception and the compilation is error-
{ free.
public static void main(String args[]) 12. Which of the following concepts make
{ extensive use of arrays?
int []arr = {1,2,3,4,5}; a) Binary trees
b) Scheduling of processes
[Link](arr[2]);
c) Caching
[Link](arr[4]); d) Spatial locality
} Answer: d
} Explanation: Whenever a particular memory
a) 3 and 5 location is referred, it is likely that the
b) 5 and 3 locations nearby are also referred, arrays are
c) 2 and 4 stored as contigous blocks in memory, so if
d) 4 and 2 you want to access array elements, spatial
Answer: a locality makes it to access quickly.
Explanation: Array indexing starts from 0. 13. What are the advantages of arrays?
10. What is the output of the following piece a) Objects of mixed data types can be stored
of code? b) Elements in an array cannot be sorted
public class array c) Index of first element of an array is 1
{ d) Easier to store elements of same data type
public static void main(String args[]) Answer: d
{ Explanation: Arrays stores elements of same
data type and present in continuous memory
int []arr = {1,2,3,4,5};
locations.
[Link](arr[5]);
14. What are the disadvantages of arrays?
}
a) Data structure like queue or stack cannot
} be implemented
a) 4 b) There are chances of wastage of memory
b) 5 space if elements inserted in an array are
c) ArrayIndexOutOfBoundsException lesser than the allocated size
d) InavlidInputException c) Index value of an array can be negative
Answer: c d) Elements are sequentially accessed
Explanation: Trying to access an element Answer: b
beyond the limits of an array gives Explanation: Arrays are of fixed size. If we
ArrayIndexOutOfBoundsException. insert elements less than the allocated size,
11. When does the Array Index Out Of unoccupied positions can’t be used again.
Bounds Exception occur? Wastage will occur in memory.
a) Compile-time 15. Assuming int is of 4bytes, what is the size
b) Run-time of int arr[15];?
c) Not an error a) 15
d) Not an exception at all b) 19
Answer: b c) 11
Explanation: d) 60
ArrayIndexOutOfBoundsException is a run-

DIWAKAR EDUCATION HUB Page 5


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: d the top most element in the stack i.e. last
Explanation: Since there are 15 int elements entered element.
and each int is of 4bytes, we get 15*4 = 20. In a stack, if a user tries to remove an
60bytes. element from empty stack it is called
16. In general, the index of the first element _________
in an array is __________ a) Underflow
a) 0 b) Empty collection
b) -1 c) Overflow
c) 2 d) Garbage Collection
d) 1 Answer: a
Answer: a Explanation: Underflow occurs when the user
Explanation: In general, Array Indexing starts performs a pop operation on an empty stack.
from 0. Thus, the index of the first element in Overflow occurs when the stack is full and
an array is 0. the user performs a push operation. Garbage
17. Elements in an array are accessed Collection is used to recover the memory
_____________ occupied by objects that are no longer used.
a) randomly 21. Pushing an element into stack already
b) sequentially having five elements and stack size of 5, then
c) exponentially stack becomes
d) logarithmically a) Overflow
Answer: a b) Crash
Explanation: Elements in an array are c) Underflow
accessed randomly. In Linked lists, elements d) User flow
are accessed sequentially. Answer: a
18. Process of inserting an element in stack is Explanation: The stack is filled with 5
called ____________ elements and pushing one more element
a) Create causes a stack overflow. This results in
b) Push overwriting memory, code and loss of
c) Evaluation unsaved work on the computer.
d) Pop 22. Entries in a stack are “ordered”. What is
Answer: b the meaning of this statement?
Explanation: Push operation allows users to a) A collection of stacks is sortable
insert elements in stack. If stack is filled b) Stack entries may be compared with the ‘<‘
completely and trying to perform push operation
operation stack – overflow can happen. c) The entries are stored in a linked list
19. Process of removing an element from d) There is a Sequential entry that is one by
stack is called __________ one
a) Create Answer: d
b) Push Explanation: In stack data structure,
c) Evaluation elements are added one by one using push
d) Pop operation. Stack follows LIFO Principle i.e.
Answer: d Last In First Out(LIFO).
Explanation: Elements in stack are removed 23. Which of the following applications may
using pop operation. Pop operation removes use a stack?

DIWAKAR EDUCATION HUB Page 6


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
a) A parentheses balancing program Answer: b
b) Tracking of local variables at run time Explanation: In the entire parenthesis
c) Compiler Syntax Analyzer balancing method when the incoming token
d) Data Transfer between two asynchronous is a left parenthesis it is pushed into stack. A
process right parenthesis makes pop operation to
Answer: d delete the elements in stack till we get left
Explanation: Data transfer between the two parenthesis as top most element. 2 left
asynchronous process uses the queue data parenthesis are pushed whereas one right
structure for synchronisation. The rest are all parenthesis removes one of left parenthesis.
stack applications. 2 elements are there before right parenthesis
24. Consider the usual algorithm for which is the maximum number of elements in
determining whether a sequence of stack at run time.
parentheses is balanced. 26. What is the value of the postfix
The maximum number of parentheses that expression 6 3 2 4 + – *:
appear on the stack AT ANY ONE TIME when a) 1
the algorithm analyzes: (()(())(())) are: b) 40
a) 1 c) 74
b) 2 d) -1
c) 3 Answer: d
d) 4 or more Explanation: Postfix Expression is (6+(3-
Answer: c (2*4))) which results -18 as output.
Explanation: In the entire parenthesis 27. Here is an infix expression: 4 + 3*(6*3-
balancing method when the incoming token 12). Suppose that we are using the usual
is a left parenthesis it is pushed into stack. A stack algorithm to convert the expression
right parenthesis makes pop operation to from infix to postfix notation.
delete the elements in stack till we get left The maximum number of symbols that will
parenthesis as top most element. 3 elements appear on the stack AT ONE TIME during the
are there in stack before right parentheses conversion of this expression?
comes. Therefore, maximum number of a) 1
elements in stack at run time is 3. b) 2
25. Consider the usual algorithm for c) 3
determining whether a sequence of d) 4
parentheses is balanced. Answer: d
Suppose that you run the algorithm on a Explanation: When we perform the
sequence that contains 2 left parentheses conversion from infix to postfix expression +,
and 3 right parentheses (in some order). *, (, * symbols are placed inside the stack. A
The maximum number of parentheses that maximum of 4 symbols are identified during
appear on the stack AT ANY ONE TIME during the entire conversion.
the computation? 28. The postfix form of the expression (A+
a) 1 B)*(C*D- E)*F / G is?
b) 2 a) AB+ CD*E – FG /**
c) 3 b) AB + CD* E – F **G /
d) 4 or more c) AB + CD* E – *F *G /
d) AB + CDE * – * F *G /

DIWAKAR EDUCATION HUB Page 7


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c 31. The process of accessing data stored in a
Explanation: (((A+ B)*(C*D- E)*F) / G) is serial access memory is similar to
converted to postfix expression as manipulating data on a ________
(AB+(*(C*D- E)*F )/ G) a) Heap
(AB+CD*E-*F) / G b) Binary Tree
(AB+CD*E-*F * G/). Thus Postfix expression is c) Array
AB+CD*E-*F*G/ d) Stack
29. The data structure required to check Answer: d
whether an expression contains balanced Explanation: In serial access memory data
parenthesis is? records are stored one after the other in
a) Stack which they are created and are accessed
b) Queue sequentially. In stack data structure,
c) Array elements are accessed sequentially. Stack
d) Tree data structure resembles the serial access
Answer: a memory.
Explanation: The stack is a simple data 32. The postfix form of A*B+C/D is?
structure in which elements are added and a) *AB/CD+
removed based on the LIFO principle. Open b) AB*CD/+
parenthesis is pushed into the stack and a c) A*BC+/D
closed parenthesis pops out elements till the d) ABCD+/*
top element of the stack is its corresponding Answer: b
open parenthesis. If the stack is empty, Explanation: Infix expression is (A*B)+(C/D)
parenthesis is balanced otherwise it is AB*+(C/D)
unbalanced. AB*CD/+. Thus postfix expression is AB*CD/+.
30. What data structure would you mostly 33. Which data structure is needed to convert
likely see in a non recursive implementation infix notation to postfix notation?
of a recursive algorithm? a) Branch
a) Linked List b) Tree
b) Stack c) Queue
c) Queue d) Stack
d) Tree Answer: d
Answer: b Explanation: The Stack data structure is used
Explanation: In recursive algorithms, the to convert infix expression to postfix
order in which the recursive process comes expression. The purpose of stack is to reverse
back is the reverse of the order in which it the order of the operators in the expression.
goes forward during execution. The compiler It also serves as a storage structure, as no
uses the stack data structure to implement operator can be printed until both of its
recursion. In the forwarding phase, the values operands have appeared.
of local variables, parameters and the return 34. The prefix form of A-B/ (C * D ^ E) is?
address are pushed into the stack at each a) -/*^ACBDE
recursion level. In the backing-out phase, the b) -ABCD*^DE
stacked address is popped and used to c) -A/B*C^DE
execute the rest of the code. d) -A/BC*^DE

DIWAKAR EDUCATION HUB Page 8


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c Answer: b
Explanation: Infix Expression is (A-B)/(C*D^E) Explanation: The postfix expression is
(-A/B)(C*D^E) evaluated using stack. We will get the infix
-A/B*C^DE. Thus prefix expression is - expression as
A/B*C^DE (5*(4+6))*(4+9/3). On solving the Infix
35. What is the result of the following Expression, we get
operation? (5*(10))*(4+3)
Top (Push (S, X)) = 50*7
a) X = 350.
b) X+S 39. Convert the following infix expressions
c) S into its equivalent postfix expressions
d) XS (A + B ⋀D)/(E – F)+G
Answer: a a) (A B D ⋀ + E F – / G +)
Explanation: The function Push(S,X) pushes b) (A B D +⋀ E F – / G +)
the value X in the stack S. Top() function gives c) (A B D ⋀ + E F/- G +)
the value which entered last. X entered into d) (A B D E F + ⋀ / – G +)
stack S at last. Answer: a
36. The prefix form of an infix expression (p + Explanation: The given infix expression is (A +
q) – (r * t) is? B ⋀D)/(E – F)+G.
a) + pq – *rt (A B D ^ + ) / (E – F) +G
b) – +pqr * t (A B D ^ + E F – ) + G. ‘/’ is present in stack.
c) – +pq * rt A B D ^ + E F – / G +. Thus Postfix Expression
d) – + * pqrt is A B D ^ + E F – / G +.
Answer: c 40. Convert the following Infix expression to
Explanation: Given Infix Expression is ((p+q)- Postfix form using a stack
(r*t)) x + y * z + (p * q + r) * s, Follow usual
(+pq)-(r*t) precedence rule and assume that the
(-+pq)(r*t) expression is legal.
-+pq*rt. Thus prefix expression is -+pq*rt. a) xyz*+pq*r+s*+
37. Which data structure is used for b) xyz*+pq*r+s+*
implementing recursion? c) xyz+*pq*r+s*+
a) Queue d) xyzp+**qr+s*+
b) Stack Answer: a
c) Array Explanation: The Infix Expression is x + y * z +
d) List (p * q + r) * s.
Answer: b (x y z ) + (p * q + r) * s. ‘+’, ‘*’ are present in
Explanation: Stacks are used for the stack.
implementation of Recursion. (x y z * + p q * r) * s. ‘+’ is present in stack.
38. The result of evaluating the postfix x y z * + p q * r + s * +. Thus Postfix
expression 5, 4, 6, +, *, 4, 9, 3, /, +, * is? Expression is x y z * + p q * r + s * +.
a) 600 41. Which of the following statement(s)
b) 350 about stack data structure is/are NOT
c) 650 correct?
d) 588 a) Linked List are used for implementing

DIWAKAR EDUCATION HUB Page 9


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Stacks c) Postfix Expression
b) Top of the Stack always contain the new d) Both Prefix and Postfix Expressions
node Answer: c
c) Stack is the FIFO data structure Explanation: The expression in which
d) Null link is present in the last node at the operator succeeds its operands is called
bottom of the stack postfix expression. The expression in which
Answer: c operator precedes the operands is called
Explanation: Stack follows LIFO. prefix expression. If an operator is present
42. Consider the following operation between two operands, then it is called infix
performed on a stack of size 5. expressions.
Push(1); 45. Assume that the operators +,-, X are left
Pop(); associative and ^ is right associative.
Push(2); The order of precedence (from highest to
Push(3); lowest) is ^, X, +, -. The postfix expression for
Pop(); the infix expression a + b X c – d ^ e ^ f is
Push(4); a) abc X+ def ^^ –
Pop(); b) abc X+ de^f^ –
Pop(); c) ab+c Xd – e ^f^
Push(5); d) -+aXbc^ ^def
After the completion of all operation, the Answer: b
number of elements present in stack are Explanation: Given Infix Expression is a + b X
a) 1 c – d ^ e ^ f.
b) 2 (a b c X +) (d ^ e ^ f). ‘–‘ is present in stack.
c) 3 (a b c X + d e ^ f ^ -). Thus the final expression
d) 4 is (a b c X + d e ^ f ^ -).
Answer: a 46. If the elements “A”, “B”, “C” and “D” are
Explanation: Number of elements present in placed in a stack and are deleted one at a
stack is equal to the difference between time, what is the order of removal?
number of push operations and number of a) ABCD
pop operations. Number of elements is 5- b) DCBA
4=1. c) DCAB
43. Which of the following is not an inherent d) ABDC
application of stack? Answer: b
a) Reversing a string Explanation: Stack follows LIFO(Last In First
b) Evaluation of postfix expression Out). So the removal order of elements are
c) Implementation of recursion DCBA.
d) Job scheduling 47. A linear list of elements in which deletion
Answer: d can be done from one end (front) and
Explanation: Job Scheduling is not performed insertion can take place only at the other end
using stacks. (rear) is known as a ?
44. The type of expression in which operator a) Queue
succeeds its operands is? b) Stack
a) Infix Expression c) Tree
b) Prefix Expression d) Linked list

DIWAKAR EDUCATION HUB Page 10


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: a b) DCBA
Explanation: Linear list of elements in which c) DCAB
deletion is done at front side and insertion at d) ABDC
rear side is called Queue. In stack we will Answer: a
delete the last entered element first. Explanation: Queue follows FIFO approach.
48. The data structure required for Breadth i.e. First in First Out Approach. So, the order
First Traversal on a graph is? of removal elements are ABCD.
a) Stack 52. A data structure in which elements can be
b) Array inserted or deleted at/from both the ends
c) Queue but not in the middle is?
d) Tree a) Queue
Answer: c b) Circular queue
Explanation: In Breadth First Search c) Dequeue
Traversal, BFS, starting vertex is first taken d) Priority queue
and adjacent vertices which are unvisited are Answer: c
also taken. Again, the first vertex which was Explanation: In dequeuer, we can insert or
added as an unvisited adjacent vertex list will delete elements from both the ends. In
be considered to add further unvisited queue, we will follow first in first out
vertices of the graph. To get first unvisited principle for insertion and deletion of
vertex we need to follows First In First Out elements. Element with least priority will be
principle. Queue uses FIFO principle. deleted in a priority queue.
49. A queue follows __________ 53. A normal queue, if implemented using an
a) FIFO (First In First Out) principle array of size MAX_SIZE, gets full when
b) LIFO (Last In First Out) principle a) Rear = MAX_SIZE – 1
c) Ordered array b) Front = (rear + 1)mod MAX_SIZE
d) Linear tree c) Front = rear + 1
Answer: a d) Rear = front
Explanation: Element first added in queue Answer: a
will be deleted first which is FIFO principle. Explanation: When Rear = MAX_SIZE – 1,
50. Circular Queue is also known as ________ there will be no space left for the elements to
a) Ring Buffer be added in queue. Thus queue becomes full.
b) Square Buffer 54. Queues serve major role in
c) Rectangle Buffer ______________
d) Curve Buffer a) Simulation of recursion
Answer: a b) Simulation of arbitrary linked list
Explanation: Circular Queue is also called as c) Simulation of limited resource allocation
Ring Buffer. Circular Queue is a linear data d) Simulation of heap sort
structure in which last position is connected Answer: c
back to the first position to make a circle. It Explanation: Simulation of recursion uses
forms a ring structure. stack data structure. Simulation of arbitrary
51. If the elements “A”, “B”, “C” and “D” are linked lists uses linked lists. Simulation of
placed in a queue and are deleted one at a resource allocation uses queue as first
time, in what order will they be removed? entered data needs to be given first priority
a) ABCD

DIWAKAR EDUCATION HUB Page 11


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
during resource allocation. Simulation of and deletion at the last node requires to
heap sort uses heap data structure. traverse through every node in the linked list.
55. Which of the following is not the type of Suppose there are n elements in a linked list,
queue? we need to traverse through each node.
a) Ordinary queue Hence time complexity becomes O(n).
b) Single ended queue 58. In linked list each node contain minimum
c) Circular queue of two fields. One field is data field to store
d) Priority queue the data second field is?
Answer: b a) Pointer to character
Explanation: Queue always has two ends. So, b) Pointer to integer
single ended queue is not the type of queue. c) Pointer to node
56. A linear collection of data elements d) Node
where the linear node is given by means of Answer: c
pointer is called? Explanation: Each node in a linked list
a) Linked list contains data and a pointer (reference) to the
b) Node list next node. Second field contains pointer to
c) Primitive list node.
d) Unordered list 59. What would be the asymptotic time
Answer: a complexity to add a node at the end of singly
Explanation: In Linked list each node has its linked list, if the pointer is initially pointing to
own data and the address of next node. the head of the list?
These nodes are linked by using pointers. a) O(1)
Node list is an object that consists of a list of b) O(n)
all nodes in a document with in a particular c) θ(n)
selected set of nodes. d) θ(1)
57. Consider an implementation of unsorted Answer: c
singly linked list. Suppose it has its Explanation: In case of a linked list having n
representation with a head pointer only. elements, we need to travel through every
Given the representation, which of the node of the list to add the element at the end
following operation can be implemented in of the list. Thus asymptotic time complexity is
O(1) time? θ(n).
i) Insertion at the front of the linked list 60. What would be the asymptotic time
ii) Insertion at the end of the linked list complexity to insert an element at the front
iii) Deletion of the front node of the linked list of the linked list (head is known)?
iv) Deletion of the last node of the linked list a) O(1)
a) I and II b) O(n)
b) I and III c) O(n2)
c) I, II and III d) O(n3)
d) I, II and IV Answer: b
Answer: b Explanation: To add an element at the front
Explanation: We know the head node in the of the linked list, we will create a new node
given linked list. Insertion and deletion of which holds the data to be added to the
elements at the front of the linked list linked list and pointer which points to head
completes in O (1) time whereas for insertion position in the linked list. The entire thing

DIWAKAR EDUCATION HUB Page 12


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
happens within O (1) time. Thus the of circular doubly linked lists, we will break
asymptotic time complexity is O (1). the link in both the lists and hook them
61. What would be the asymptotic time together. Thus circular doubly linked list
complexity to find an element in the linked concatenates two lists in O (1) time.
list? 64. Consider the following definition in c
a) O(1) programming language
b) O(n) struct node
c) O(n2) {
d) O(n4) int data;
Answer: b struct node * next;
Explanation: If the required element is in the
}
last position, we need to traverse the entire
typedef struct node NODE;
linked list. This will take O (n) time to search
the element. NODE *ptr;
62. What would be the asymptotic time Which of the following c code is used to
complexity to insert an element at the create new node?
second position in the linked list? a) ptr = (NODE*)malloc(sizeof(NODE));
a) O(1) b) ptr = (NODE*)malloc(NODE);
b) O(n) c) ptr = (NODE*)malloc(sizeof(NODE*));
c) O(n2) d) ptr = (NODE)malloc(sizeof(NODE));
d) O(n3)
Answer: a Answer: a
Explanation: A new node is created with the Explanation: As it represents the right way to
required element. The pointer of the new create a node.
node points the node to which the head node [Link] kind of linked list is best to answer
of the linked list is also pointing. The head question like “What is the item at position
node pointer is changed and it points to the n?”
new node which we created earlier. The a) Singly linked list
entire process completes in O (1) time. Thus b) Doubly linked list
the asymptotic time complexity to insert an c) Circular linked list
element in the second position of the linked d) Array implementation of linked list
list is O (1). Answer: d
63. The concatenation of two list can Explanation: Arrays provide random access
performed in O(1) time. Which of the to elements by providing the index value
following variation of linked list can be used? within square brackets. In the linked list, we
a) Singly linked list need to traverse through each element until
b) Doubly linked list we reach the nth position. Time taken to
c) Circular doubly linked list access an element represented in arrays is
d) Array implementation of list less than the singly, doubly and circular linked
Answer: c lists. Thus, array implementation is used to
Explanation: We can easily concatenate two access the item at the position n.
lists in O (1) time using singly or doubly linked 66. Linked lists are not suitable to for the
list, provided that we have a pointer to the implementation of?
last node at least one of the lists. But in case a) Insertion sort

DIWAKAR EDUCATION HUB Page 13


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
b) Radix sort Linked List
c) Polynomial manipulation c) Random access is not allowed in a typical
d) Binary search implementation of Linked Lists
Answer: d d) Access of elements in linked list takes less
Explanation: It cannot be implemented using time than compared to arrays
linked lists. Answer: d
67. Linked list is considered as an example of Explanation: To access an element in a linked
___________ type of memory allocation. list, we need to traverse every element until
a) Dynamic we reach the desired element. This will take
b) Static more time than arrays as arrays provide
c) Compile time random access to its elements.
d) Heap 71. What does the following function do for a
Answer: a given Linked List with first node as head?
Explanation: As memory is allocated at the void fun1(struct node* head)
run time. {
68. In Linked List implementation, a node if(head == NULL)
carries information regarding ___________ return;
a) Data fun1(head->next);
b) Link
printf("%d ", head->data);
c) Data and Link
d) Node }
Answer: b a) Prints all nodes of linked lists
Explanation: A linked list is a collection of b) Prints all nodes of linked list in reverse
objects linked together by references from an order
object to another object. By convention these c) Prints alternate nodes of Linked List
objects are names as nodes. Linked list d) Prints alternate nodes in reverse order
consists of nodes where each node contains
one or more data fields and a reference(link) Answer: b
to the next node. Explanation: fun1() prints the given Linked
69. Linked list data structure offers List in reverse manner.
considerable saving in _____________ For Linked List 1->2->3->4->5, fun1() prints 5-
>4->3->2->1.
a) Computational Time
b) Space Utilization 72. Which of the following sorting algorithms
c) Space Utilization and Computational Time can be used to sort a random linked list with
d) Speed Utilization minimum time complexity?
Answer: c a) Insertion Sort
Explanation: Linked lists saves both space b) Quick Sort
and time. c) Heap Sort
d) Merge Sort
70. Which of the following points is/are not
true about Linked List data structure when it Answer: d
is compared with array? Explanation: Both Merge sort and Insertion
a) Arrays have better cache locality that can sort can be used for linked lists. The slow
make them better in terms of performance random-access performance of a linked list
b) It is easy to insert and delete elements in makes other algorithms (such as quicksort)

DIWAKAR EDUCATION HUB Page 14


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
perform poorly, and others (such as Node *move_to_front(Node *head)
heapsort) completely impossible. Since worst {
case time complexity of Merge Sort is Node *p, *q;
O(nLogn) and Insertion sort is O(n2), merge if ((head == NULL: || (head->next ==
sort is preferred. NULL))
73. What is the output of following function return head;
for start pointing to first node of following
q = NULL; p = head;
linked list?
while (p-> next !=NULL)
1->2->3->4->5->6
{
void fun(struct node* start)
q = p;
{
p = p->next;
if(start == NULL)
}
return;
_______________________________
printf("%d ", start->data);
return head;
if(start->next != NULL )
}
fun(start->next->next);
printf("%d ", start->data);
a) q = NULL; p->next = head; head = p;
}
b) q->next = NULL; head = p; p->next = head;
a) 1 4 6 6 4 1 c) head = p; p->next = q; q->next = NULL;
b) 1 3 5 1 3 5 d) q->next = NULL; p->next = head; head = p;
c) 1 2 3 5
d) 1 3 5 5 3 1
Answer: d
Explanation: When while loop completes its
Answer: d execution, node ‘p’ refers to the last node
Explanation: fun() prints alternate nodes of whereas the ‘q’ node refers to the node
the given Linked List, first from head to end, before ‘p’ in the linked list. q->next=NULL
and then from end to head. makes q as the last node. p->next=head
If Linked List has even number of nodes, then places p as the first node. the head must be
skips the last node. modified to ‘p’ as ‘p’ is the starting node of
74. The following C function takes a simply- the list (head=p). Thus the sequence of steps
linked list as input argument. are q->next=NULL, p->next=head, head=p.
It modifies the list by moving the last element 75. The following C function takes a single-
to the front of the list and returns linked list of integers as a parameter and
the modified list. Some part of the code is left rearranges the elements of the list.
blank. Choose the correct alternative The function is called with the list containing
to replace the blank line. the integers 1, 2, 3, 4, 5, 6, 7 in the given
typedef struct node order. What will be the contents of the list
{ after the function completes execution?
int value; struct node
struct node *next; {
}Node; int value;
struct node *next;

DIWAKAR EDUCATION HUB Page 15


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
}; node X from given linked list?
void rearrange(struct node *list) a) Possible if X is not last node
{ b) Possible if size of linked list is even
struct node *p, * q; c) Possible if size of linked list is odd
d) Possible if X is not first node
int temp;
Answer: a
if ((!list) || !list->next)
Explanation:
return; Following are simple steps.
p = list; struct node *temp = X->next;
q = list->next; X->data = temp->data;
while(q) X->next = temp->next;
{ free(temp);
temp = p->value; 78. You are given pointers to first and last
p->value = q->value; nodes of a singly linked list, which of the
q->value = temp; following operations are dependent on the
p = q->next; length of the linked list?
q = p?p->next:0; a) Delete the first element
} b) Insert a new element as a first element
} c) Delete the last element of the list
d) Add a new element at the end of the list
a) 1, 2, 3, 4, 5, 6, 7
b) 2, 1, 4, 3, 6, 5, 7 Answer: c
c) 1, 3, 2, 5, 4, 7, 6 Explanation: Deletion of the first element of
d) 2, 3, 4, 5, 6, 7, 1 the list is done in O (1) time by deleting
memory and changing the first pointer.
Insertion of an element as a first element can
Answer: b
be done in O (1) time. We will create a node
Explanation: The function rearrange()
that holds data and points to the head of the
exchanges data of every node with its next
given linked list. The head pointer was
node. It starts exchanging data from the first
changed to a newly created node.
node itself.
Deletion of the last element requires a
76. In the worst case, the number of
pointer to the previous node of last, which
comparisons needed to search a singly linked
can only be obtained by traversing the list.
list of length n for a given element is
This requires the length of the linked list.
a) log 2 n
Adding a new element at the end of the list
b) n⁄2
can be done in O (1) by changing the pointer
c) log 2 n – 1
of the last node to the newly created node
d) n
and last is changed to a newly created node.
Answer: d
79. In the worst case, the number of
Explanation: In the worst case, the element
comparisons needed to search a singly linked
to be searched has to be compared with all
list of length n for a given element is
elements of linked list.
a) log2 n
77. Given pointer to a node X in a singly b) n⁄2
linked list. Only one pointer is given, pointer c) log2 n – 1
to head node is not given, can we delete the d) n

DIWAKAR EDUCATION HUB Page 16


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: d c) O(logn)
Explanation: The worst-case happens if the d) O(n2)
required element is at last or the element is Answer: b
absent in the list. For this, we need to Explanation: To count the number of
compare every element in the linked list. If n elements, you have to traverse through the
elements are there, n comparisons will entire list, hence complexity is O(n).
happen in the worst case. 83. What is the functionality of the following
80. Which of the following is not a code?
disadvantage to the usage of array? public void function(Node node)
a) Fixed size {
b) There are chances of wastage of memory if(size == 0)
space if elements inserted in an array are
head = node;
lesser than the allocated size
else
c) Insertion based on position
d) Accessing elements at specified positions {
Answer: d Node temp,cur;
Explanation: Array elements can be accessed for(cur = head; (temp =
in two steps. First, multiply the size of the [Link]())!=null; cur = temp);
data type with the specified position, second, [Link](node);
add this value to the base address. Both of }
these operations can be done in constant size++;
time, hence accessing elements at a given }
index/position is faster.
a) Inserting a node at the beginning of the list
81. What is the time complexity of inserting b) Deleting a node at the beginning of the list
at the end in dynamic arrays? c) Inserting a node at the end of the list
a) O(1) d) Deleting a node at the end of the list
b) O(n)
Answer: c
c) O(logn)
Explanation: The for loop traverses through
d) Either O(1) or O(n)
the list and then inserts a new node as
Answer: d [Link](node);
Explanation: Depending on whether the
84. What is the space complexity for deleting
array is full or not, the complexity in dynamic
a linked list?
array varies. If you try to insert into an array
a) O(1)
which is not full, then the element is simply
b) O(n)
stored at the end, this takes O(1) time. If you
c) Either O(1) or O(n)
try to insert into an array which is full, first
d) O(logn)
you will have to allocate an array with double
Answer: a
the size of the current array and then copy all
Explanation: You need a temp variable to
the elements into it and finally insert the new
element, this takes O(n) time. keep track of current node, hence the space
complexity is O(1).
82. What is the time complexity to count the
number of elements in the linked list? 85. Which of these is not an application of
linked list?
a) O(1)
a) To implement file systems
b) O(n)
b) For separate chaining in hash-tables
DIWAKAR EDUCATION HUB Page 17
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
c) To implement non-binary trees Node cur = head;
d) Random Access of elements while(cur!=null)
{
Answer: d size++;
Explanation: To implement file system, for cur = [Link]();
separate chaining in hash-tables and to
}
implement non-binary trees linked lists are
}
used. Elements are accessed sequentially in
linked list. Random access of elements is not d)
an applications of linked list. public int length(Node head)
86. Which of the following piece of code has {
the functionality of counting the number of int size = 0;
elements in the list? Node cur = head;
a) while(cur!=null)
public int length(Node head) {
{ size++;
int size = 0; cur = [Link]().getNext();
Node cur = head; }
while(cur!=null) return size;
{ }
size++; Answer: a
cur = [Link](); Explanation: ‘cur’ pointer traverses through
} list and increments the size variable until the
return size; end of list is reached.
}
b) 87. How do you insert an element at the
beginning of the list?
public int length(Node head)
a)
{
public void insertBegin(Node node)
int size = 0;
{
Node cur = head;
[Link](head);
while(cur!=null)
head = node;
{
size++;
cur = [Link]();
}
size++;
b)
}
public void insertBegin(Node node)
return size;
{
}
head = node;
c)
[Link](head);
public int length(Node head)
size++;
{
}
int size = 0;
c)

DIWAKAR EDUCATION HUB Page 18


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
public void insertBegin(Node node) c) Find and return the position of the given
{ element in the list
Node temp = [Link]() d) Find and insert a new element in the list
[Link](temp); Answer: c
head = node; Explanation: When temp is equal to data, the
position of data is returned.
size++;
89. Which of the following is false about a
}
doubly linked list?
d) a) We can navigate in both the directions
public void insertBegin(Node node) b) It requires more space than a singly linked
{ list
Node temp = [Link]() c) The insertion and deletion of a node take a
[Link](temp); bit longer
node = head; d) Implementing a doubly linked list is easier
size++; than singly linked list
} Answer: d
Explanation: A doubly linked list has two
Answer: a
pointers ‘left’ and ‘right’ which enable it to
Explanation: Set the ‘next’ pointer point to
traverse in either direction. Compared to
the head of the list and then make this new
singly liked list which has only a ‘next’
node as the head.
pointer, doubly linked list requires extra
space to store this extra pointer. Every
insertion and deletion requires manipulation
88. What is the functionality of the following
of two pointers, hence it takes a bit longer
piece of code?
time. Implementing doubly linked list involves
public int function(int data) setting both left and right pointers to correct
{ nodes and takes more time than singly linked
Node temp = head; list.
int var = 0; 90. What is a memory efficient double linked
while(temp != null) list?
{ a) Each node has only one pointer to traverse
if([Link]() == data) the list back and forth
{ b) The list has breakpoints for faster traversal
c) An auxiliary singly linked list acts as a
return var;
helper list to traverse through the doubly
} linked list
var = var+1; d) A doubly linked list that uses bitwise AND
temp = [Link](); operator for storing addresses
} Answer: a
return Integer.MIN_VALUE; Explanation: Memory efficient doubly linked
} list has only one pointer to traverse the list
a) Find and delete a given element in the list back and forth. The implementation is based
b) Find and return the given element in the on pointer difference. It uses bitwise XOR
list operator to store the front and rear pointer

DIWAKAR EDUCATION HUB Page 19


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
addresses. Instead of storing actual memory c) head-6-1-2-3-4-5-0-tail
address, every node store the XOR address of d) head-0-1-2-3-4-5-tail
previous and next nodes. Answer: c
91. How do you calculate the pointer Explanation: The given sequence of
difference in a memory efficient double operations perform addition of nodes at the
linked list? head and tail of the list.
a) head xor tail 94. What is the functionality of the following
b) pointer to previous node xor pointer to piece of code?
next node public int function()
c) pointer to previous node – pointer to next {
node
Node temp = [Link]();
d) pointer to next node – pointer to previous
node [Link]([Link]());
Answer: b [Link]().setNext(tail);
Explanation: The pointer difference is size--;
calculated by taking XOR of pointer to return [Link]();
previous node and pointer to the next node. }
92. What is the worst case time complexity of a) Return the element at the tail of the list
inserting a node in a doubly linked list? but do not remove it
a) O(nlogn) b) Return the element at the tail of the list
b) O(logn) and remove it from the list
c) O(n) c) Return the last but one element from the
d) O(1) list but do not remove it
Answer: c d) Return the last but one element at the tail
Explanation: In the worst case, the position of the list and remove it from the list
to be inserted maybe at the end of the list,
hence you have to traverse through the Answer: b
entire list to get to the correct position, Explanation: The previous and next pointers
hence O(n). of the tail and the last but one element are
93. Consider the following doubly linked list: manipulated, this suggests that the last node
head-1-2-3-4-5-tail is being removed from the list.
What will be the list after performing the 95. Consider the following doubly linked list:
given sequence of operations? head-1-2-3-4-5-tail
Node temp = new What will be the list after performing the
Node(6,head,[Link]()); given sequence of operations?
Node temp1 = new Node temp = new
Node(0,[Link](),tail); Node(6,head,[Link]());
[Link](temp); [Link](temp);
[Link]().setPrev(temp); [Link]().setPrev(temp);
[Link](temp1); Node temp1 = [Link]();
[Link]().setNext(temp1); [Link]([Link]());
a) head-0-1-2-3-4-5-6-tail [Link]().setNext(tail);
b) head-1-2-3-4-5-6-tail a) head-6-1-2-3-4-5-tail
b) head-6-1-2-3-4-tail
DIWAKAR EDUCATION HUB Page 20
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
c) head-1-2-3-4-5-6-tail head’s next node, return the data stored in
d) head-1-2-3-4-5-tail head and make this next node as the head.
97. What is the functionality of the following
Answer: b code? Choose the most appropriate answer.
Explanation: A new node is added to the public int function()
head of the list and a node is deleted from {
the tail end of the list. if(head == null)
96. What is the functionality of the following return Integer.MIN_VALUE;
code? Choose the most appropriate answer.
int var;
Node temp = head;
public int function()
Node cur;
{
while([Link]() != head)
if(head == null)
{
return Integer.MIN_VALUE;
cur = temp;
int var;
temp = [Link]();
Node temp = head;
}
while([Link]() != head)
if(temp == head)
temp = [Link]();
{
if(temp == head)
var = [Link]();
{
head = null;
var = [Link]();
return var;
head = null;
}
return var;
var = [Link]();
}
[Link](head);
[Link]([Link]());
return var;
var = [Link]();
}
head = [Link]();
a) Return data from the end of the list
return var; b) Returns the data and deletes the node at
} the end of the list
a) Return data from the end of the list c) Returns the data from the beginning of the
b) Returns the data and deletes the node at list
the end of the list d) Returns the data and deletes the node
c) Returns the data from the beginning of the from the beginning of the list
list
d) Returns the data and deletes the node Answer: b
from the beginning of the list Explanation: First traverse through the list to
find the end node, also have a trailing pointer
Answer: d to find the penultimate node, make this
Explanation: First traverse through the list to trailing pointer’s ‘next’ point to the head and
find the end node, then manipulate the ‘next’ return the data stored in the ‘temp’ node.
pointer such that it points to the current 98. Which of the following is false about a
circular linked list?
DIWAKAR EDUCATION HUB Page 21
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
a) Every node has a successor while((temp != head) &&
b) Time complexity of inserting a new node at (!([Link]() == data)))
the head of the list is O(1) {
c) Time complexity for deleting the last node temp =
is O(n) [Link]();
d) We can traverse the whole circular linked flag = 1;
list by starting from any point
break;
}
Answer: b
}
Explanation: Time complexity of inserting a
new node at the head of the list is O(n) if(flag)
because you have to traverse through the list
to find the tail node. [Link]("success");
99. Consider a small circular linked list. How else
to detect the presence of cycles in this list [Link]("fail");
effectively? }
a) Keep one node as head and traverse a) Print success if a particular element is not
another temp node till the end to check if its found
‘next points to head b) Print fail if a particular element is not
b) Have fast and slow pointers with the fast found
pointer advancing two nodes at a time and c) Print success if a particular element is
slow pointer advancing by one node at a time equal to 1
c) Cannot determine, you have to pre-define d) Print fail if the list is empty
if the list contains cycles View Answer
d) Circular linked list itself represents a cycle. Answer: b
So no new cycles cannot be generated Explanation: The function prints fail if the
Answer: b given element is not found. Note that this
Explanation: Advance the pointers in such a option is inclusive of option d, the list being
way that the fast pointer advances two nodes empty is one of the cases covered.
at a time and slow pointer advances one 101. What is the time complexity of searching
node at a time and check to see if at any for an element in a circular linked list?
given instant of time if the fast pointer points a) O(n)
to slow pointer or if the fast pointer’s ‘next’ b) O(nlogn)
points to the slow pointer. This is applicable c) O(1)
for smaller lists. d) O(n2)
100. What is the functionality of the following
piece of code? Select the most appropriate Answer: a
public void function(int data) Explanation: In the worst case, you have to
{ traverse through the entire list of n elements.
int flag = 0; 102. Which of the following application
if( head != null) makes use of a circular linked list?
{ a) Undo operation in a text editor
Node temp = b) Recursive function calls
[Link](); c) Allocating CPU to resources

DIWAKAR EDUCATION HUB Page 22


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
d) Implement Hash Tables 105. What does the following function check
for? (all necessary headers to be included and
Answer: c function is called from main)
Explanation: Generally, round robin fashion #define MAX 10
is employed to allocate CPU time to
resources which makes use of the circular typedef struct stack
linked list data structure. Recursive function {
calls use stack data structure. Undo
int top;
Operation in text editor uses doubly linked
lists. Hash tables uses singly linked lists. int item[MAX];
103. What differentiates a circular linked list }stack;
from a normal linked list?
a) You cannot have the ‘next’ pointer point to int function(stack *s)
null in a circular linked list {
b) It is faster to traverse the circular linked list if(s->top == -1)
c) You may or may not have the ‘next’ pointer return 1;
point to null in a circular linked list else return 0;
d) Head node is known in circular linked list
}
Answer: c
a) full stack
Explanation: The ‘next’ pointer points to null
b) invalid index
only when the list is empty, otherwise it
c) empty stack
points to the head of the list. Every node in
d) infinite stack
circular linked list can be a starting
point(head).
Answer: c
104. Which of the following real world
Explanation: An empty stack is represented
scenarios would you associate with a stack
with the top-of-the-stack(‘top’ in this case) to
data structure?
be equal to -1.
a) piling up of chairs one above the other
b) people standing in a line to be serviced at a 106. What does ‘stack underflow’ refer to?
counter a) accessing item from an undefined stack
c) offer services based on the priority of the b) adding items to a full stack
c) removing items from an empty stack
customer
d) index out of bounds exception
d) tatkal Ticket Booking in IRCTC

Answer: c
Answer: a
Explanation: Removing items from an empty
Explanation: Stack follows Last In First Out
stack is termed as stack underflow.
(LIFO) policy. Piling up of chairs one above
the other is based on LIFO, people standing in 107. What is the output of the following
a line is a queue and if the service is based on program?
priority, then it can be associated with a public class Stack
priority queue. Tatkal Ticket Booking Follows {
First in First Out Policy. People who click the protected static final int CAPACITY =
book now first will enter the booking page 100;
first. protected int size,top = -1;

DIWAKAR EDUCATION HUB Page 23


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
protected Object stk[]; {
Stack myStack = new Stack();
public Stack() [Link](10);
{ Object element1 =
stk = new Object[CAPACITY]; [Link]();
} Object element2 =
[Link]();
public void push(Object item)
{ [Link](element2);
if(size_of_stack==size) }
{ }
a) stack is full
[Link]("Stack overflow"); b) 20
c) 0
return;
d) -999
}
else
Answer: d
{ Explanation: The first call to pop() returns 10,
top++; whereas the second call to pop() would result
stk[top]=item; in stack underflow and the program returns -
} 999.
} 108. What is the time complexity of pop()
public Object pop() operation when the stack is implemented
{ using an array?
a) O(1)
if(top<0)
b) O(n)
{
c) O(logn)
return -999; d) O(nlogn)
} Answer: a
else Explanation: pop() accesses only one end of
{ the structure, and hence constant time.
Object ele=stk[top]; 109. Which of the following array position
top--; will be occupied by a new element being
size_of_stack--; pushed for a stack of size N
return ele; elements(capacity of stack > N).
a) S[N-1]
}
b) S[N]
}
c) S[1]
} d) S[0]
Answer: b
public class StackDemo Explanation: Elements are pushed at the end,
{ hence N.
public static void main(String args[])

DIWAKAR EDUCATION HUB Page 24


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
110. What happens when you pop from an array ‘a’ is pushed into the stack, and then
empty stack while implementing using the the elements are popped out into the array
Stack ADT in Java? ‘b’. Stack is a LIFO structure, this results in
a) Undefined error reversing the given array.
b) Compiler displays a warning 112. Array implementation of Stack is not
c) EmptyStackException is thrown dynamic, which of the following statements
d) NoStackException is thrown supports this argument?
Answer: c a) space allocation for array is fixed and
Explanation: The Stack ADT throws an cannot be changed during run-time
EmptyStackException if the stack is empty b) user unable to give the input for stack
and a pop() operation is tried on it. operations
111. What is the functionality of the following c) a runtime exception halts execution
piece of Java code? d) improper program compilation
Assume: ‘a’ is a non empty array of integers,
the Stack class creates an array of specified Answer: a
size and provides a top pointer indicating Explanation: You cannot modify the size of
TOS(top of stack), push and pop have normal an array once the memory has been
meaning. allocated, adding fewer elements than the
public void some_function(int[] a) array size would cause wastage of space, and
{ adding more elements than the array size at
Stack S=new Stack([Link]); run time would cause Stack Overflow.
int[] b=new int[[Link]]; 113. Which of the following array element
will return the top-of-the-stack-element for a
for(int i=0;i<[Link];i++)
stack of size N elements(capacity of stack >
{
N).
[Link](a[i]); a) S[N-1]
} b) S[N]
for(int i=0;i<[Link];i++) c) S[N-2]
{ d) S[N+1]
b[i]=(int)([Link]());
} Answer: a
[Link]("output :"); Explanation: Array indexing start from 0,
hence N-1 is the last index.
for(int i=0;i<[Link];i++)
114. Consider these functions:
{
push() : push an element into the stack
[Link](b[i]);
pop() : pop the top-of-the-stack element
} top() : returns the item stored in top-of-the-
} stack-node
a) print alternate elements of array What will be the output after performing
b) duplicate the given array these sequence of operations
c) parentheses matching push(20);
d) reverse the array push(4);
Answer: d top();
Explanation: Every element from the given pop();
DIWAKAR EDUCATION HUB Page 25
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
pop(); Answer: d
pop(); Explanation: Deletion of the head node in the
push(5); linked list is taken as the best case. The
top(); successor of the head node is changed to
head and deletes the predecessor of the
a) 20
newly assigned head node. This process
b) 4
completes in O(1) time.
c) stack underflow
d) 5 118. Which of the following statements are
not correct with respect to Singly Linked
List(SLL) and Doubly Linked List(DLL)?
Answer: d
a) Complexity of Insertion and Deletion at
Explanation: 20 and 4 which were pushed are
known position is O(n) in SLL and O(1) in DLL
popped by the two pop() statements, the
b) SLL uses lesser memory per node than DLL
recent push() is 5, hence top() returns 5.
c) DLL has more searching power than SLL
115. Which of the following data structures d) Number of node fields in SLL is more than
can be used for parentheses matching? DLL
a) n-ary tree
Answer: d
b) queue
Explanation: To insert and delete at known
c) priority queue
positions requires complete traversal of the
d) stack
list in worst case in SLL, SLL consists of an
item and a node field, while DLL has an item
Answer: d and two node fields, hence SLL occupies
Explanation: For every opening brace, push it lesser memory, DLL can be traversed both
into the stack, and for every closing brace, ways(left and right), while SLL can traverse in
pop it off the stack. Do not take action for only one direction, hence more searching
any other character. In the end, if the stack is power of DLL. Node fields in SLL is 2 (data and
empty, then the input has balanced address of next node) whereas in DLL is
parentheses.
3(data, address to next node, address to
116. Minimum number of queues to previous node).
implement stack is ___________
a) 3 119. What does the following function do?
b) 4
public Object some_func()throws
c) 1
emptyStackException
d) 2
{
Answer: c if(isEmpty())
Explanation: Use one queue and one counter throw new
to count the number of elements in the emptyStackException("underflow");
queue. return [Link]();
117. What is the best case time complexity of }
deleting a node in Singly Linked list? a) pop
a) O (n) b) delete the top-of-the-stack element
b) O (n2) c) retrieve the top-of-the-stack element
c) O (nlogn) d) push operation
d) O (1)
DIWAKAR EDUCATION HUB Page 26
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c Answer: b
Explanation: This code is only retrieving the Explanation: Adding items to a full stack is
top element, note that it is not equivalent to termed as stack underflow.
pop operation as you are not setting the 121. What is the space complexity of a linear
‘next’ pointer point to the next node in queue having n elements?
sequence. a) O(n)
119. What is the functionality of the following b) O(nlogn)
piece of code? c) O(logn)
public void display() d) O(1)
{ Answer: a
if(size == 0) Explanation: Because there are n elements.
122. Which of the following properties is
[Link]("underflow"); associated with a queue?
else a) First In Last Out
b) First In First Out
{
c) Last In First Out
Node current = first; d) Last In Last Out
while(current != null)
Answer: b
{ Explanation: Queue follows First In First Out
structure.
[Link]([Link]()); 123. In a circular queue, how do you
current = increment the rear end of the queue?
[Link](); a) rear++
} b) (rear+1) % CAPACITY
} c) (rear % CAPACITY)+1
} d) rear–
a) reverse the list
b) display the list Answer: b
c) display the list excluding top-of-the-stack- Explanation: Ensures rear takes the values
element from 0 to (CAPACITY-1).
d) reverse the list excluding top-of-the-stack- 124. What is the term for inserting into a full
element queue known as?
a) overflow
Answer: b b) underflow
Explanation: An alias of the node ‘first’ is c) null pointer exception
created which traverses through the list and d) program won’t be compiled
displays the elements.
120. What does ‘stack overflow’ refer to? Answer: a
a) accessing item from an undefined stack Explanation: Just as stack, inserting into a full
b) adding items to a full stack queue is termed overflow.
c) removing items from an empty stack 125. What is the time complexity of enqueue
d) index out of bounds exception operation?
a) O(logn)
b) O(nlogn)
DIWAKAR EDUCATION HUB Page 27
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
c) O(n) on their priority. Higher priority elements will
d) O(1) be deleted first whereas lower priority
elements will be deleted next. Queue data
Answer: d structure always follows FIFO principle.
Explanation: Enqueue operation is at the rear 128. In linked list implementation of queue, if
end, it takes O(1) time to insert a new item only front pointer is maintained, which of the
into the queue. following operation take worst case linear
126. What does the following piece of code time?
do? a) Insertion
public Object function() b) Deletion
{ c) To empty a queue
d) Both Insertion and To empty a queue
if(isEmpty())
Answer: d
return -999;
Explanation: Since front pointer is used for
else deletion, so worst time for the other two
{ cases.
Object high; 129. In linked list implementation of a queue,
high = q[front]; where does a new element be inserted?
return high; a) At the head of link list
} b) At the centre position in the link list
} c) At the tail of the link list
a) Dequeue d) At any position in the linked list
b) Enqueue Answer: c
c) Return the front element Explanation: Since queue follows FIFO so
d) Return the last element new element inserted at last.
130. In linked list implementation of a queue,
Answer: c front and rear pointers are tracked. Which of
Explanation: q[front] gives the element at these pointers will change during an insertion
the front of the queue, since we are not into a NONEMPTY queue?
moving the ‘front’ to the next element, a) Only front pointer
it is not a dequeue operation. b) Only rear pointer
127. What is the need for a circular queue? c) Both front and rear pointer
a) effective usage of memory d) No pointer will be changed
b) easier computations Answer: b
c) to delete elements based on priority Explanation: Since queue follows FIFO so
d) implement LIFO principle in queues new element inserted at last.
131. In linked list implementation of a queue,
Answer: a front and rear pointers are tracked. Which of
Explanation: In a linear queue, dequeue these pointers will change during an insertion
operation causes the starting elements of the into EMPTY queue?
array to be empty, and there is no way you a) Only front pointer
can use that space, while in a circular queue, b) Only rear pointer
you can effectively use that space. Priority c) Both front and rear pointer
queue is used to delete the elements based d) No pointer will be changed

DIWAKAR EDUCATION HUB Page 28


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c b) Overflow
Explanation: Since its the starting of queue, c) Front value
so both values are changed. d) Rear value
132. In case of insertion into a linked queue, Answer: a
a node borrowed from the __________ list is Explanation: To check whether there is
inserted in the queue. element in the list or not.
a) AVAIL 137. Which of the following is true about
b) FRONT linked list implementation of queue?
c) REAR a) In push operation, if new nodes are
d) NULL inserted at the beginning of linked list, then
Answer: a in pop operation, nodes must be removed
Explanation: All the nodes are collected in from end
AVAIL list. b) In push operation, if new nodes are
133. In linked list implementation of a queue, inserted at the beginning, then in pop
from where is the item deleted? operation, nodes must be removed from the
a) At the head of link list beginning
b) At the centre position in the link list c) In push operation, if new nodes are
c) At the tail of the link list inserted at the end, then in pop operation,
d) Node before the tail nodes must be removed from end
Answer: a d) In push operation, if new nodes are
Explanation: Since queue follows FIFO so inserted at the end, then in pop operation,
new element deleted from first. nodes must be removed from beginning
134. In linked list implementation of a queue, Answer: a
the important condition for a queue to be Explanation: It can be done by both the
empty is? methods.
a) FRONT is null 138. With what data structure can a priority
b) REAR is null queue be implemented?
c) LINK is empty a) Array
d) FRONT==REAR-1 b) List
Answer: a c) Heap
Explanation: Because front represents the d) Tree
deleted nodes. Answer: d
135. The essential condition which is checked Explanation: Priority queue can be
before insertion in a linked queue is? implemented using an array, a list, a binary
a) Underflow search tree or a heap, although the most
b) Overflow efficient one being the heap.
c) Front value 139. Which of the following is not an
d) Rear value application of priority queue?
Answer: b a) Huffman codes
Explanation: To check whether there is space b) Interrupt handling in operating system
in the queue or not. c) Undo operation in text editors
136. The essential condition which is checked d) Bayesian spam filter
before deletion in a linked queue is?
a) Underflow
DIWAKAR EDUCATION HUB Page 29
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c b) O(logn)
Explanation: Undo operation is achieved c) O(n)
using a stack. d) O(n2)
140. What is the time complexity to insert a Answer: c
node based on key in a priority queue? Explanation: In the worst case, you might
a) O(nlogn) have to traverse the entire list.
b) O(logn) 144. What is the functionality of the following
c) O(n) piece of code?
d) O(n2) public Object delete_key()
Answer: c {
Explanation: In the worst case, you might if(count == 0)
have to traverse the entire list.
{
141. What is not a disadvantage of priority
[Link]("Q is
scheduling in operating systems?
empty");
a) A low priority process might have to wait
indefinitely for the CPU [Link](0);
b) If the system crashes, the low priority }
systems may be lost permanently else
c) Interrupt handling {
d) Indefinite blocking Node cur = [Link]();
Answer: c Node dup = [Link]();
Explanation: The lower priority process Object e = [Link]();
should wait until the CPU completes the [Link](dup);
processing higher priority process. Interrupt
count--;
handling is an advantage as interrupts should
return e;
be given more priority than tasks at hand so
that interrupt can be serviced to produce }
desired results. }
142. Which of the following is not an a) Delete the second element in the list
advantage of priority queue? b) Return but not delete the second element
a) Easy to implement in the list
b) Processes with different priority can be c) Delete the first element in the list
efficiently handled d) Return but not delete the first element in
c) Applications with differing requirements the list
d) Easy to delete elements in any case
Answer: d Answer: c
Explanation: In worst case, the entire queue Explanation: A pointer is made to point at
has to be searched for the element having the first element in the list and one more to
highest priority. This will take more time than point to the second element, pointer
usual. So deletion of elements is not an manipulations are done such that the first
advantage. element is no longer being pointed by any
143. What is the time complexity to insert a other pointer, its value is returned.
node based on position in a priority queue? 145. What is a dequeue?
a) O(nlogn) a) A queue with insert/delete defined for

DIWAKAR EDUCATION HUB Page 30


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
both front and rear ends of the queue by ‘head’. Otherwise, traverse till the end of
b) A queue implemented with a doubly linked the list and insert the new node there.
list 147. What are the applications of dequeue?
c) A queue implemented with both singly and a) A-Steal job scheduling algorithm
doubly linked lists b) Can be used as both stack and queue
d) A queue with insert/delete defined for c) To find the maximum of all sub arrays of
front side of the queu size k
Answer: a d) To avoid collision in hash tables
Explanation: A dequeue or a double ended
queue is a queue with insert/delete defined Answer: d
for both front and rear ends of the queue. Explanation: All of the mentioned can be
146. What is the functionality of the following implemented with a dequeue.
piece of code? 148. What is the time complexity of deleting
public void function(Object item) from the rear end of the dequeue
{ implemented with a singly linked list?
Node temp=new Node(item,trail); a) O(nlogn)
if(isEmpty()) b) O(logn)
c) O(n)
{
d) O(n2)
[Link](temp);
[Link](trail); Answer: c
} Explanation: Since a singly linked list is used,
else first you have to traverse till the end, so the
{ complexity is O(n).
Node cur=[Link](); 149. After performing these set of
while([Link]()!=trail) operations, what does the final list look
{ contain?
cur=[Link](); InsertFront(10);
} InsertFront(20);
[Link](temp); InsertRear(30);
} DeleteFront();
size++; InsertRear(40);
} InsertRear(10);
a) Insert at the front end of the dequeue DeleteRear();
b) Insert at the rear end of the dequeue InsertRear(15);
c) Fetch the element at the rear end of the display();
dequeue a) 10 30 10 15
d) Fetch the element at the front end of the b) 20 30 40 15
dequeue c) 20 30 40 10
d) 10 30 40 15
Answer: b
Explanation: If the list is empty, this new Answer: d
node will point to ‘trail’ and will be pointed at Explanation: A careful tracing of the given

DIWAKAR EDUCATION HUB Page 31


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
operation yields the result. a) O(m)
10 b) O(n)
20 10 c) O(m*n)
20 10 30 d) Data is insufficient
10 30 Answer: a
10 30 40 Explanation: To perform deQueue operation
10 30 40 10 you need to pop each element from the first
10 30 40 stack and push it into the second stack. In this
10 30 40 15 case you need to pop ‘m’ times and need to
150. A Double-ended queue supports perform push operations also ‘m’ times. Then
operations such as adding and removing you pop the first element from this second
items from both the sides of the queue. They stack (constant time) and pass all the
support four operations like addFront(adding elements to the first stack (as done in the
item to top of the queue), addRear(adding beginning)(‘m-1’ times). Therfore the time
item to the bottom of the queue), complexity is O(m).
removeFront(removing item from the top of 152. Consider you have an array of some
the queue) and removeRear(removing item random size. You need to perform dequeue
from the bottom of the queue). You are given operation. You can perform it using stack
only stacks to implement this data structure. operation (push and pop) or using queue
You can implement only push and pop operations itself (enQueue and Dequeue).
operations. What are the total number of The output is guaranteed to be same. Find
stacks required for this operation?(you can some differences?
reuse the stack) a) They will have different time complexities
a) 1 b) The memory used will not be different
b) 2 c) There are chances that output might be
c) 3 different
d) 4 d) No differences
Answer: b Answer: a
Explanation: The addFront and removeFront Explanation: To perform operations such as
operations can be performed using one stack Dequeue using stack operation you need to
itself as push and pop are supported (adding empty all the elements from the current
and removing element from top of the stack) stack and push it into the next stack, resulting
but to perform addRear and removeRear you in a O(number of elements) complexity
need to pop each element from the current whereas the time complexity of dequeue
stack and push it into another stack, push or operation itself is O(1). And there is a need of
pop the element as per the asked operation a extra stack. Therefore more memory is
from this stack and in the end pop elements needed.
from this stack to the first stack. 153. Consider you have a stack whose
151. You are asked to perform a queue elements in it are as follows.
operation using a stack. Assume the size of 5 4 3 2 << top
the stack is some value ‘n’ and there are ‘m’ Where the top element is 2.
number of variables in this stack. The time You need to get the following stack
complexity of performing deQueue operation 6 5 4 3 2 << top
is (Using only stack operations like push and The operations that needed to be performed
pop)(Tightly bound).
DIWAKAR EDUCATION HUB Page 32
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
are (You can perform only push and pop): c) Extra memory is not required
a) Push(pop()), push(6), push(pop()) d) There are no problem
b) Push(pop()), push(6) Answer: a
c) Push(pop()), push(pop()), push(6) Explanation: To perform Queue operations
d) Push(6) such as enQueue and deQueue there is a
Answer: a need of emptying all the elements of a
Explanation: By performing push(pop()) on all current stack and pushing elements into the
elements on the current stack to the next next stack and vice versa. Therfore it has a
stack you get 2 3 4 5 << [Link](6) and time complexity of O(n) and the need of extra
perform push(pop()) you’ll get back 6 5 4 3 2 stack as well, may not be feasible for a large
<< top. You have actually performed dataset.
enQueue operation using push and pop. 156. Consider yourself to be in a planet
154. A double-ended queue supports where the computational power of chips to
operations like adding and removing items be slow. You have an array of size [Link]
from both the sides of the queue. They want to perform enqueue some element into
support four operations like addFront(adding this array. But you can perform only push and
item to top of the queue), addRear(adding pop operations .Push and pop operation both
item to the bottom of the queue), take 1 sec respectively. The total time
removeFront(removing item from the top of required to perform enQueue operation is?
the queue) and removeRear(removing item a) 20
from the bottom of the queue). You are given b) 40
only stacks to implement this data structure. c) 42
You can implement only push and pop d) 43
operations. What’s the time complexity of Answer: d
performing addFront and addRear? (Assume Explanation: First you have to empty all the
‘m’ to be the size of the stack and ‘n’ to be elements of the current stack into the
the number of elements) temporary stack, push the required element
a) O(m) and O(n) and empty the elements of the temporary
b) O(1) and O(n) stack into the original stack. Therfore taking
c) O(n) and O(1) 10+10+1+11+11= 43 seconds.
d) O(n) and O(m) 157. You have two jars, one jar which has 10
Answer: b rings and the other has none. They are placed
Explanation: addFront is just a normal push one above the other. You want to remove the
operation. Push operation is of O(1). last ring in the jar. And the second jar is weak
Whereas addRear is of O(n) as it requires two and cannot be used to store rings for a long
push(pop()) operations of all elements of a time.
stack. a) Empty the first jar by removing it one by
155. Why is implementation of stack one from the first jar and placing it into the
operations on queues not feasible for a large second jar
dataset (Asssume the number of elements in b) Empty the first jar by removing it one by
the stack to be n)? one from the first jar and placing it into the
a) Because of its time complexity O(n) second jar and empty the second jar by
b) Because of its time complexity O(log(n)) placing all the rings into the first jar one by
one

DIWAKAR EDUCATION HUB Page 33


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
c) There exists no possible way to do this 160. To implement a stack using queue(with
d) Break the jar and remove the last on only enqueue and dequeue operations), how
Answer: b many queues will you need?
Explanation: This is similar to performing a) 1
dequeue operation using push and pop only. b) 2
Elements in the first jar are taken out and c) 3
placed in the second jar. After removing the d) 4
last element from the first jar, remove all the Answer: b
elements in the second jar and place them in Explanation: Either the push or the pop has
the first jar. to be a costly operation, and the costlier
158. Given only a single array of size 10 and operation requires two queues.
no other memory is available. Which of the 161. What is the functionality of the following
following operation is not feasible to piece of code?
implement (Given only push and pop public void fun(int x)
operation)? {
a) Push [Link](x);
b) Pop
}
c) Enqueue
d) Returntop a) Perform push() with push as the costlier
operation
Answer: c
b) Perform push() with pop as the costlier
Explanation: To perform Enqueue using just
operation
push and pop operations, there is a need of
c) Perform pop() with push as the costlier
another array of same size. But as there is no
operation
extra available memeory, the given operation
d) Perform pop() with pop as the costlier
is not feasible.
operation
159. Given an array of size n, let’s assume an
element is ‘touched’ if and only if some
Answer: b
operation is performed on it(for example, for
Explanation: offer() suggests that it is a push
performing a pop operation the top element
operation, but we see that it is performed
is ‘touched’). Now you need to perform
with only one queue, hence the pop
Dequeue operation. Each element in the
operation is costlier.
array is touched atleast?
a) Once 162. Reversing a word using stack can be
b) Twice used to find if the given word is a palindrome
c) Thrice or not.
d) Four times a) True
b) False
Answer: d
Explanation: First each element from the first Answer: a
stack is popped, then pushed into the second Explanation: This application of stack can also
stack, dequeue operation is done on the top be used to find if the given word is a
of the stack and later the each element of palindrome because, if the reversed is same
second stack is popped then pushed into the as that of the original word, the given word is
a palindrome.
first stack. Therfore each element is touched
four times. 163. Which is the most appropriate data
structure for reversing a word?
DIWAKAR EDUCATION HUB Page 34
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
a) queue c) XOR
b) stack d) NOR
c) tree Answer: a
d) graph Explanation: 1 OR 1 = 1, 0 OR 1 = 1, any bit
Answer: b OR’ed with 1 gives 1.
Explanation: Stack is the most appropriate 168. Which of the following bitwise
data structure for reversing a word because operations will you use to set a particular bit
stack follows LIFO principle. to 0?
164. Operations required for reversing a a) OR
word or a string using stack are push() and b) AND
pop(). c) XOR
a) True d) NAND
b) False Answer: b
Answer: a Explanation: 1 AND 0 = 0, 0 AND 0 = 0, any
Explanation: Push operation inserts a bit AND with 0 gives 0.
character into the stack and pop operation 169. Which of the following bitwise
pops the top of the stack. operations will you use to toggle a particular
165. What is the time complexity of reversing bit?
a word using stack algorithm? a) OR
a) O (N log N) b) AND
b) O (N2) c) XOR
c) O (N) d) NOT
d) O (M log N) Answer: c
Answer: c Explanation: 1 XOR 1 = 0, 0 XOR 1 = 1, note
Explanation: The time complexity of that NOT inverts all the bits, while XOR
reversing a stack is mathematically found to toggles only a specified bit.
be O (N) where N is the input. 170. Which of the following is not an
166. What is a bit array? advantage of bit array?
a) Data structure for representing arrays of a) Exploit bit level parallelism
records b) Maximal use of data cache
b) Data structure that compactly stores bits c) Can be stored and manipulated in the
c) An array in which most of the elements register set for long periods of time
have the same value d) Accessing Individual Elements is easy
d) Array in which elements are not present in Answer: d
continuous locations Explanation: Individual Elements are difficult
Answer: b to access and can’t be accessed in some
Explanation: It compactly stores bits and programming languages. If random access is
exploits bit-level parallelism. more common than sequential access, they
167. Which of the following bitwise have to be compressed to byte/word array.
operations will you use to set a particular bit Exploit Bit parallelism, Maximal use of data
to 1? cache and storage and manipulation for
a) OR longer time in register set are all advantages
b) AND of bit array.

DIWAKAR EDUCATION HUB Page 35


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
171. What is a dynamic array? Answer: d
a) A variable size data structure Explanation: ArrayList is used to implement
b) An array which is created at runtime dynamic arrays in Java.
c) The memory to the array is allocated at 175. Which of the following is the correct
runtime syntax to declare an ArrayList in Java?
d) An array which is reallocated everytime a) ArrayList al = new ArrayList();
whenever new elements have to be added b) ArrayList al = new ArrayList[];
Answer: a c) ArrayList al() = new ArrayList();
Explanation: It is a varying-size list data d) ArrayList al[] = new ArrayList[];
structure that allows items to be added or Answer: a
removed, it may use a fixed sized array at the Explanation: This is a non-generic way of
back end. creating an ArrayList.
172. What is meant by physical size in a 176. Array is divided into two parts in
dynamic array? ____________
a) The size allocated to elements a) Hashed Array Tree
b) The size extended to add new elements b) Geometric Array
c) The size of the underlying array at the c) Bounded-size dynamic array
back-end d) Sparse Array
d) The size visible to users Answer: c
Answer: c Explanation: The first part stores the items of
Explanation: Physical size, also called array the dynamic array and the second part is
capacity is the size of the underlying array, reserved for new allocations.
which is the maximum size without relocation 177. Which of the following is a disadvantage
of data. of dynamic arrays?
173. The number of items used by the a) Locality of reference
dynamic array contents is its __________ b) Data cache utilization
a) Physical size c) Random access
b) Capacity d) Memory leak
c) Logical size Answer: d
d) Random size Explanation: Dynamic arrays share the
Answer: c advantage of arrays, added to it is the
Explanation: The number of items used by dynamic addition of elements to the array.
the dynamic array contents is called logical Memory can be leaked if it is not handled
size. Physical size is the size of the underlying properly during allocation and deallocation. It
array, which is the maximum size without is a disadvantage.
reallocation of data. 178. What are parallel arrays?
174. How will you implement dynamic arrays a) Arrays of the same size
in Java? b) Arrays allocated one after the other
a) Set c) Arrays of the same number of elements
b) Map d) Arrays allocated dynamically
c) HashMap Answer: c
d) List Explanation: Different arrays can be of
different data types but should contain same

DIWAKAR EDUCATION HUB Page 36


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
number of elements. Elements at b) Jump Search
corresponding index belong to a record. c) Binary Search
179. Which of the following is a disadvantage d) Fibonacci Search
of parallel array over the traditional arrays? Answer: c
a) When a language does not support Explanation: Since the array is sorted, binary
records, parallel arrays can be used search is preferred as its time complexity is
b) Increased locality of reference O(logn).
c) Ideal cache behaviour 183. Which of the following is not an
d) Insertion and Deletion becomes tedious application of sorted array?
Answer: d a) Commercial computing
Explanation: Insertion and deletion of b) Priority Scheduling
elements require to move every element c) Discrete Mathematics
from their initial positions. This will become d) Hash Tables
tedious. For Record collection, locality of Answer: d
reference and Ideal Cache behaviour we can Explanation: Sorted arrays have widespread
use parallel arrays. applications as all commercial computing
180. Which of the following is an advantage involves large data which is very useful if it is
of parallel arrays? sorted. It makes best use of locality of
a) Poor locality of reference for non- reference and data cache. Linked lists are
sequential access used in Hash Tables not arrays.
b) Very little direct language support 184. What is the worst case time complexity
c) Expensive to shrink or grow of inserting an element into the sorted array?
d) Increased Locality of Reference a) O(nlogn)
Answer: d b) O(logn)
Explanation: Elements in the parallel array c) O(n)
are accessed sequentially as one arrays holds d) O(n2)
the keys whereas other holds the values. This Answer: c
sequential access generally improves Locality Explanation: In the worst case, an element
of Reference. It is an advantage. must added to the front of the array, which
181. What is a sorted array? means that rest of the elements have to be
a) Arrays sorted in numerical order shifted, hence the worst case time complexity
b) Arrays sorted in alphabetical order becomes O(n).
c) Elements of the array are placed at equally 185. What is the order of a matrix?
spaced addresses in the memory a) number of rows X number of columns
d) All of the mentioned b) number of columns X number of rows
Answer: d c) number of rows X number of rows
Explanation: The array can be sorted in any d) number of columns X number of columns
way, numerical, alphabetical or any other Answer: a
way but the elements are placed at equally Explanation: The order of the matrix is the
spaced addresses. number of rows X number of columns.
182. To search for an element in a sorted 186. Which of the following property does
array, which searching technique can be not hold for matrix multiplication?
used? a) Associative
a) Linear Search b) Distributive

DIWAKAR EDUCATION HUB Page 37


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
c) Commutative 190. Which of the following don’t use
d) Additive Inverse matrices?
Answer: c a) In solving linear equations
Explanation: In matrix multiplication, AB != b) Image processing
BA c) Graph theory
187. How do you allocate a matrix using a d) Sorting numbers
single pointer in C?(r and c are the number of Answer: d
rows and columns respectively) Explanation: Numbers uses arrays(1-D) for
a) int *arr = malloc(r * c * sizeof(int)); sorting not matrices(2-D arrays). Solving
b) int *arr = (int *)malloc(r * c * sizeof(int)); linear equations is a separate field in
c) int *arr = (int *)malloc(r + c * sizeof(int)); Mathematics involving matrices, Image
d) int *arr = (int *)malloc(r * c * sizeof(arr)); processing stores the pixels in the form of
Answer: b matrices, and the graphs are represented
Explanation: Total number of elements in the with the help of matrices to indicate the
matrix will be r*c nodes and edges.
188. If row-major order is used, how is the 191. Which of the following is an advantage
following matrix stored in memory? of matrices?
abc a) Internal complexity
def b) Searching through a matrix is complex
ghi c) Not space efficient
a) ihgfedcba d) Graph Plotting
b) abcdefghi Answer: d
c) cfibehadg Explanation: Adjacency and Incidence
d) adgbehcfi Matrices are used to store vertices and edges
Answer: b of a graph. It is an advantage to plot graphs
Explanation: It starts with the first element easily using matrices. But Time complexity of
and continues in the same row until the end a matrix is O(n2) and sometimes the internal
of row is reached and then proceeds with the organization becomes tedious. They are all
next row. C follows row-major order. disadvantages of matrices.
189. If column-major order is used, how is 192. Matrix A when multiplied with Matrix C
the following matrix stored in memory? gives the Identity matrix I, what is C?
abc a) Identity matrix
def b) Inverse of A
ghi c) Square of A
a) ihgfedcba d) Transpose of A
b) abcdefghi Answer: b
c) cfibehadg Explanation: Any square matrix when
d) adgbehcfi multiplied with its inverse gives the identity
Answer: d matrix. Note that non square matrices are
Explanation: It starts with the first element not invertible.
and continues in the same column until the 193. What does the following piece of code
end of column is reached and then proceeds do?
with the next column. Fortran follows for(int i = 0; i < row; i++)
column-major order. {

DIWAKAR EDUCATION HUB Page 38


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
for(int j = 0; j < column; j++) 196. Who coined the term Sparse Matrix?
{ a) Harry Markowitz
if(i == j) b) James Sylvester
sum = sum + (array[i][j]); c) Chris Messina
d) Arthur Cayley
}
Answer: a
}
Explanation: Harry Markowitz coined the
[Link](sum);
term Sparse Matrix. James Sylvester coined
a) Normal of a matrix the term Matrix. Chris Messina coined the
b) Trace of a matrix term Hashtag and Arthur Cayley developed
c) Square of a matrix the algebraic aspects of a matrix.
d) Transpose of a matrix 197. Is O(n) the Worst case Time Complexity
for addition of two Sparse Matrix?
Answer: b a) True
Explanation: Trace of a matrix is the sum of b) False
the principal diagonal elements. Answer: a
194. Which matrix has most of the elements Explanation: In Addition, the matrix is
(not all) as Zero? traversed linearly, hence it has the time
a) Identity Matrix complexity of O(n) where n is the number of
b) Unit Matrix non-zero elements in the largest matrix
c) Sparse Matrix amongst two.
d) Zero Matrix
198. The matrix contains m rows and n
Answer: c columns. The matrix is called Sparse Matrix if
Explanation: Sparse Matrix is a matrix in ________
which most of the elements are Zero. Identity a) Total number of Zero elements > (m*n)/2
Matrix is a matrix in which all principle b) Total number of Zero elements = m + n
diagonal elements are 1 and rest of the c) Total number of Zero elements = m/n
elements are Zero. Unit Matrix is also called d) Total number of Zero elements = m-n
Identity Matrix. Zero Matrix is a matrix in Answer: a
which all the elements are Zero.
Explanation: For matrix to be Sparse Matrix,
195. What is the relation between Sparsity it should contain Zero elements more than
and Density of a matrix? the non-zero elements. Total elements of the
a) Sparsity = 1 – Density given matrix is m*n. So if Total number of
b) Sparsity = 1 + Density Zero elements > (m*n)/2, then the matrix is
c) Sparsity = Density*Total number of called Sparse Matrix.
elements 199. Which of the following is not the
d) Sparsity = Density/Total number of method to represent Sparse Matrix?
elements a) Dictionary of Keys
Answer: a b) Linked List
Explanation: Sparsity of a matrix is equal to 1 c) Array
minus Density of the matrix. The Sparsity of d) Heap
matrix is defined as the total number of Zero Answer: d
Valued elements divided total number of Explanation: Heap is not used to represent
elements.
Sparse Matrix while in Dictionary, rows and

DIWAKAR EDUCATION HUB Page 39


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
column numbers are used as Keys and values Answer: b
as Matrix entries, Linked List is used with Explanation: The number of inversions in an
each node of Four fields (Row, Column, array indicates how close or far the array is
Value, Next Node) (2D array is used to from being completely sorted. The array is
represent the Sparse Matrix with three fields sorted if the number of inversions are 0.
(Row, Column, Value). 204. How many inversions does a sorted
200. Is Sparse Matrix also known as Dense array have?
Matrix? a) 0
a) True b) 1
b) False c) 2
Answer: b d) cannot be determined
Explanation: Sparse Matrix is a matrix with Answer: a
most of the elements as Zero elements while Explanation: When an array is sorted then
Dense Matrix is a matrix with most of the there cannot be any inversion in the array. As
elements as Non-Zero element. the necessary condition for an inversion is
201. Which one of the following is a Special arr[i]>arr[j] and i<j.
Sparse Matrix? 205. What is the condition for two elements
a) Band Matrix arr[i] and arr[j] to form an inversion?
b) Skew Matrix a) arr[i]<arr[j]
c) Null matrix b) i < j
d) Unit matrix c) arr[i] < arr[j] and i < j
Answer: a d) arr[i] > arr[j] and i < j
Explanation: A band matrix is a sparse matrix Answer: d
whose non zero elements are bounded to a Explanation: For two elements to form an
diagonal band, comprising the main diagonal inversion the necessary condition is arr[i] >
and zero or more diagonals on either side. arr[j] and i < j. The number of inversions in an
202. In what way the Symmetry Sparse array indicate how close or far the array is
Matrix can be stored efficiently? from being completely sorted.
a) Heap 206. Under what condition the number of
b) Binary tree inversions in an array are maximum?
c) Hash table a) when the array is sorted
d) Adjacency List b) when the array is reverse sorted
Answer: b c) when the array is half sorted
Explanation: Since Symmetry Sparse Matrix d) depends on the given array
arises as the adjacency matrix of the Answer: b
undirected graph. Hence it can be stored Explanation: Number of inversions in an
efficiently as an adjacency list. array are maximum when the given array is
203. What does the number of inversions in reverse sorted. As the necessary condition for
an array indicate? an inversion is arr[i]>arr[j] and i<j.
a) mean value of the elements of array 207. What will be the resulting array after
b) measure of how close or far the array is rotating arr[]={1, 2, 3, 4, 5} by 2?
from being sorted a) 2, 1, 3, 4, 5
c) the distribution of values in the array b) 3, 4, 5, 1, 2
d) median value of the elements of array

DIWAKAR EDUCATION HUB Page 40


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
c) 4, 5, 1, 2, 3 Answer: b
d) 1, 2, 3, 5, 4 Explanation: It is a datastructure, which can
Answer: b make search in sorted linked list faster in the
Explanation: When the given array is rotated same way as binary search tree and sorted
by 2 then the resulting array will be array (using binary search) are faster.
Rotation 1: {2,3,4,5,1} [Link] of the following is true about the
Rotation 2: {3,4,5,1,2}. Move-To-Front Method for rearranging
Thus, the final array is {3,4,5,1,2}. nodes?
208. What will be the minimum number of a) node with highest access count is moved
jumps required to reach the end of the array to head of the list
arr[] = {1,3,6,3,6,8,5}? b) requires extra storage
a) 1 c) may over-reward infrequently accessed
b) 2 nodes
c) 3 d) requires a counter for each node
d) not possible to reach the end Answer: c
Answer: c Explanation: In Move-To-front Method the
Explanation: Each element of the array element which is searched is moved to the
represents the maximum number of steps head of the list. And if a node is searched
that can be taken forward from that element. even once, it is moved to the head of the list
If the first element is 0 then it is not possible and given maximum priority even if it is not
to reach the end. going to be accessed frequently in the future.
209. What will be the minimum number of Such a situation is referred to as over-
jumps required to reach the end of the array rewarding.
arr[] ={0,1,3,6,3,6,8,5}? 212. What is xor linked list ?
a) 1 a) uses of bitwise XOR operation to decrease
b) 2 storage requirements for doubly linked lists
c) 3 b) uses of bitwise XOR operation to decrease
d) not possible to reach the end storage requirements for linked lists
Answer: d c) uses of bitwise operations to decrease
Explanation: Each element of the array storage requirements for doubly linked lists
represents the maximum number of steps d) just another form of linked list
that can be taken forward from that element. Answer: a
So as the first element here is 0 so we cannot Explanation: Why we use bitwise XOR
move any further from the first element. operation is to decrease storage
Thus, it is not possible to reach the end of the requirements for doubly linked lists.
array. 213. What does a xor linked list have ?
210. What is a skip list? a) every node stores the XOR of addresses of
a) a linkedlist with size value in nodes previous and next nodes
b) a linkedlist that allows faster search within b) actuall memory address of next node
an ordered sequence c) every node stores the XOR of addresses of
c) a linkedlist that allows slower search within previous and next two nodes
an ordered sequence d) every node stores xor 0 and the current
d) a tree which is in the form of linked list node address

DIWAKAR EDUCATION HUB Page 41


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: a Answer: b
Explanation: Every node stores the XOR of Explanation: In memory the pointer address
addresses. for next node may not be adjacent or nearer
214. Consider a situation of writing a binary to each other and also array have wonderful
tree into a file with memory storage caching power from os and manipulating
efficiency in mind, is array representation of pointers is a overhead. Heap data structure is
tree is good? always a complete binary tree.
a) yes because we are overcoming the need 216. Can a tree stored in an array using either
of pointers and so space efficiency one of inorder or post order or pre order
b) yes because array values are indexable traversals be again reformed?
c) No it is not efficient in case of sparse trees a) Yes just traverse through the array and
and remaning cases it is fine form the tree
d) No linked list representation of tree is only b) No we need one more traversal to form a
fine tree
c) No in case of sparse trees
Answer: c d) Yes by using both inorder and array
Explanation: In case of sparse trees (where elements
one node per level in worst cases), the array
size (2h)-1 where h is height but only h Answer: b
indexes will be filled and (2h)-1-h nodes will Explanation: We need any two traversals for
be left unused leading to space wastage. tree formation but if some additional stuff or
215. Why is heap implemented using array techniques are used while storing a tree in an
representations than tree(linked list) array then one traversal can facilitate like
representations though both tree also storing null values of a node in array.
representations and heaps have same 217. How many children does a binary tree
complexities? have?
for binary heap a) 2
-insert: O(log n) b) any number of children
-delete min: O(log n) c) 0 or 1 or 2
d) 0 or 1
Answer: c
for a tree
Explanation: Can have atmost 2 nodes.
-insert: O(log n)
218. What is/are the disadvantages of
-delete: O(log n) implementing tree using normal arrays?
Then why go with array representation when a) difficulty in knowing children nodes of a
both are having same values ? node
a) arrays can store trees which are complete b) difficult in finding the parent of a node
and heaps are not complete c) have to know the maximum number of
b) lists representation takes more memory nodes possible before creation of trees
hence memory efficiency is less and go with d) difficult to implement
arrays and arrays have better caching Answer: c
c) lists have better caching Explanation: The size of array is fixed in
d) In lists insertion and deletion is difficult normal arrays. We need to know the number
of nodes in the tree before array declaration.

DIWAKAR EDUCATION HUB Page 42


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
It is the main disadvantage of using arrays to d) use another array parallel to the array with
represent binary trees. tree
219. What must be the ideal size of array if Answer: a
the height of tree is ‘l’? Explanation: Array cannot represent arbitrary
a) 2l-1 shaped trees. It can only be used in case of
b) l-1 complete trees. If every node stores data
c) l saying that which of its children exists in the
d) 2l array then elements can be accessed easily.
Answer: a 223. Advantages of linked list representation
Explanation: Maximum elements in a tree of binary trees over arrays?
(complete binary tree in worst case) of height a) dynamic size
‘L’ is 2L-1. Hence size of array is taken as 2L-1. b) ease of insertion/deletion
220. What are the children for node ‘w’ of a c) ease in randomly accessing a node
complete-binary tree in an array d) both dynamic size and ease in
representation? insertion/deletion
a) 2w and 2w+1
b) 2+w and 2-w Answer: d
c) w+1/2 and w/2 Explanation: It has both dynamic size and
d) w-1/2 and w+1/2 ease in insertion and deletion as advantages.
Answer: a 224. Disadvantages of linked list
Explanation: The left child is generally taken representation of binary trees over arrays?
as 2*w whereas the right child will be taken a) Randomly accessing is not possible
as 2*w+1 because root node is present at b) Extra memory for a pointer is needed with
index 0 in the array and to access every index every element in the list
position in the array. c) Difficulty in deletion
221. What is the parent for a node ‘w’ of a d) Random access is not possible and extra
complete binary tree in an array memory with every element
representation when w is not 0?
a) floor(w-1/2) Answer: d
b) ceil(w-1/2) Explanation: Random access is not possible
c) w-1/2 with linked lists.
d) w/2 225. Which of the following traversing
Answer: a algorithm is not used to traverse in a tree?
Explanation: Floor of w-1/2 because we can’t a) Post order
miss a node. b) Pre order
222. If the tree is not a complete binary tree c) Post order
then what changes can be made for easy d) Randomized
access of children of a node in the array?
a) every node stores data saying which of its Answer: d
children exist in the array Explanation: Generally, all nodes in a tree are
b) no need of any changes continue with 2w visited by using preorder, inorder and
and 2w+1, if node is at i postorder traversing algorithms.
c) keep a seperate table telling children of a 226. Level order traversal of a tree is formed
node with the help of

DIWAKAR EDUCATION HUB Page 43


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
a) breadth first search Answer: d
b) depth first search Explanation: We just replace a to be deleted
c) dijkstra’s algorithm node with last leaf node of a tree. this must
d) prims algorithm not be done in case of BST or heaps.
229. What may be the psuedo code for
Answer: a finding the size of a tree?
Explanation: Level order is similar to bfs. a) find_size(root_node–>left_node) + 1 +
227. Identify the reason which doesn’t play a find_size(root_node–>right_node)
key role to use threaded binary trees? b) find_size(root_node–>left_node) +
a) The storage required by stack and queue is find_size(root_node–>right_node)
more c) find_size(root_node–>right_node) – 1
b) The pointers in most of nodes of a binary d) find_size(root_node–>left_node + 1
tree are NULL
c) It is Difficult to find a successor node Answer: a
d) They occupy less size Explanation: Draw a tree and analyze the
expression. we are always taking size of left
Answer: d subtree and right subtree and adding root
Explanation: Threaded binary trees are value(1) to it and finally printing size.
introduced to make the Inorder traversal 230. What is missing in this logic of finding a
faster without using any stack or recursion. path in the tree for a given sum (i.e checking
Stack and Queue require more space and whether there will be a path from roots to
pointers in the majority of binary trees are leaf nodes with given sum)?
null and difficulties are raised while finding checkSum(struct bin-treenode *root , int
successor nodes. Size constraints are not sum) :
taken on threaded binary trees, but they if(root==null)
occupy less space than a stack/queue. return sum as 0
228. The following lines talks about deleting a else :
node in a binary tree.(the tree property must
leftover_sum=sum-root_node-->value
not be violated after deletion)
i) from root search for the node to be deleted //missing
ii) a) code for having recursive calls to either
iii) delete the node at only left tree or right trees or to both
what must be statement ii) and fill up subtrees depending on their existence
statement iii) b) code for having recursive calls to either
a) ii)-find random node,replace with node to only left tree or right trees
be deleted. iii)- delete the node c) code for having recursive calls to either
b) ii)-find node to be deleted. iii)- delete the only left tree
node at found location d) code for having recursive calls to either
c) ii)-find deepest node,replace with node to only right trees
be deleted. iii)- delete a node
d) ii)-find deepest node,replace with node to Answer: a
be deleted. iii)- delete the deepest node Explanation: if(left subtree and right subtree)
then move to both subtrees
else if only left subtree then move to left
subtree carrying leftover_sum parameter
DIWAKAR EDUCATION HUB Page 44
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
else if only right subtree then move to right c) printing ancestors of a node passed as
subtree carrying leftover_sum parameter. argument
231. What must be the missing logic below so d) printing nodes from leaf node to a node
as to print mirror of a tree as below as an passed as argument
example?
Answer: c
Explanation: We are checking if left or right
node is what the argument sent or else if not
the case then move to left node or right node
and print all nodes while searching for the
argument node.
233. What is the maximum number of
if(rootnode): children that a binary tree node can have?
mirror(rootnode-->left) a) 0
b) 1
mirror(rootnode-->right)
c) 2
d) 3
//missing Answer: c
Explanation: In a binary tree, a node can
end have atmost 2 nodes (i.e.) 0,1 or 2 left and
a) swapping of left and right nodes is missing right child.
b) swapping of left with root nodes is missing 234. The following given tree is an example
c) swapping of right with root nodes is for?
missing
d) nothing is missing

Answer: a
Explanation: Mirror is another tree with left
and right children of nodes are interchanged
as shown in the figure.
232. What is the code below trying to print?
void print(tree *root,tree *node) a) Binary tree
{ b) Binary search tree
if(root ==null) return 0 c) Fibonacci tree
d) AVL tree
if(root-->left==node || root-->right==node
|| print(root->left,node)||printf(root- Answer: a
>right,node) Explanation: The given tree is an example for
binary tree since has got two children and the
{
left and right children do not satisfy binary
print(root->data) search tree’s property, Fibonacci and AVL
} tree.
} 235. A binary tree is a rooted tree but not an
a) just printing all nodes ordered tree.
b) not a valid logic to do any task

DIWAKAR EDUCATION HUB Page 45


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
a) true
b) false
Answer: b
Explanation: A binary tree is a rooted tree
and also an ordered tree (i.e) every node in a
binary tree has at most two children.
236. How many common operations are
performed in a binary tree?
a) 1 a) inserting a leaf node
b) 2 b) inserting an internal node
c) 3 c) deleting a node with 0 or 1 child
d) 4 d) deleting a node with 2 children
Answer: c Answer: c
Explanation: Three common operations are Explanation: The above diagram is a
performed in a binary tree- they are depiction of deleting a node with 0 or 1 child
insertion, deletion and traversal. since the node D which has 1 child is deleted.
237. What is the traversal strategy used in 240. General ordered tree can be encoded
the binary tree? into binary trees.
a) depth-first traversal a) true
b) breadth-first traversal b) false
c) random traversal Answer: a
d) Priority traversal Explanation: General ordered tree can be
Answer: b mapped into binary tree by representing
Explanation: Breadth first traversal, also them in a left-child-right-sibling way.
known as level order traversal is the traversal 241. How many bits would a succinct binary
strategy used in a binary tree. It involves tree occupy?
visiting all the nodes at a given level. a) n+O(n)
238. How many types of insertion are b) 2n+O(n)
performed in a binary tree? c) n/2
a) 1 d) n
b) 2 Answer: b
c) 3 Explanation: A succinct binary tree occupies
d) 4 close to minimum possible space established
Answer: b by lower bounds. A succinct binary tree
Explanation: Two kinds of insertion operation would occupy 2n+O(n) bits.
is performed in a binary tree- inserting a leaf 242. The average depth of a binary tree is
node and inserting an internal node. given as?
239. What operation does the following a) O(N)
diagram depict? b) O(√N)
c) O(N2)
d) O(log N)
Answer: d
Explanation: The average depth of a binary

DIWAKAR EDUCATION HUB Page 46


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
tree is given as O(√N). In case of a binary visited before the right subtrees. In Inorder
search tree, it is O(log N). traversal, the Left subtree is visited first then
243. How many orders of traversal are the Root node then the Right subtree. In
applicable to a binary tree (In General)? postorder traversal, the Left subtree is visited
a) 1 first, then Right subtree and then the Root
b) 4 node is visited.
c) 2 247. Construct a binary tree using the
d) 3 following data.
Answer: d The preorder traversal of a binary tree is 1, 2,
Explanation: The three orders of traversal 5, 3, 4. The inorder traversal of the same
that can be applied to a binary tree are in- binary tree is 2, 5, 1, 4, 3.
order, pre-order and post order traversal.
244. If binary trees are represented in arrays,
what formula can be used to locate a left
child, if the node has an index i?
a) 2i+1
b) 2i+2
c) 2i
d) 4i
Answer: a
Explanation: If binary trees are represented
in arrays, left children are located at indices
2i+1 and right children at 2i+2. a)
245. Using what formula can a parent node
be located in an array?
a) (i+1)/2
b) (i-1)/2
c) i/2
d) 2i/2
Answer: b
Explanation: If a binary tree is represented in
an array, parent nodes are found at indices (i-
1)/2.
246. Which of the following properties are
obeyed by all three tree – traversals? b)
a) Left subtrees are visited before right
subtrees
b) Right subtrees are visited before left
subtrees
c) Root node is visited before left subtree
d) Root node is visited before right subtree
Answer: a
Explanation: In preorder, inorder and
postorder traversal the left subtrees are

DIWAKAR EDUCATION HUB Page 47


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
as right child to node 3. Thus the final tree is:

c)

1. For the tree below, write the pre-order


traversal.

d)
Answer: d
Explanation: Here,
Preorder Traversal is 1, 2, 5, 3, 4
Inorder Traversal is 2, 5, 1, 4, 3
Root node of binary tree is the first node in
Preorder traversal.
The rough sketch of tree is: a) 2, 7, 2, 6, 5, 11, 5, 9, 4
b) 2, 7, 5, 2, 6, 9, 5, 11, 4
c) 2, 5, 11, 6, 7, 4, 9, 5, 2
d) 2, 7, 5, 6, 11, 2, 5, 4, 9
Answer: a
Explanation: Pre order traversal follows
NLR(Node-Left-Right).
Second node in preorder traversal is 2. This 248. For the tree below, write the post-order
makes 5 as right child to node 2. The fourth traversal.
node in preorder traversal is 3. This makes 4

DIWAKAR EDUCATION HUB Page 48


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
c) Post-order traversal
d) In-order traversal
Answer: b
Explanation: As the name itself suggests, pre-
order traversal can be used.
252. Consider the following data. The pre
order traversal of a binary tree is A, B, E, C, D.
The in order traversal of the same binary tree
is B, E, A, D, C. The level order sequence for
the binary tree is _________
a) A, C, D, B, E
b) A, B, C, D, E
a) 2, 7, 2, 6, 5, 11, 5, 9, 4 c) A, B, C, E, D
b) 2, 7, 5, 2, 6, 9, 5, 11, 4 d) D, B, E, A, C
c) 2, 5, 11, 6, 7, 4, 9, 5, 2
Answer: b
d) 2, 7, 5, 6, 11, 2, 5, 4, 9
Explanation: The inorder sequence is B, E, A,
Answer: c D, C and Preorder sequence is A, B, E, C, D.
Explanation: Post order traversal follows The tree constructed with the inorder and
LRN(Left-Right-Node). preorder sequence is
249. What is the time complexity of pre-order
traversal in the iterative fashion?
a) O(1)
b) O(n)
c) O(logn)
d) O(nlogn)
Answer: b
Explanation: Since you have to go through all
the nodes, the complexity becomes O(n).
250. What is the space complexity of the
post-order traversal in the recursive fashion?
(d is the tree depth and n is the number of
nodes) The levelorder traversal (BFS traversal) is A,
a) O(1) B, C, E, D.
b) O(nlogd) 253. Consider the following data and specify
c) O(logd) which one is Preorder Traversal Sequence,
d) O(d) Inorder and Postorder sequences.
Answer: d S1: N, M, P, O, Q
Explanation: In the worst case we have d S2: N, P, Q, O, M
stack frames in the recursive call, hence the S3: M, N, O, P, Q
complexity is O(d). a) S1 is preorder, S2 is inorder and S3 is
251. To obtain a prefix expression, which of postorder
the tree traversals is used? b) S1 is inorder, S2 is preorder and S3 is
a) Level-order traversal postorder
b) Pre-order traversal c) S1 is inorder, S2 is postorder and S3 is

DIWAKAR EDUCATION HUB Page 49


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
preorder Answer: b
d) S1 is postorder, S2 is inorder and S3 is Explanation: As the name itself suggests, pre-
preorder order traversal can be used.
Answer: c 257. Consider the following data. The pre
Explanation: Preorder traversal starts from order traversal of a binary tree is A, B, E, C, D.
the root node and postorder and inorder The in order traversal of the same binary tree
starts from the left child node of the left is B, E, A, D, C. The level order sequence for
subtree. The first node of S3 is different and the binary tree is _________
for S1 and S2 it’s the same. Thus, S3 is a) A, C, D, B, E
preorder traversal and the root node is M. b) A, B, C, D, E
Postorder traversal visits the root node at c) A, B, C, E, D
last. S2 has the root node(M) at last that d) D, B, E, A, C
implies S2 is postorder traversal. S1 is inorder Answer: b
traversal as S2 is postorder traversal and S3 is Explanation: The inorder sequence is B, E, A,
preorder traversal. Therefore, S1 is inorder D, C and Preorder sequence is A, B, E, C, D.
traversal, S2 is postorder traversal and S3 is The tree constructed with the inorder and
preorder traversal. preorder sequence is
254. What is the time complexity of pre-order
traversal in the iterative fashion?
a) O(1)
b) O(n)
c) O(logn)
d) O(nlogn)
Answer: b
Explanation: Since you have to go through all
the nodes, the complexity becomes O(n).
255. What is the space complexity of the
post-order traversal in the recursive fashion?
(d is the tree depth and n is the number of
nodes) The levelorder traversal (BFS traversal) is A,
a) O(1) B, C, E, D.
b) O(nlogd) 258. Consider the following data and specify
c) O(logd) which one is Preorder Traversal Sequence,
d) O(d) Inorder and Postorder sequences.
Answer: d S1: N, M, P, O, Q
Explanation: In the worst case we have d S2: N, P, Q, O, M
stack frames in the recursive call, hence the S3: M, N, O, P, Q
complexity is O(d). a) S1 is preorder, S2 is inorder and S3 is
256. To obtain a prefix expression, which of postorder
the tree traversals is used? b) S1 is inorder, S2 is preorder and S3 is
a) Level-order traversal postorder
b) Pre-order traversal c) S1 is inorder, S2 is postorder and S3 is
c) Post-order traversal preorder
d) In-order traversal d) S1 is postorder, S2 is inorder and S3 is
preorder
DIWAKAR EDUCATION HUB Page 50
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c
Explanation: Preorder traversal starts from
the root node and postorder and inorder
starts from the left child node of the left
subtree. The first node of S3 is different and
for S1 and S2 it’s the same. Thus, S3 is
preorder traversal and the root node is M.
Postorder traversal visits the root node at
last. S2 has the root node(M) at last that
implies S2 is postorder traversal. S1 is inorder
traversal as S2 is postorder traversal and S3 is
preorder traversal. Therefore, S1 is inorder a) 2, 7, 2, 6, 5, 11, 5, 9, 4
traversal, S2 is postorder traversal and S3 is b) 2, 7, 5, 2, 11, 9, 6, 5, 4
preorder traversal. c) 2, 5, 11, 6, 7, 4, 9, 5, 2
259. For the tree below, write the in-order d) 2, 7, 5, 6, 11, 2, 5, 4, 9
traversal. Answer: b
Explanation: Level order traversal follows a
breadth first search approach.
261. The number of edges from the root to
the node is called __________ of the tree.
a) Height
b) Depth
c) Length
d) Width
Answer: b
Explanation: The number of edges from the
root to the node is called depth of the tree.
a) 6, 2, 5, 7, 11, 2, 5, 9, 4
262. The number of edges from the node to
b) 6, 5, 2, 11, 7, 4, 9, 5, 2
the deepest leaf is called _________ of the
c) 2, 7, 2, 6, 5, 11, 5, 9, 4
tree.
d) 2, 7, 6, 5, 11, 2, 9, 5, 4
a) Height
Answer: a b) Depth
Explanation: In-order traversal follows c) Length
LNR(Left-Node-Right). d) Width
260. For the tree below, write the level-order Answer: a
traversal. Explanation: The number of edges from the
node to the deepest leaf is called height of
the tree.
263. What is a full binary tree?
a) Each node has exactly zero or two children
b) Each node has exactly two children
c) All the leaves are at the same level
d) Each node has exactly one or two children

DIWAKAR EDUCATION HUB Page 51


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: a Hierarchical structure, Faster search, Router
Explanation: A full binary tree is a tree in algorithms are advantages of trees.
which each node has exactly 0 or 2 children. 267. In a full binary tree if number of internal
264. What is a complete binary tree? nodes is I, then number of leaves L are?
a) Each node has exactly zero or two children a) L = 2*I
b) A binary tree, which is completely filled, b) L = I + 1
with the possible exception of the bottom c) L = I – 1
level, which is filled from right to left d) L = 2*I – 1
c) A binary tree, which is completely filled, Answer: b
with the possible exception of the bottom Explanation: Number of Leaf nodes in full
level, which is filled from left to right binary tree is equal to 1 + Number of Internal
d) A tree In which all nodes have degree 2 Nodes i.e L = I + 1
Answer: c 268. What is an AVL tree?
Explanation: A binary tree, which is a) a tree which is balanced and is a height
completely filled, with the possible exception balanced tree
of the bottom level, which is filled from left b) a tree which is unbalanced and is a height
to right is called complete binary tree. A Tree balanced tree
in which each node has exactly zero or two c) a tree with three children
children is called full binary tree. A Tree in d) a tree with atmost 3 children
which the degree of each node is 2 except Answer: a
leaf nodes is called perfect binary tree. Explanation: It is a self balancing tree with
265. What is the average case time height difference atmost 1.
complexity for finding the height of the 269. Why we need to a binary tree which is
binary tree? height balanced?
a) h = O(loglogn) a) to avoid formation of skew trees
b) h = O(nlogn) b) to save memory
c) h = O(n) c) to attain faster memory access
d) h = O(log n) d) to simplify storing
Answer: d
Explanation: The nodes are either a part of Answer: a
left sub tree or the right sub tree, so we don’t Explanation: In real world dealing with
have to traverse all the nodes, this means the random values is often not possible, the
complexity is lesser than n, in the average probability that u are dealing with non
case, assuming the nodes are spread evenly, random values(like sequential) leads to
the time complexity becomes O(logn). mostly skew trees, which leads to worst case.
266. Which of the following is not an hence we make height balance by rotations.
advantage of trees? 270. Which of the below diagram is following
a) Hierarchical structure AVL tree property?
b) Faster search
c) Router algorithms
d) Undo/Redo operations in a notepad
Answer: d
Explanation: Undo/Redo operations in a
notepad is an application of stack.

DIWAKAR EDUCATION HUB Page 52


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
is p can be written in terms of height as the
beside recurrence relation which on solving
gives N(he)= O(logp) as worst case height.
272. To restore the AVL property after
inserting a element, we start at the insertion
point and move towards root of that tree. is
this statement true?
a) true
b) false

Answer: a
i. Explanation: It is interesting to note that
after insertion, only the path from that point
to node or only that subtrees are imbalanced
interms of height.
273. Given an empty AVL tree, how would
you construct AVL tree when a set of
numbers are given without performing any
rotations?
a) just build the tree with the given input
b) find the median of the set of elements
ii. given, make it as root and construct the tree
a) only i c) use trial and error
b) only i and ii d) use dynamic programming to build the
c) only ii tree
d) i is not a binary search tree
Answer: b
Answer: b Explanation: Sort the given input, find the
Explanation: The property of AVL tree is it is median element among them, make it as root
height balanced tree with difference of and construct left and right subtrees with
atmost 1 between left and right subtrees. All elements lesser and greater than the median
AVL trees are binary search tree. element recursively. this ensures the
subtrees differ only by height 1.
271. What is the maximum height of an AVL
tree with p nodes? 274. What maximum difference in heights
a) p between the leafs of a AVL tree is possible?
b) log(p) a) log(n) where n is the number of nodes
c) log(p)/2 b) n where n is the number of nodes
d) p⁄2 c) 0 or 1
d) atmost 1
Answer: b
Explanation: Consider height of tree to be Answer: a
‘he’, then number of nodes which totals to p Explanation: At every level we can form a
can be written in terms of height as tree with difference in height between
N(he)=N(he-1)+1+N(he-2). since N(he) which subtrees to be atmost 1 and so there can be

DIWAKAR EDUCATION HUB Page 53


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
log(n) such levels since height of AVL tree is c) Height(w-left), x
log(n). d) Height(w-left)
275. Consider the pseudo code:
int avl(binarysearchtree root): Answer: a
if(not root) Explanation: In the code we are trying to
return 0 make the left rotation and so we need to find
maximum of those two values.
left_tree_height = avl(left_of_root)
277. Why to prefer red-black trees over AVL
trees?
if(left_tree_height== -1) a) Because red-black is more rigidly balanced
return left_tree_height b) AVL tree store balance factor in every node
which costs space
right_tree_height= avl(right_of_root) c) AVL tree fails at scale
d) Red black is more efficient
if(right_tree_height==-1)
return right_tree_height Answer: b
Does the above code can check if a binary Explanation: Every node in an AVL tree need
search tree is an AVL tree? to store the balance factor (-1, 0, 1) hence
a) yes space costs to O(n), n being number of nodes.
b) no but in red-black we can use the sign of
number (if numbers being stored are only
positive) and hence save space for storing
Answer: a
balancing information. there are even other
Explanation: The condition to check the
reasons where redblack is mostly prefered.
height difference between left and right
subtrees is missing. if 278. What is a threaded binary tree
(absolute(left_tree_height – traversal?
right_tree_height)>1) must be added. a) a binary tree traversal using stacks
b) a binary tree traversal using queues
276. Consider the below left-left rotation
c) a binary tree traversal using stacks and
pseudo code where the node contains value
queues
pointers to left, right child nodes and a height
d) a binary tree traversal without using stacks
value and Height() function returns height
and queues
value stored at a particular node.
avltree leftrotation(avltreenode z):
Answer: d
avltreenode w =x-left
Explanation: This type of tree traversal will
x-left=w-right not use stack or queue.
w-right=x 279. What are the disadvantages of normal
x-height=max(Height(x-left),Height(x- binary tree traversals?
right))+1 a) there are many pointers which are null and
w-height=max(missing)+1 thus useless
return w b) there is no traversal which is efficient
What is missing? c) complexity in implementing
a) Height(w-left), x-height d) improper traversals
b) Height(w-right), x-height

DIWAKAR EDUCATION HUB Page 54


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: a null left pointer points to the predecessor
Explanation: As there are majority of and the right null pointer point to the
pointers with null value going wasted we use successor. In threaded binary trees, we can
threaded binary trees. use in-order, preorder and postorder
280. In general, the node content in a traversals to visit every node in the tree.
threaded binary tree is ________ 283. What are double and single threaded
a) leftchild_pointer, left_tag, data, right_tag, trees?
rightchild_pointer a) when both left, right nodes are having null
b) leftchild_pointer, left_tag pointers and only right node is null pointer
c) leftchild_pointer, left_tag, right_tag, respectively
rightchild_pointer b) having 2 and 1 node
d) leftchild_pointer, left_tag, data c) using single and double linked lists
d) using heaps and priority queues
Answer: a
Explanation: It contains additional 2 pointers Answer: a
over normal binary tree node structure. Explanation: They are properties of double
281. What are null nodes filled with in a and single threaded binary trees respectively.
threaded binary tree? 284. What is wrong with below code for
a) inorder predecessor for left node and inorder traversal of inorder threaded binary
inorder successor for right node information tree:
b) right node with inorder predecessor and inordertraversal(threadedtreenode root):
left node with inorder successor information threadedtreenode q =
c) they remain null inorderpredecessor(root)
d) some other values randomly while(q!=root):
q=inorderpredecessor(q)
Answer: a
print [Link]
Explanation: If preorder or postorder is used
then the respective predecessor and a) inordersuccessor instead of
successor info is stored. inorderpredecessor must be done
b) code is correct
282. Which of the following tree traversals
c) it is code for post order
work if the null left pointer pointing to the
d) it is code for pre order
predecessor and null right pointer pointing to
the successor in a binary tree?
a) inorder, postorder, preorder traversals Answer: a
b) inorder Explanation: Property of inorder threaded
c) postorder binary tree is left node with inorder
d) preorder predecessor and right node with inorder
successor information are stored.
Answer: a 285. What is inefficient with the below
Explanation: In threaded binary trees, the threaded binary tree picture?

DIWAKAR EDUCATION HUB Page 55


a) it has dangling pointers b) 63
b) nothing inefficient c) 127
c) incorrect threaded tree d) 188
d) space is being used more Answer: a
Answer: a Explanation: A B-tree of order m of height h
Explanation: The nodes extreme left and will have the maximum number of keys when
right are pointing to nothing which could be all nodes are completely filled. So, the B-tree
also used efficiently. will have n = (mh+1 – 1) keys in this situation.
286. Which of the following is the most So, required number of maximum keys =
widely used external memory data structure? 43+1 – 1 = 256 – 1 = 255.
a) AVL tree 289. Five node splitting operations occurred
b) B-tree when an entry is inserted into a B-tree. Then
c) Red-black tree how many nodes are written?
d) Both AVL tree and Red-black tree a) 14
Answer: b b) 7
Explanation: In external memory, the data is c) 11
transferred in form of blocks. These blocks d) 5
have data valued and pointers. And B-tree Answer: c
can hold both the data values and pointers. Explanation: If s splits occur in a B-tree, 2s +
So B-tree is used as an external memory data 1 nodes are written (2 halves of each split
structure. and the parent of the last node split). So, if 5
287. B-tree of order n is a order-n multiway splits occurred, then 2 * 5 + 1 , i.e. 11 nodes
tree in which each non-root node contains are written.
__________ 290. B-tree and AVL tree have the same
a) at most (n – 1)/2 keys worst case time complexity for insertion and
b) exact (n – 1)/2 keys deletion.
c) at least 2n keys a) True
d) at least (n – 1)/2 keys b) False
Answer: d Answer: a
Explanation: A non-root node in a B-tree of Explanation: Both the B-tree and the AVL
order n contains at least (n – 1)/2 keys. And tree have O(log n) as worst case time
contains a maximum of (n – 1) keys and n complexity for insertion and deletion.
sons. 291. 2-3-4 trees are B-trees of order 4. They
288. A B-tree of order 4 and of height 3 will are an isometric of _____ trees.
have a maximum of _______ keys. a) AVL
a) 255 b) AA
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
c) 2-3 tree, there exists a Red-Black tree with data
d) Red-Black elements in the same order.
Answer: d 292. Figure shown below is B-tree of order 5.
Explanation: 2-3-4 trees are isometric of Red- What is the result of deleting 130 from the
Black trees. It means that, for every 2-3-4 tree?

a)

b)

c)

DIWAKAR EDUCATION HUB Page 57


d)

Answer: c requirements in a B-tree.


Explanation: Each non-root in a B-tree of a) True
order 5 must contain at least 2 keys. Here, b) False
when the key 130 is deleted the node gets Answer: a
underflowed i.e. number of keys in the node Explanation: The front compression and the
drops below 2. So we combine the node with rear compression are techniques used to
key 110 with it’s brother node having keys reduce space and time requirements in B-
144 and 156. And this combined node will tree. The compression enables to retain more
also contain the separator key from parent keys in a node so that the number of nodes
i.e. key 140, leaving the root with two keys needed can be reduced.
110 and 160. 295. Which of the following is true?
293. What is the best case height of a B-tree a) larger the order of B-tree, less frequently
of order n and which has k keys? the split occurs
a) logn (k+1) – 1 b) larger the order of B-tree, more frequently
b) nk the split occurs
c) logk (n+1) – 1 c) smaller the order of B-tree, more
d) klogn frequently the split occurs
Answer: a d) smaller the order of B-tree, less frequently
Explanation: B-tree of order n and with the split occurs
height k has best case height h, where h = Answer: a
logn (k+1) – 1. The best case occurs when all Explanation: The average probability of the
the nodes are completely filled with keys. split is 1/(⌈m / 2⌉ – 1), where m is the order of
294. Compression techniques can be used on B-tree. So, if m larger, the probability of split
the keys to reduce both space and time will be less.
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
296. In a B+ tree, both the internal nodes and Answer: a
the leaves have keys. Explanation: A B+ -tree always grows
a) True upwards. And In a B+tree – i)The path from
b) False the root to every leaf node is of the same
Answer: b length, so the tree is balanced. ii) Leaves are
Explanation: In a B+ -tree, only the leaves linked, so allow sequential searching. iii) An
have keys, and these keys are replicated in index is built with a single key per block of
non-leaf nodes for defining the path for data rather than with one key per data
locating individual records. record, so it is shallower than B-tree.
297. Which of the following is true? 300. A B+ -tree of order 3 is generated by
a) B + tree allows only the rapid random inserting 89, 9 and 8. The generated B+ -tree
access is __________
b) B + tree allows only the rapid sequential
access
c) B + tree allows rapid random access as well
as rapid sequential access
d) B + tree allows rapid random access and
slower sequential access
Answer: c
a)
Explanation: The B+ -tree being a variation of
B-tree allows rapid random access. In a B+ -
tree the leaves are linked together, so it also
provides rapid sequential access.
298. A B+ tree can contain a maximum of 7
pointers in a node. What is the minimum
number of keys in leaves?
a) 6
b)
b) 3
c) 4
d) 7
Answer: b
Explanation: Maximum number of pointers in
a node is 7, i.e. the order of the B+ -tree is 7.
In a B+ tree of order n each leaf node
contains at most n – 1 key and at least ⌈(n − c)
1)/2⌉ keys. Therefore, a minimum number of
keys each leaf can have = ⌈(7 – 1)/2⌉ = 3.
299. Which of the following is false?
a) A B+ -tree grows downwards
b) A B+ -tree is balanced
c) In a B+ -tree, the sibling pointers allow
sequential searching d)
d) B+ -tree is shallower than B-tree

DIWAKAR EDUCATION HUB Page 59


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: b Explanation:

6. Statement 1: When a node is split during Answer: d


insertion, the middle key is promoted to the Explanation: In a B+ -tree finding the next
parent as well as retained in right half-node. recored (successor) involves accessing an
Statement 2: When a key is deleted from the additional leaf at most. So, the efficiency of
leaf, it is also deleted from the non-leaf finding the next record is O(1).
nodes of the tree. 302. What is the maximum number of keys
a) Statement 1 is true but statement 2 is false that a B+ -tree of order 3 and of height 3
b) Statement 2 is true but statement 1 is false have?
c) Both the statements are true a) 3
d) Both the statements are false b) 80
Answer: a c) 27
Explanation: During the split, the middle key d) 26
is retained in the right half node and also Answer: d
promoted to parent node. When a key is Explanation: A B+ tree of order n and height
deleted from the leaf, it is retained in non- h can have at most nh – 1 keys. Therefore
leaves, because it can be still a valid maximum number of keys = 33 -1 = 27 -1 = 26.
separator between keys in nodes below. 303. Which of the following is false?
301. Efficiency of finding the next record in a) Compared to B-tree, B+ -tree has larger
B+ tree is ____ fanout
a) O(n) b) Deletion in B-tree is more complicated
b) O(log n) than in B+ -tree
c) O(nlog n) c) B+ -tree has greater depth than
d) O(1) corresponding B-tree

DIWAKAR EDUCATION HUB Page 60


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
d) Both B-tree and B+ -tree have same search
and insertion efficiencies
Answer: c
Explanation: A B+ -tree has larger fanout and
therefore have a depth smaller than that of
corresponding B-tree.
304. Which one of the following data
structures are preferred in database-system b)
implementation?
a) AVL tree
b) B-tree
c) B+ -tree
d) Splay tree
Answer: c
Explanation: The database-system c)
implementations use B+ -tree data structure
because they can be used for multilevel
indexing.
305. 2-3 tree is a specific form of _________
a) B – tree
b) B+ – tree
c) AVL tree
d) Heap d)
Answer: a Answer: c
Explanation: The 2-3 trees is a balanced tree. Explanation: Tree should have two subtrees
It is a specific form the B – tree. It is B – tree at node2, but it should not have three
of order 3, where every node can have two elements. The node with elements 11 and 15
child subtrees and one key or 3 child subtrees should have three child subtrees.
and two keys. 307. AVL trees provide better insertion the 2-
306. Which of the following is the 2-3 tree? 3 trees.
a) True
b) False
Answer: b
Explanation: Insertion in AVL tree and 2-3
tree requires searching for proper position
for insertion and transformations for
balancing the tree. In both, the trees
a) searching takes O(log n) time, but rebalancing
in AVL tree takes O(log n), while the 2-3 tree
takes O(1). So, 2-3 tree provides better
insertions.
308. How many child nodes does each node
of Ternary Tree contain?
a) 4

DIWAKAR EDUCATION HUB Page 61


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
b) 6 b) A(i,j) = i+j for i>=j
c) 5 c) A(i,j) = i+j for i = j
d) 3 d) A(1,i) = i+1 for i<1
Answer: d Answer: a
Explanation: Each node of Ternary tree Explanation: The Ackermann’s function is
contains at most 3 nodes. So Ternary tree can defined as A(1,i) = i+1 for i>=1. This form in
have 1, 2 or 3 child nodes but not more than text grows faster and the inverse is slower.
that. 313. Which of the following is not a collision
309. Which of the following is the name of resolution strategy for open addressing?
the node having child nodes? a) Linear probing
a) Brother b) Quadratic probing
b) Sister c) Double hashing
c) Mother d) Rehashing
d) Parent Answer: d
Answer: d Explanation: Linear probing, quadratic
Explanation: Parent node is the node having probing and double hashing are all collision
child nodes and child nodes may contain resolution strategies for open addressing
references to their parents. Parent node is a whereas rehashing is a different technique.
node connected by a directed edge to its 314. Hashing can be used in online spelling
child. checkers.
310. What is the worst case efficiency for a a) True
path compression algorithm? b) False
a) O(N) Answer: a
b) O(log N) Explanation: If misspelling detection is
c) O(N log N) important, an entire dictionary can be pre-
d) O(M log N) hashed and words can be checked in constant
Answer: d time.
Explanation: The worst case efficiency for a 315. Which of the following schemes does
path compression algorithm is quadratic probing come under?
mathematically found to be O(M log N). a) rehashing
311. Path Compression algorithm performs in b) extended hashing
which of the following operations? c) separate chaining
a) Create operation d) open addressing
b) Insert operation Answer: d
c) Find operation Explanation: Quadratic probing comes under
d) Delete operation open addressing scheme to resolve collisions
Answer: c in hash tables.
Explanation: Path compression algorithm is 316. Which scheme uses a randomization
performed during find operation and is approach?
independent of the strategy used to perform a) hashing by division
unions. b) hashing by multiplication
312. What is the definition for Ackermann’s c) universal hashing
function? d) open addressing
a) A(1,i) = i+1 for i>=1

DIWAKAR EDUCATION HUB Page 62


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c c) h(k) = m/k
Explanation: Universal hashing scheme uses d) h(k) = m mod k
a randomization approach whereas hashing Answer: b
by division and hashing by multiplication are Explanation: In division method for creating
heuristic in nature. hash functions, k keys are mapped into one
317. Which hash function satisfies the of m slots by taking the reminder of k divided
condition of simple uniform hashing? by m.
a) h(k) = lowerbound(km) 321. What can be the value of m in the
b) h(k)= upperbound(mk) division method?
c) h(k)= lowerbound(k) a) Any prime number
d) h(k)= upperbound(k) b) Any even number
Answer: a c) 2p – 1
Explanation: If the keys are known to be d) 2p
random real numbers k independently and Answer: a
uniformly distributed in the range 0<=k<=1, Explanation: A prime number not too close
the hash function which satisfies the to an exact power of 2 is often a good choice
condition of simple uniform hashing is for m since it reduces the number of
h(k)= lowerbound(km). collisions which are likely to occur.
318. A good hash approach is to derive the 322. Which scheme provides good
hash value that is expected to be dependent performance?
of any patterns that might exist in the data. a) open addressing
a) True b) universal hashing
b) False c) hashing by division
Answer: b d) hashing by multiplication
Explanation: A hash value is expected to be Answer: b
unrelated or independent of any patterns in Explanation: Universal hashing scheme
the distribution of keys. provides better performance than other
319. Interpret the given character string as an schemes because it uses a unique
integer expressed in suitable radix notation. randomisation approach.
Character string = pt 323. Using division method, in a given hash
a) 14963 table of size 157, the key of value 172 be
b) 14392 placed at position ____
c) 12784 a) 19
d) 14452 b) 72
Answer: d c) 15
Explanation: The given character string can d) 17
be interpreted as (112,116) (Ascii values) Answer: c
then expressed as a radix-128 integer, hence Explanation: The key 172 can be placed at
the value is 112*128 + 116 = 14452. position 15 by using the formula
320. What is the hash function used in the H(k) = k mod m
division method? H(k) = 172 mod 157
a) h(k) = k/m H(k) = 15.
b) h(k) = k mod m 324. How many steps are involved in creating
a hash function using a multiplication

DIWAKAR EDUCATION HUB Page 63


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
method? m= 27
a) 1 m = 128.
b) 4 328. What is the value of h(k) for the key
c) 3 123456?
d) 2 Given: p=14, s=2654435769, w=32
Answer: d a) 123
Explanation: In multiplication method 2 steps b) 456
are involved. First multiplying the key value c) 70
by a constant. Then multiplying this value by d) 67
m. Answer: d
325. What is the hash function used in Explanation: A = s/2w
multiplication method? A = 2654435769/ 232
a) h(k) = floor( m(kA mod 1)) k.A = 123456 * (2654435769/ 232)
b) h(k) = ceil( m(kA mod 1)) = (76300 * 232) + 17612864
c) h(k) = floor(kA mod m) Hence r1= 76300; r0=17612864
d) h(k) = ceil( kA mod m) Since w=14 the 14 most significant bits of r0
Answer: a yield the value of h(k) as 67.
Explanation: The hash function can be 329. What is the average retrieval time when
computed by multiplying m with the n keys hash to the same slot?
fractional part of kA (kA mod 1) and then a) Theta(n)
computing the floor value of the result. b) Theta(n2)
326. What is the advantage of the c) Theta(nlog n)
multiplication method? d) Big-Oh(n2)
a) only 2 steps are involved Answer: a
b) using constant Explanation: The average retrieval time when
c) value of m not critical n keys hash to the same slot is given by
d) simple multiplication Theta(n) as the collision occurs in the hash
Answer: c table.
Explanation: The value of m can be simply in 330. Collisions can be reduced by choosing a
powers of 2 since we can easily implement hash function randomly in a way that is
the function in most computers. m=2p where independent of the keys that are actually to
p is an integer. be stored.
327. What is the table size when the value of a) True
p is 7 in multiplication method of creating b) False
hash functions? Answer: a
a) 14 Explanation: Because of randomization, the
b) 128 algorithm can behave differently on each
c) 49 execution, providing good average case
d) 127 performance for any input.
Answer: b 331. Double hashing is one of the best
Explanation: In multiplication method of methods available for open addressing.
creating hash functions the table size can be a) True
taken in integral powers of 2. b) False
m = 2p

DIWAKAR EDUCATION HUB Page 64


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: a
Explanation: Double hashing is one of the
best methods for open addressing because
the permutations produced have many
characteristics of randomly chosen
permutations.
332. What is the hash function used in
Double Hashing?
a) (h1(k) – i*h2(k))mod m
b) h1(k) + h2(k)
c) (h1(k) + i*h2(k))mod m
d) (h1(k) + h2(k))mod m
Answer: c
Explanation: Double hashing uses a hash
function of the form (h1(k) + i*h2(k))mod m
where h1 and h2 are auxiliary hash functions
and m is the size of the hash table.
333. Which of the following statements for a
simple graph is correct? a) B and E
a) Every path is a trail b) C and D
b) Every trail is a path c) A and E
c) Every trail is a path as well as every path is d) C and B
a trail
Answer: d
d) Path and trail have no relation
Explanation: After removing either B or C,
Answer: a the graph becomes disconnected.
Explanation: In a walk if the vertices are
335. For the given graph(G), which of the
distinct it is called a path, whereas if the
following statements is true?
edges are distinct it is called a trail.
334. In the given graph identify the cut
vertices.

a) G is a complete graph
b) G is not a connected graph
c) The vertex connectivity of the graph is 2
d) The edge connectivity of the graph is 1

DIWAKAR EDUCATION HUB Page 65


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c b) 3
Explanation: After removing vertices B and C, c) 1
the graph becomes disconnected. d) 11
336. What is the number of edges present in Answer: b
a complete graph having n vertices? Explanation: By euler’s formula the relation
a) (n*(n+1))/2 between vertices(n), edges(q) and regions(r)
b) (n*(n-1))/2 is given by n-q+r=2.
c) n 340. If a simple graph G, contains n vertices
d) Information given is insufficient and m edges, the number of edges in the
Answer: b Graph G'(Complement of G) is ___________
Explanation: Number of ways in which every a) (n*n-n-2*m)/2
vertex can be connected to each other is nC2. b) (n*n+n+2*m)/2
337. The given Graph is regular. c) (n*n-n-2*m)/2
d) (n*n-n+2*m)/2
Answer: a
Explanation: The union of G and G’ would be
a complete graph so, the number of edges in
G’= number of edges in the complete form of
G(nC2)-edges in G(m).
341. Which of the following properties does a
simple graph not hold?
a) Must be connected
b) Must be unweighted
c) Must have no loops or multiple edges
d) Must have no multiple edges
a) True Answer: a
b) False Explanation: A simple graph maybe
Answer: a connected or disconnected.
Explanation: In a regular graph, degrees of all 342. What is the maximum number of edges
the vertices are equal. In the given graph the in a bipartite graph having 10 vertices?
degree of every vertex is 3. a) 24
338. In a simple graph, the number of edges b) 21
is equal to twice the sum of the degrees of c) 25
the vertices. d) 16
a) True Answer: c
b) False Explanation: Let one set have n vertices
Answer: b another set would contain 10-n vertices.
Explanation: The sum of the degrees of the Total number of edges would be n*(10-n),
vertices is equal to twice the number of differentiating with respect to n, would yield
edges. the answer.
339. A connected planar graph having 6 343. Which of the following is true?
vertices, 7 edges contains _____________ a) A graph may contain no edges and many
regions. vertices
a) 15 b) A graph may contain many edges and no

DIWAKAR EDUCATION HUB Page 66


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
vertices Incidence Matrix
c) A graph may contain no edges and no d) No way to represent
vertices Answer: c
d) A graph may contain no vertices and many Explanation: Adjacency Matrix, Adjacency
edges List and Incidence Matrix are used to
Answer: b represent a graph.
Explanation: A graph must contain at least 348. The number of elements in the
one vertex. adjacency matrix of a graph having 7 vertices
344. For a given graph G having v vertices and is __________
e edges which is connected and has no cycles, a) 7
which of the following statements is true? b) 14
a) v=e c) 36
b) v = e+1 d) 49
c) v + 1 = e Answer: d
d) v = e-1 Explanation: There are n*n elements in the
Answer: b adjacency matrix of a graph with n vertices.
Explanation: For any connected graph with 349. What would be the number of zeros in
no cycles the equation holds true. the adjacency matrix of the given graph?
345. For which of the following combinations
of the degrees of vertices would the
connected graph be eulerian?
a) 1,2,3
b) 2,3,4
c) 2,4,5
d) 1,3,5
Answer: a
Explanation: A graph is eulerian if either all of
its vertices are even or if only two of its a) 10
vertices are odd. b) 6
346. A graph with all vertices having equal c) 16
degree is known as a __________ d) 0
a) Multi Graph Answer: b
b) Regular Graph Explanation: Total number of values in the
c) Simple Graph matrix is 4*4=16, out of which 6 entries are
d) Complete Graph non zero.
Answer: b 350. Adjacency matrix of all graphs are
Explanation: The given statement is the symmetric.
definition of regular graphs. a) False
347. Which of the following ways can be used b) True
to represent a graph? Answer: a
a) Adjacency List and Adjacency Matrix Explanation: Only undirected graphs produce
b) Incidence Matrix symmetric adjacency matrices.
c) Adjacency List, Adjacency Matrix as well as 351. Incidence matrix and Adjacency matrix
of a graph will always have same dimensions?
DIWAKAR EDUCATION HUB Page 67
DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
a) True c) Source – 1, 8 Sink – 4
b) False d) Source – 4, Sink – 1,8
Answer: b Answer: c
Explanation: For a graph having V vertices Explanation: Every Stack of the Graph
and E edges, Adjacency matrix have V*V Structured Stack represents a path, each path
elements while Incidence matrix have V*E starts with the source vertex and ends with
elements. the sink vertex.
352. The column sum in an incidence matrix 356. Graph Structured Stack finds its
for a simple graph is __________ application in _____________
a) depends on number of edges a) Bogo Sort
b) always greater than 2 b) Tomita’s Algorithm
c) equal to 2 c) Todd–Coxeter algorithm
d) equal to the number of edges d) Heap Sort
Answer: c Answer: b
Explanation: For every edge only the vertices Explanation: Tomita’s is a parsing algorithm
with which it is connected would have the which uses Graph Structured Stack in its
value 1 in the matrix, as an edge connects implementation.
two vertices sum will always be 2. 357. Space complexity for an adjacency list of
353. What are the dimensions of an incidence an undirected graph having large values of V
matrix? (vertices) and E (edges) is ___________
a) Number of edges*number of edges a) O(E)
b) Number of edges*number of vertices b) O(V*V)
c) Number of vertices*number of vertices c) O(E+V)
d) Number of edges * (1⁄2 * number of d) O(V)
vertices) Answer: c
Answer: b Explanation: In an adjacency list for every
Explanation: Columns may represent edges vertex there is a linked list which have the
and vertices may be represented by the rows. values of the edges to which it is connected.
354. A Graph Structured Stack is a 358. For some sparse graph an adjacency list
_____________ is more space efficient against an adjacency
a) Undirected Graph matrix.
b) Directed Graph a) True
c) Directed Acyclic Graph b) False
d) Regular Graph Answer: a
Answer: c Explanation: Space complexity for adjacency
Explanation: A Graph Structured Stack is a matrix is always O(V*V) while space
Directed Acyclic Graph with each path complexity for adjacency list in this case
representing a stack. would be O(V).
355. If a Graph Structured Stack contains 359. How many of the following statements
{1,2,3,4} {1,5,3,4} {1,6,7,4} and {8,9,7,4}, what are correct?
would be the source and sink vertices of the i) All cyclic graphs are complete graphs.
DAC? ii) All complete graphs are cyclic graphs.
a) Source – 1, 8 Sink – 7,4 iii) All paths are bipartite.
b) Source – 1 Sink – 8,4 iv) All cyclic graphs are bipartite.

DIWAKAR EDUCATION HUB Page 68


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
v) There are cyclic graphs which are Answer: d
complete. Explanation: It is practical to implement
a) 1 linear search in the situations mentioned in
b) 2 When the list has only a few elements and
c) 3 When performing a single search in an
d) 4 unordered list, but for larger elements the
Answer: b complexity becomes larger and it makes
Explanation: Statements iii) and v) are sense to sort the list and employ binary
correct. search or hashing.
360. All paths and cyclic graphs are bipartite 364. What is the best case and worst case
graphs. complexity of ordered linear search?
a) True a) O(nlogn), O(logn)
b) False b) O(logn), O(nlogn)
Answer: b c) O(n), O(1)
Explanation: Only paths and even cycles are d) O(1), O(n)
bipartite graphs. Answer: d
361. What is the best case for linear search? Explanation: Although ordered linear search
a) O(nlogn) is better than unordered when the element is
b) O(logn) not present in the array, the best and worst
c) O(n) cases still remain the same, with the key
d) O(1) element being found at first position or at
Answer: d last position.
Explanation: The element is at the head of 365. Which of the following is a disadvantage
the array, hence O(1). of linear search?
362. What is the worst case for linear search? a) Requires more space
a) O(nlogn) b) Greater time complexities compared to
b) O(logn) other searching algorithms
c) O(n) c) Not easy to understand
d) O(1) d) Not easy to implement
Answer: c Answer: b
Explanation: Worst case is when the desired Explanation: The complexity of linear search
element is at the tail of the array or not as the name suggests is O(n) which is much
present at all, in this case you have to greater than other searching techniques like
traverse till the end of the array, hence the binary search(O(logn)). Linear search is easy
complexity is O(n). to implement and understand than other
searching techniques.
363. Where is linear searching used?
a) When the list has only a few elements 366. Is there any difference in the speed of
b) When performing a single search in an execution between linear serach(recursive) vs
unordered list linear search(lterative)?
c) Used all the time a) Both execute at same speed
d) When the list has only a few elements and b) Linear search(recursive) is faster
When performing a single search in an c) Linear search(Iterative) is faster
unordered list d) Cant be said

DIWAKAR EDUCATION HUB Page 69


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c b) O(n)
Explanation: The Iterative algorithm is faster c) O(logn)
than the latter as recursive algorithm has d) O(nx)
overheads like calling function and registering Answer: a
stacks repeatedly. Explanation: The best case occurs when the
367. Is the space consumed by the linear given element to be found is at the first
search(recursive) and linear search(iterative) position. Therefore O(1) is the correct
same? answer.
a) No, recursive algorithm consumes more 371. Can linear search recursive algorithm
space and binary search recursive algorithm be
b) No, recursive algorithm consumes less performed on an unordered list?
space a) Binary search can’t be used
c) Yes b) Linear search can’t be used
d) Nothing can be said c) Both cannot be used
Answer: a d) Both can be used
Explanation: The recursive algorithm Answer: a
consumes more space as it involves the usage Explanation: As binary search requires
the stack space(calls the function numerous comparison, it is required that the list be
times). ordered. Whereas this doesn’t matter for
368. What is the worst case runtime of linear linear search.
search(recursive) algorithm? 372. What is the advantage of recursive
a) O(n) approach than an iterative approach?
b) O(logn) a) Consumes less memory
c) O(n2) b) Less code and easy to implement
d) O(nx) c) Consumes more memory
Answer: a d) More code has to be written
Explanation: In the worst case scenario, Answer: b
there might be a need of calling the stack n Explanation: A recursive approach is easier to
times. Therfore O(n). understand and contains fewer lines of code.
369. Linear search(recursive) algorithm used 373. What is the worst case complexity of
in _____________ binary search using recursion?
a) When the size of the dataset is low a) O(nlogn)
b) When the size of the dataset is large b) O(logn)
c) When the dataset is unordered c) O(n)
d) Never used d) O(n2)
Answer: a Answer: b
Explanation: It is used when the size of the Explanation: Using the divide and conquer
dataset is low as its runtime is O(n) which is master theorem.
more when compared to the binary search 374. What is the average case time
O(logn). complexity of binary search using recursion?
370. What is the best case runtime of linear a) O(nlogn)
search(recursive) algorithm on an ordered set b) O(logn)
of elements? c) O(n)
a) O(1) d) O(n2)

DIWAKAR EDUCATION HUB Page 70


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: b Answer: b
Explanation: T(n) = T(n/2) + 1, Using the Explanation: For sorting small arrays,
divide and conquer master theorem. insertion sort runs even faster than quick
375. Which of the following is not an sort. But, it is impractical to sort large arrays.
application of binary search? 379. For the best case input, the running time
a) To find the lower/upper bound in an of an insertion sort algorithm is?
ordered sequence a) Linear
b) Union of intervals b) Binary
c) Debugging c) Quadratic
d) To search in unordered list d) Depends on the input
Answer: d Answer: a
Explanation: In Binary search, the elements Explanation: The best case input for an
in the list should be sorted. It is applicable insertion sort algorithm runs in linear time
only for ordered list. Hence Binary search in and is given by O(N).
unordered list is not an application. 380. How many passes does an insertion sort
376. Jump search algorithm requires which of algorithm consist of?
the following condition to be true? a) N
a) array should be sorted b) N-1
b) array should have not be sorted c) N+1
c) array should have a less than 64 elements d) N2
d) array should be partially sorted Answer: b
Answer: a Explanation: An insertion algorithm consists
Explanation: Jump sort requires the input of N-1 passes when an array of N elements is
array to be sorted. The algorithm would fail given.
to give the correct result if array is not sorted. 381. Which of the following algorithm
377. Which of the following examples implementations is similar to that of an
represent the worst case input for an insertion sort?
insertion sort? a) Binary heap
a) array in sorted order b) Quick sort
b) array sorted in reverse order c) Merge sort
c) normal unsorted array d) Radix sort
d) large array Answer: a
Answer: b Explanation: Insertion sort is similar to that
Explanation: The worst case input for an of a binary heap algorithm because of the use
insertion sort algorithm will be an array of temporary variable to swap.
sorted in reverse order and its running time is 382. What is the average case running time of
quadratic. an insertion sort algorithm?
378. Which of the following sorting a) O(N)
algorithms is the fastest for sorting small b) O(N log N)
arrays? c) O(log N)
a) Quick sort d) O(N2)
b) Insertion sort Answer: d
c) Shell sort Explanation: The average case analysis of a
d) Heap sort

DIWAKAR EDUCATION HUB Page 71


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
tight bound algorithm is mathematically 387. Which of the following sorting algorithm
achieved to be O(N2). is best suited if the elements are already
383. Any algorithm that sorts by exchanging sorted?
adjacent elements require O(N2) on average. a) Heap Sort
a) True b) Quick Sort
b) False c) Insertion Sort
Answer: a d) Merge Sort
Explanation: Each swap removes only one Answer: c
inversion, so O(N2) swaps are required. Explanation: The best case running time of
384. Binary search can be used in an insertion the insertion sort is O(n). The best case
sort algorithm to reduce the number of occurs when the input array is already sorted.
comparisons. As the elements are already sorted, only one
a) True comparison is made on each pass, so that the
b) False time required is O(n).
Answer: a 388. Insertion sort is an example of an
Explanation: Binary search can be used in an incremental algorithm.
insertion sort algorithm to reduce the a) True
number of comparisons. This is called a b) False
Binary insertion sort. Answer: a
385. Which of the following options contain Explanation: In the incremental algorithms,
the correct feature of an insertion sort the complicated structure on n items is built
algorithm? by first building it on n − 1 items. And then
a) anti-adaptive we make the necessary changes to fix things
b) dependable in adding the last item. Insertion sort builds
c) stable, not in-place the sorted sequence one element at a time.
d) stable, adaptive Therefore, it is an example of an incremental
Answer: d algorithm.
Explanation: An insertion sort is stable, 389. What is an in-place sorting algorithm?
adaptive, in-place and incremental in nature. a) It needs O(1) or O(logn) memory to create
386. Which of the following is correct with auxiliary locations
regard to insertion sort? b) The input is already sorted and in-place
a) insertion sort is stable and it sorts In-place c) It requires additional storage
b) insertion sort is unstable and it sorts In- d) It requires additional space
place Answer: a
c) insertion sort is stable and it does not sort Explanation: Auxiliary memory is required for
In-place storing the data temporarily.
d) insertion sort is unstable and it does not 390. In the following scenarios, when will you
sort In-place use selection sort?
Answer: a a) The input is already sorted
Explanation: During insertion sort, the b) A large file has to be sorted
relative order of elements is not changed. c) Large values need to be sorted with small
Therefore, it is a stable sorting algorithm. And keys
insertion sort requires only O(1) of additional d) Small values need to be sorted with large
memory space. Therefore, it sorts In-place. keys

DIWAKAR EDUCATION HUB Page 72


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
Answer: c c) It can be used for small keys
Explanation: Selection is based on keys, d) It takes linear time to sort the elements
hence a file with large values and small keys Answer: b
can be efficiently sorted with selection sort. Explanation: As the input size increases, the
391. What is the worst case complexity of performance of selection sort decreases.
selection sort? 395. What is an external sorting algorithm?
a) O(nlogn) a) Algorithm that uses tape or disk during the
b) O(logn) sort
c) O(n) b) Algorithm that uses main memory during
d) O(n2) the sort
Answer: d c) Algorithm that involves swapping
Explanation: Selection sort creates a sub-list, d) Algorithm that are considered ‘in place’
LHS of the ‘min’ element is already sorted Answer: a
and RHS is yet to be sorted. Starting with the Explanation: As the name suggests, external
first element the ‘min’ element moves sorting algorithm uses external memory like
towards the final element. tape or disk.
392. What is the advantage of selection sort 396. What is an internal sorting algorithm?
over other sorting techniques? a) Algorithm that uses tape or disk during the
a) It requires no additional storage space sort
b) It is scalable b) Algorithm that uses main memory during
c) It works best for inputs which are already the sort
sorted c) Algorithm that involves swapping
d) It is faster than any other sorting d) Algorithm that are considered ‘in place’
technique Answer: b
Answer: a Explanation: As the name suggests, internal
Explanation: Since selection sort is an in- sorting algorithm uses internal main memory.
place sorting algorithm, it does not require 397. What is the worst case complexity of
additional storage. bubble sort?
393. What is the average case complexity of a) O(nlogn)
selection sort? b) O(logn)
a) O(nlogn) c) O(n)
b) O(logn) d) O(n2)
c) O(n) Answer: d
d) O(n2) Explanation: Bubble sort works by starting
Answer: d from the first element and swapping the
Explanation: In the average case, even if the elements if required in each iteration.
input is partially sorted, selection sort 398. What is the average case complexity of
behaves as if the entire array is not sorted. bubble sort?
Selection sort is insensitive to input. a) O(nlogn)
394. What is the disadvantage of selection b) O(logn)
sort? c) O(n)
a) It requires auxiliary memory d) O(n2)
b) It is not scalable Answer: d
Explanation: Bubble sort works by starting

DIWAKAR EDUCATION HUB Page 73


DATA STRUCTURES AND ALGORITHMS UNIT – 7 MCQS
from the first element and swapping the 402. What is the auxiliary space complexity of
elements if required in each iteration even in merge sort?
the average case. a) O(1)
399. Which of the following is not an advantage b) O(log n)
of optimised bubble sort over other sorting c) O(n)
techniques in case of sorted elements? d) O(n log n)
a) It is faster Answer: c
b) Consumes less memory Explanation: An additional space of O(n) is
c) Detects whether the input is already sorted required in order to merge two sorted arrays.
d) Consumes less time Thus merge sort is not an in place sorting
Answer: c algorithm.
Explanation: Optimised Bubble sort is one of 403. Merge sort can be implemented using
the simplest sorting techniques and perhaps O(1) auxiliary space.
the only advantage it has over other a) true
techniques is that it can detect whether the b) false
input is already sorted. It is faster than other in Answer: a
case of sorted array and consumes less time to Explanation: Standard merge sort requires O(n)
describe whether the input array is sorted or space to merge two sorted arrays. We can
not. It consumes same memory than other optimize this merging process so that it takes
sorting techniques. Hence it is not an only constant space. This version is known as in
advantage. place merge sort.
400. Merge sort uses which of the following 404. What is the worst case time complexity of
technique to implement sorting? merge sort?
a) backtracking a) O(n log n)
b) greedy algorithm b) O(n2)
c) divide and conquer c) O(n2 log n)
d) dynamic programming d) O(n log n2)
Answer: c Answer: a
Explanation: Merge sort uses divide and Explanation: The time complexity of merge
conquer in order to sort a given array. This is sort is not affected by worst case as its
because it divides the array into two halves and algorithm has to implement the same number
applies merge sort algorithm to each half of steps in any case. So its time complexity
individually after which the two sorted halves remains to be O(n log n).
are merged together. 405. Which of the following method is used for
401. What is the average case time complexity sorting in merge sort?
of merge sort? a) merging
a) O(n log n) b) partitioning
b) O(n2) c) selection
c) O(n2 log n) d) exchanging
d) O(n log n2) Answer: a
Answer: a Explanation: Merge sort algorithm divides the
Explanation: The recurrence relation for merge array into two halves and applies merge sort
sort is given by T(n) = 2T(n/2) + n. It is found to algorithm to each half individually after which
be equal to O(n log n) using the master the two sorted halves are merged together.
theorem. Thus its method of sorting is called merging.

DIWAKAR EDUCATION HUB Page 74

You might also like