Data Structure 2 Lyst1728905520227
Data Structure 2 Lyst1728905520227
www.knowledgegate.in
www.knowledgegate.in
Syllabus
• Arrays, Stacks, Queues, Linked lists, Trees, Binary search trees, Binary heaps,
Graphs
www.knowledgegate.in
www.knowledgegate.in
Idea of computer science
• Computer science is about solving problems by designing algorithms that can be converted into
efficient programs. The key challenge is optimizing for time and memory.
www.knowledgegate.in
www.knowledgegate.in
What is data structure
• Data structure is a particular way of organizing data in a computer memory, so that Memory
can be used efficiently both in terms of time and space. It is a logical relationship existing
between individual elements of data, it considers elements stored and also their relationship
to each other. Data structure mainly specifies the following four things: -
• Organization of data, Accessing methods, Degree of association, Processing
methods
www.knowledgegate.in
www.knowledgegate.in
Array Link List
Stack Tree
Graph
www.knowledgegate.in
Queue www.knowledgegate.in
The Impact of Data Structures on Programs
• Data structures affect both the structural and functional aspects of a program. The choice of data
structure plays a crucial role in program design and efficiency.
• Specialized Data Structures for Different Applications
• Relational Databases: Often use B-tree indexes for efficient data retrieval.
• Compiler Implementations: Commonly rely on hash tables for fast identifier lookups.
• Data Structures & Algorithm Efficiency: Efficient data structures are essential to designing efficient
algorithms. In some programming paradigms, data structures are emphasized over algorithms as the
primary organizing factor in software design.
• Implementing Data Structures: The implementation of a data structure typically involves creating a set
of procedures to instantiate and manipulate the structure, ensuring efficient use and access.
www.knowledgegate.in
www.knowledgegate.in
Primitive and Non-Primitive Data Structures
• Primitive Data Structures
• Definition: Primitive data structures are predefined by the system and are directly operated upon by
machine instructions.
• Examples: char, int, float, double.
• Operations: The set of operations (like addition, subtraction) on these data types is predefined and can be
directly executed by the system.
• Non-Primitive Data Structures
• When primitive data structures are insufficient, we use derived and user-defined data structures.
• Derived Data Structures
• Definition: Derived data structures are built using primitive data types (e.g., arrays). They are provided
by the system but their structure is more complex.
• Examples: Arrays (e.g., array of int, array of char).
• Operations: Predefined operations, similar to primitives, are available for manipulation.
• User-Defined Data Structures
• Definition: Created by the user using primitive and derived types, with custom structures and
operations.
• Examples: Linked Lists, Trees, Stacks, Queues.
• Operations: The user defines the operations to perform on these structures using constructs like
structures or classes.
www.knowledgegate.in
www.knowledgegate.in
Data
Structure
Non-
Primitive
Primitive
Files
Integer float Character Pointer Array List
Non-linear
Linear List
list
Link List
Stack Queues Graphs Trees
www.knowledgegate.in
www.knowledgegate.in
LINEAR DATA STRUCTURE NON-LINEAR DATA STRUCTURE
• In a linear data structure, data elements are • In a non-linear data structure, data elements are
arranged in a linear order where each and every attached in hierarchical manner.
element are attached to its previous and next
adjacent.
• In linear data structure, single level is involved. • Whereas in non-linear data structure, multiple levels
are involved.
• Its implementation is easy in comparison to non- • While its implementation is complex in comparison
linear data structure. to linear data structure.
• In linear data structure, data elements can be • While in non-linear data structure, data elements
traversed in a single run only. can’t be traversed in a single run only.
• Its examples are: array, stack, queue, linked list, etc. • While its examples are: trees and graphs.
www.knowledgegate.in
www.knowledgegate.in
Homogeneous vs. Heterogeneous Data Structures
• Homogeneous Data: These data structures store elements of the same type, such as integers
or floats. A common example is an array, where all elements share the same data type.
• Heterogeneous Data: These data structures can hold elements of different types. For
example, a data structure may store integers, floats, and characters together. Examples
include structures and unions.
www.knowledgegate.in
www.knowledgegate.in
Array
• An array is a is a data structure that stores collection of elements of same type stored at
contiguous memory locations and can be accessed using an index.
int num[5];
www.knowledgegate.in
www.knowledgegate.in
How to declare an array in C
• datatype arrayName[array Size];
• int myarray[5];
• In C programming, when an array is declared, memory is allocated for its elements, but the
initial values of these elements remain undefined or contain garbage values. This means that
until explicitly initialized, the contents of a newly declared array in C are unpredictable.
• Array Size in C: It's crucial to note that in C, the size of an array is fixed upon declaration and
cannot be altered thereafter. This underscores the importance of planning array usage
according to fixed size constraints in C applications.
www.knowledgegate.in
www.knowledgegate.in
How to initialize and Change values in an array in C
• dataType arrayName[arraySize] = {value1, value2, ..., valueN};
• int myarray[5] = {1, 2, 3, 4, 5};
• int myarray[] = {1, 2, 3, 4, 5};
www.knowledgegate.in
www.knowledgegate.in
• Advantages of Arrays:
• Efficient Storage and Access: Arrays store elements in contiguous memory locations, allowing for fast
retrieval using indices, making them suitable for handling large amounts of data.
• Random Access: Arrays provide constant-time access to any element using its index, making operations like
reading or updating an element extremely efficient.
• Ease of Use: Arrays are simple to understand and use, with common sorting and searching algorithms like
binary search applicable, making them an accessible data structure for beginners and experts alike.
• Disadvantages of Arrays:
• Fixed Size: Once created, the size of an array cannot be changed, which can be restrictive when working with
dynamic data where the size of the data set may increase or decrease.
• Lack of Flexibility for Insertion/Deletion: Arrays do not natively support efficient insertion or deletion of
elements, as these operations may require shifting elements, which can be time-consuming.
• Homogeneous Elements: Arrays can only store elements of the same data type, limiting their flexibility in
scenarios that require handling multiple types of data.
www.knowledgegate.in
www.knowledgegate.in
• Types of indexing in array:
• 0 (zero-based indexing): The first element of the array is indexed by subscript of 0
• 1 (one-based indexing): The first element of the array is indexed by subscript of 1
• n (n-based indexing): The base index of an array can be freely chosen. Usually
programming languages allowing n-based indexing also allow negative index values and
other scalar data types like enumerations, or characters may be used as an array index.
www.knowledgegate.in
www.knowledgegate.in
Size of an array
• Number of elements = (Upper bound – Lower Bound) + 1
• Lower bound index of the first element of the array
• Upper bound index of the last element of the array
www.knowledgegate.in
www.knowledgegate.in
One Dimensional array
• Address of the element at kth index
• a[k] =
www.knowledgegate.in
www.knowledgegate.in
One Dimensional array
• Address of the element at kth index
• a[k] = B + W*k
• a[k] = B + W*(k – Lower bound)
• B is the base address of the array
• W is the size of each element
• K is the index of the element
• Lower bound index of the first element of the array
• Upper bound index of the last element of the array
www.knowledgegate.in
www.knowledgegate.in
Q Let the base address of the first element of the array is 250 and each
element of the array occupies 3 bytes in the memory, then address of
the fifth element of a one- dimensional array a[10] ?
www.knowledgegate.in
www.knowledgegate.in
Q An array has been declared as follows
A: array [-6--------6] of elements where every element takes 4 bytes, if
the base address of the array is 3500 find the address of array[0]?
www.knowledgegate.in
www.knowledgegate.in
Q A program P reads in 500 integers in the range [0...100] experimenting the
scores of 500 students. It then prints the frequency of each score above 50. What
would be the best way for P to store the frequencies? (GATE - 2005) (2 Marks)
[Asked in Cognizant 2016]
www.knowledgegate.in
www.knowledgegate.in
Two-Dimensional array
• A two-dimensional (2D) array is essentially an array of arrays. It is organized in a matrix-like structure,
consisting of rows and columns. This makes it ideal for representing data in a tabular format.
• 2D arrays are often used to simulate relational databases or other grid-based structures. They allow for
efficient storage and retrieval of large amounts of data, which can easily be passed to multiple
functions as needed, simplifying data management.
data_type array_name[rows][columns];
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
www.knowledgegate.in
www.knowledgegate.in
Implementation of 2D array
• In computing, row-major order and column-major order are methods for
storing multidimensional arrays in linear storage such as random access memory.
• The difference between the orders lies in which elements of an array are contiguous in
memory.
www.knowledgegate.in
www.knowledgegate.in
Row Major implementation of 2D array
• In Row major method elements of an array are arranged sequentially row by row.
• Thus, elements of first row occupies first set of memory locations reserved for the array,
elements of second row occupies the next set of memory and so on.
www.knowledgegate.in
www.knowledgegate.in
Row Major implementation of 2D array
Address of a[i][j] =
B = Base address
W = Size of each element
L1 = Lower bound of rows
U1 = Upper bound of rows
L2 = Lower bound of columns
U2 = Upper bound of columns
www.knowledgegate.in
www.knowledgegate.in
Row Major implementation of 2D array
www.knowledgegate.in
Q Let A be a two dimensional array declared as follows:
Assuming that each integer takes one memory location, the array is stored in row-major order and
the first element of the array is stored at location 100, what is the address of the element a[i][j] ?
(Gate-1998) (2 Marks)
(A) 15i+ j+ 84
(B) 15j+ i+ 84
(C) 10i+ j+ 89
(D) 10j+ i+ 89
www.knowledgegate.in
www.knowledgegate.in
Column Major implementation of 2D array
• In Column major method elements of an array are arranged sequentially column by column.
Thus, elements of first column occupies first set of memory locations reserved for the array,
elements of second column occupies the next set of memory and so on.
www.knowledgegate.in
www.knowledgegate.in
Column Major implementation of 2D array
Address of a[i][j] = B + W*[ (U1-L1+1) (j-L2) + (i-L1)]
B = Base address
W = Size of each element
L1 = Lower bound of rows
U1 = Upper bound of rows
L2 = Lower bound of columns
U2 = Upper bound of columns
(U1-L1+1) = numbers of rows
(j-L2) = number of columns before us
(i-L1) = number of elements before us in current column
www.knowledgegate.in
www.knowledgegate.in
Q An array VAL[1…15][1…10] is stored in the memory with each element
requiring 4 bytes of storage. If the base address of the array VAL is 1500,
determine the location of VAL[12][9] when the array VAL is stored
(i) Row wise (ii) Column wise.
www.knowledgegate.in
www.knowledgegate.in
Q A[5.....15,-8.....8] is A[11][17] and we are supposed to find
A[8][5] - Row Major Order Base Address:800, each element
occupies 4 memory cells?
www.knowledgegate.in
www.knowledgegate.in
Q Two matrices M1 and M2 are to be stored in arrays A and B respectively. Each
array can be stored either in row-major or column-major order in contiguous
memory locations. The time complexity of an algorithm to compute M 1 × M2 will
be (Gate-2004) (2 Marks)
(A) best if A is in row-major, and B is in column- major order
www.knowledgegate.in
www.knowledgegate.in
Q An n x n array v is defined as follows:
v[i, j] = i-j for all i, j, 1 <= i <= n, 1 <= j <= n
The sum of the elements of the array v is (Gate-2000) (1 Marks)
(A) 0
(B) n-1
(C) n2 - 3n + 2
(D) n2 (n+1)/2
www.knowledgegate.in
www.knowledgegate.in
3-Dimensional array
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
N-Dimensional array
www.knowledgegate.in
www.knowledgegate.in
N-Dimensional array
www.knowledgegate.in
www.knowledgegate.in
Q A Young tableau is a 2D array of integers increasing from left to right and from top to bottom.
Any unfilled entries are marked with ∞, and hence there cannot be any entry to the right of, or
below a ∞. The following Young tableau consists of unique entries (GATE - 2015) (2 Marks)
1 2 5 14
3 4 6 23
10 12 18 25
31 ∞ ∞ ∞
When an element is removed from a Young tableau, other elements should be moved into its
place so that the resulting table is still a Young tableau (unfilled
entries may be filled in with a ∞). The minimum number of entries (other than 1) to be shifted,
to remove 1 from the given Young tableau is ____________
(A) 2
(B) 5
(C) 6
(D) 18
www.knowledgegate.in
www.knowledgegate.in
Q Let A be a square matrix of size n x n. Consider the following program. What is the expected output? (GATE -
2014) (1 Marks) [Asked in Hexaware 2017] [Asked in Accenture]
C = 100
for i = 1 to n do
{
for j = 1 to n do
{
Temp = A[i][j] + C
A[i][j] = A[j][i]
A[j][i] = Temp - C
}
}
for i = 1 to n do
for j = 1 to n do
Output(A[i][j]);
www.knowledgegate.in
www.knowledgegate.in
Q Consider a n*n square matrix A, such that
A[i][j] = 0 if(i<j)
a) find the space required to store the array in memory
b) derive an address access formula to access this matrix (if stored in row major order)
www.knowledgegate.in
www.knowledgegate.in
Q In a compact one dimensional array representation for lower triangular matrix (all elements
above diagonal are zero) of size n x n, non zero elements of each row are stored one after
another, (i.e. elements of lower triangle) of each row are stored one after another,
starting from first row, the index of (i, j)th element of the lower triangular matrix in this new
representation is (GATE - 1994) (2 Marks)
(A) i+j
(B) i + j-1
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
Q Consider a n*n square matrix A, such that
A[i][j] = A[j][i]
find the space required to store the array in memory
www.knowledgegate.in
www.knowledgegate.in
Q Consider a n*n square matrix A, such that
A[i][j] = 0 if |i-j| > 1
find the space required to store the array in memory
www.knowledgegate.in
www.knowledgegate.in
Q Consider a n*n square matrix A, such that
A[i][j] = A[i-1][j-1] if i>0 && j>0, 0<=i,j<=n-1
find the space required to store the array in memory
www.knowledgegate.in
www.knowledgegate.in
Q Consider a n*n square matrix A, such that
0 1 2 3
0 00 01 02 03
1 10 11 12 13
2 20 21 22 23
3 30 31 32 33
www.knowledgegate.in
www.knowledgegate.in
Basics of Stack
www.knowledgegate.in
www.knowledgegate.in
STACK
• A stack is a linear data structure that follows the Last In, First Out (LIFO) or First In, Last Out (FILO)
principle. In a stack, both the addition (push) and removal (pop) of elements are performed from one
end, known as the Top of Stack (TOS).
• The last element added is the first to be removed.
• The first element added is the last to be removed.
• The top element is the most frequently accessible, while the element at the bottom is the least
accessible in the stack. This structure is widely used for tasks like function call management, expression
evaluation, and undo operations in software.
www.knowledgegate.in
www.knowledgegate.in
Q Choose the correct alternatives (more than one may be correct) and write the
corresponding letters only: The following sequence of operations is performed on a stack:
PUSH (10), PUSH (20), POP, PUSH (10), PUSH (20), POP, POP, POP, PUSH (20), POP The
sequence of values popped out is ? (GATE - 1991) (2 Marks)
a) 20,10,20,10,20
b) 20,20,10,10,20
c) 10,20,20,10,20
d) 20,20,10,20,10
www.knowledgegate.in
www.knowledgegate.in
Stack Implementation
• Stack is generally implemented in two ways.
• Static Implementation:
• Uses an array to create the stack.
• It is a simple and straightforward method but lacks flexibility.
• The size of the stack must be defined during design, which
can lead to inefficient memory utilization if the size needs
to change later.
• Dynamic Implementation:
• Also known as linked list implementation.
• This method uses pointers to dynamically allocate
memory, making it more flexible and efficient in
terms of memory usage.
www.knowledgegate.in
www.knowledgegate.in
Push operation: - The process of adding new element to the top of stack is called push
operation. the new element will be inserted at the top after every push operation the top
is incremented by one. in the case the array is full and no new element can be
accommodated it is called over-flow condition.
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following is true about linked list implementation of stack?
(A) In push operation, if new nodes are inserted at the beginning of linked list, then
in pop operation, nodes must be removed from end.
(B) In push operation, if new nodes are inserted at the end, then in pop operation,
nodes must be removed from the beginning.
(C) Both of the above
(D) None of the above
www.knowledgegate.in
www.knowledgegate.in
Pop: - The process of deleting an element. from the top of stack is called POP operation,
after every POP operation the stack is decremented by one if there is no element in the
stack and the POP operation is requested then this will result into a stack underflow
condition.
} 0
www.knowledgegate.in
www.knowledgegate.in
Q A single array A[1...MAXSIZE] is used to implement two stacks. The two stacks grow from
opposite ends of the array. Variables top1 and top2 (top1< top2) point to the location of the
topmost element in each of the stacks. If the space is to be used efficiently, the condition for
“stack full” is (GATE - 2004) (2 Marks) [Asked in Goldman Sachs 2018]
(A) (top1 = MAXSIZE/2) and (top2 = MAXSIZE/2+1)
www.knowledgegate.in
www.knowledgegate.in
Q Let S be a stack of size n >= 1. Starting with the empty stack, suppose we push the first n
natural numbers in sequence, and then perform n pop operations. Assume that Push and Pop
operation take X seconds each, and Y seconds elapse between the end of one such stack
operation and the start of the next operation. For m >= 1, define the stack-life of m as the time
elapsed from the end of Push(m) to the start of the pop operation that removes m from S. The
average stack-life of an element of this stack is (GATE - 2003) (2 Marks)
(A) n(X+ Y)
(B) 3Y + 2X
(D) Y + 2X
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following permutations can be obtained in the output (in
the same order) using a stack assuming that the input is the sequence 1,
2, 3, 4, 5 in that order? (GATE - 1994) (2 Marks)
a) 3, 4, 5, 1, 2
b) 3, 4, 5, 2, 1
c) 1, 5, 2, 3, 4
d) 5, 4, 3, 1, 2
www.knowledgegate.in
www.knowledgegate.in
Q if the input sequence is 5, 4, 3, 2, 1 then identify the wrong
stack permutation (possible pop sequence)?
a) 4, 2, 1, 3, 5
b) 5, 2, 3, 4, 1
c) 4, 5, 1, 2, 3
d) 3, 4, 5, 2, 1
www.knowledgegate.in
www.knowledgegate.in
Arithmetic expression
• An expression consists of operands combined with operators. There are three common notations for
representing expressions:
• Infix Notation: The operator is placed between operands (e.g., A + B). This is the most familiar form
used in everyday math.
• Prefix Notation (Polish Notation): The operator is placed before the operands (e.g., +AB). This
notation was introduced by the Polish logician Jan Łukasiewicz in 1924.
• Postfix Notation (Reverse Polish Notation): The operator is placed after the operands (e.g., AB+). It is
widely used in computer systems because it's well-suited for computational processes, particularly in
the design of Arithmetic and Logic Units (ALUs) within CPUs.
• Expressions entered into a computer are usually converted to postfix notation, stored in a stack, and
then evaluated.
www.knowledgegate.in
www.knowledgegate.in
Q Assume that the operators +, -, × are left associative and ^ is right associative.
The order of precedence (from highest to lowest) is ^, x, +, -. The postfix expression
corresponding to the infix expression a + b × c – d ^ e ^ f is (GATE - 2004) (2 Marks)
a+b×c–d^e^f
(A) abc × + def ^ ^ –
(B) abc × + de ^ f ^ –
(C) ab + c × d – e ^ f ^
(D) – + a × bc ^ ^ def
www.knowledgegate.in
www.knowledgegate.in
Q The postfix expression for the infix expression
A+B∗(C+D)/F+D∗E is: (GATE - 1995) (2 Marks)
A + B ∗ (C + D) / F + D ∗ E
a) AB+CD+∗F/D+E∗
b) ABCD+∗F/DE∗++
c) A∗B+CD/F∗DE++
d) A+∗BCD/F∗DE++
www.knowledgegate.in
www.knowledgegate.in
Q Consider an expression log(x!), convert it into both prefix and
post fix notation?
www.knowledgegate.in
www.knowledgegate.in
Q Compute the post fix equivalent of the following expression
(GATE - 1998) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q The result evaluating the postfix expression 10 5 + 60 6 / * 8 – is (GATE
- 2015) (1 Marks)
10 5 + 60 6 / * 8 –
(A) 284
(B) 213
(C) 142
www.knowledgegate.in
(D) 71 www.knowledgegate.in
Q The following postfix expression with single digit operands is evaluated using a
stack 8 2 3 ^ / 2 3 * + 5 1 * - .Note that ^ is the exponentiation operator. The top
two elements of the stack after the first * is evaluated are: (GATE - 2007) (2 Marks)
[Asked in Hexaware 2017 ]
823^/23*+51*-
(A) 6, 1
(B) 5, 7
(C) 3, 2
(D) 1, 5
www.knowledgegate.in
www.knowledgegate.in
Q The result evaluating the postfix expression
8 2 3 * 1 / + 4 1 * 2 / +
www.knowledgegate.in
www.knowledgegate.in
Q The result evaluating the prefix expression
+ + 8 / * 2 3 1 / * 4 1 2
www.knowledgegate.in
www.knowledgegate.in
Q if -, * and $ are used as subtraction, multiplication and exponential.
i) – is highest precedence, then * and the $
ii) all are L to R associative
3 – 2 * 4 $ 1 * 2 $ 3
www.knowledgegate.in
www.knowledgegate.in
Q if -, * and $ are used as subtraction, multiplication and exponential.
i) – is highest precedence, then * and the $
ii) all are R to L associative
2 * 2 – 1 $ 1 $ 4 – 2
www.knowledgegate.in
www.knowledgegate.in
Q To evaluate an expression without any embedded function calls:
(GATE - 2002) (1 Marks)
(A) One stack is enough
(C) As many stacks as the height of the expression tree are needed
www.knowledgegate.in
www.knowledgegate.in
Q The best data structure to check whether an arithmetic
expression has balanced parentheses is a ?(GATE - 2004) (1 Marks)
(A) queue
(B) stack
(C) tree
(D) list
www.knowledgegate.in
www.knowledgegate.in
Recursion
• Recursion is a powerful concept in programming, where a function calls itself to solve a problem. It
requires two essential elements:
• A base condition to stop the recursion.
• Logic to solve the problem step-by-step.
• Definition: A function is recursive if it invokes itself within its own definition. It is particularly useful for
solving problems involving repetitive tasks or iterations in reverse order.
• Types of Recursion:
• Direct Recursion: When a function calls itself directly. It can be:
• Tail Recursion: The recursive call is the last statement in the function.
• Head Recursion: The recursive call occurs before other operations.
• Indirect Recursion: When two or more functions call each other in a cycle.
• Recursion is an alternative to iteration, and both techniques are used to repeatedly execute a function.
www.knowledgegate.in
www.knowledgegate.in
Q Find the output of the following pseudo code?
Void main()
{
fun(4);
}
Void fun(int x)
{
if (x > 0)
{
Printf(“%d”, x);
fun(x - 1);
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find the output of the following pseudo code?
Void main()
{
fun(4);
}
Void fun(int x)
{
if (x > 0)
{
fun(x - 1);
Printf(“%d”, x);
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find the output of the following pseudo code?
Void main()
{
fun(3);
}
Void fun(int x)
{
if (x > 0)
{
Printf(“%d”, x);
fun(x - 1);
Printf(“%d”, x);
fun(x - 1);
Printf(“%d”, x);
}
www.knowledgegate.in
} www.knowledgegate.in
Q Find the output of the following pseudo code on n = 6?
int x(int n)
{
if (n < 3)
return 1;
Else
return x(n-1) + x(n-1) + 1;
}
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following recursive C function that takes two arguments
unsigned int foo (unsigned int n, unsigned int r)
{
if (n > 0)
return (n % r + foo (n/r, r));
else
return 0;
}
What is the return value of the function foo when it is called as
foo (345, 10)? (GATE - 2011) (2 Marks)
(A) 345
(B) 12
(C) 5
www.knowledgegate.in
(D) 3 www.knowledgegate.in
Q Consider the following recursive C function that takes two arguments
unsigned int foo (unsigned int n, unsigned int r)
{
if (n > 0)
return (n % r + foo (n/r, r));
else
return 0;
}
What is the return value of the function foo when it is called as
foo (513, 2)? (GATE - 2011) (2 Marks)
(A) 9
(B) 8
(C) 5
www.knowledgegate.in
(D) 2 www.knowledgegate.in
Q Consider the following ANSI C function:int SomeFunction (int x, int y) (GATE - 2021) (2 Marks)
int SomeFunction (int x, int y)
{
if ((x==1) || (y==1))
return 1;
if (x==y)
return x;
if (x > y)
return SomeFunction(x-y, y);
if (y > x)
return SomeFunction (x, y-x);
}
The value returned by SomeFunction(15, 255) is __________
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following ANSI C program (GATE - 2021) (2 Marks)
#include <stdio.h>
int foo(int x, int y, int q)
{
if ((x<=0) && (y<=0))
return q;
if (x<=0)
return foo(x, y-q, q);
if (y<=0)
return foo(x-q, y, q);
return foo(x, y-q, q) + foo(x-q, y, q);
}
int main( )
{
int r = foo(15, 15, 10);
printf(“%d”, r);
return 0;
}
www.knowledgegate.in
(D) 45 www.knowledgegate.in
Q What value would the following function return for the input x = 95?
Function fun (x:integer):integer;
Begin
If x > 100 then fun = x – 10
Else fun = fun(fun (x+11))
End;
a) 89
b) 90
c) 91
d) 92
www.knowledgegate.in
www.knowledgegate.in
Q. A function f defined on stacks of integers satisfies the following properties.
f(∅) = 0 and f (push (S, i)) = max (f(S), 0) + i for all stacks S and integers i.
If a stack S contains the integers 2, -3, 2, -1, 2 in order from bottom to top, what
is f(S)? [Asked in AMCAT 2016] (GATE-2005)(1 Marks)
a) 6
b) 4
c) 3
d) 2
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following C function. (Gate-2015) (1 Marks)
int fun (int n)
{
int x=1, k;
if (n==1)
return x;
for (k=1; k<n; ++k)
x = x + fun(k) * fun(n – k);
return x;
}
The return value of fun(5) is __________.
www.knowledgegate.in
www.knowledgegate.in
• In mathematics, the Fibonacci numbers, commonly denoted Fn, form
a sequence, called the Fibonacci sequence, such that each number is
the sum of the two preceding ones, starting from 0 and 1.
• if n==0, then f(n) = 0
• if n==1, then f(n) = 1
• if n > 1, then f(n-1) + f(n-2)
n 0 1 2 3 4 5 6 7 8 9 10 11 12
f(n)
No of invocation
No of addition
www.knowledgegate.in
www.knowledgegate.in
no of invocation = 2f(n+1) - 1
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
Tower of hanoi
• The Tower of Hanoi (also known as the Tower of Brahma) is a classic mathematical puzzle consisting of
three rods and a set of disks of varying sizes. The puzzle starts with the disks stacked on one rod in
ascending order, forming a conical shape.
• Objective: The goal is to move the entire stack of disks to another rod while following these rules:
• Only one disk can be moved at a time.
• A disk can only be placed on an empty rod or on a larger disk.
• No larger disk can be placed on top of a smaller disk.
www.knowledgegate.in
www.knowledgegate.in
• Story & Legend
• According to a story, an ancient temple in Kashi Vishwanath contains three posts with 64
golden disks. Brahmin priests, following an ancient prophecy, have been transferring the
disks according to the rules of Brahma since ancient times. This is why the puzzle is
sometimes referred to as the Tower of Brahma.
www.knowledgegate.in
www.knowledgegate.in
Tower(N, B, A, E)
{
if(n = 1)
{
B→E
return
}
tower(n-1, B, E, A);
B→E
tower(n-1, A, B, E);
Return
}
www.knowledgegate.in
Ackerman function A(m, n)
if(m = 0), the A(m, n) = n+1
if ((m != 0) && (n=0)), the A(m, n) = A(m-1, 1)
if ((m != 0) && (n != 0)), the A(m, n) = A(m-1, A(m, n-1))
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
Q Find the output of the following pseudo code?
void Print_array(a, i, j)
{
if (i = = j)
{
printf(‘’%d’, a[i]);
return;
}
Else
{
printf(‘’%d’, a[i]);
print_array(a, i+1, j)
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find the output of the following pseudo code?
void Print_array(a, i, j)
{
if (i = = j)
{
printf(‘’%d’, a[i]);
return;
}
Else
{
print_array(a, i+1, j)
printf(‘’%d’, a[i]);
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find the output of the following pseudo code?
void Print_somthing(a, i, j)
{
if (i = = j)
{
printf(‘’%d’, a[i]);
return;
}
Else
{
if(a[i] < a[j])
Print_somthing (a, i+1, j);
Else
Print_somthing (a, i, j-1);
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find what this function is doing?
void what(struct Bnode *t)
{
if (t)
{
what(t → LC);
printf(‘’%d’, t → data);
what(t → RC);
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find what this function is doing?
void what(struct Bnode *t)
{
if (t)
{
printf(‘’%d’, t → data);
what(t → LC);
what(t → RC);
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find what this function is doing?
void what(struct Bnode *t)
{
if (t)
{
what(t → LC);
what(t → RC);
printf(‘’%d’, t → data);
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find what this function is doing?
Void what(struct Bnode *t)
{
if (t)
{
printf(‘’%d’, t → data);
what(t → LC);
printf(‘’%d’, t → data);
what(t → RC);
printf(‘’%d’, t → data);
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Find what this function is doing?
Void A(struct Bnode *t)
{
if (t)
{
B(t → LC);
printf(‘’%d’, t → data);
B(t → RC);
}
}
www.knowledgegate.in
Q Following is C like pseudo code of a function that takes a number as an argument, and uses a stack S to do processing.
void fun (int n)
{
Stack S; // Say it creates an empty stack S
while (n > 0)
{
// This line pushes the value of n%2 to stack S
push (&S, n%2);
n = n/2;
}
// Run while Stack S is not empty
while (!isEmpty(&S))
printf("%d ", pop(&S)); // pop an element from S and print it
}
What does the above function do in general?
www.knowledgegate.in
Q What does the following function print for n = 25?
void fun(int n)
{
if (n == 0)
return;
printf("%d", n%2);
fun(n/2);
}
(A) 11001
(B) 10011
(C) 11111
(D) 00000
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following recursive function fun (x, y). What is the value of fun (4, 3)
int fun(int x, int y)
{
if (x == 0)
return y;
return fun(x - 1, x + y);
}
(A) 13
(B) 12
(C) 9
(D) 10
www.knowledgegate.in
www.knowledgegate.in
Q The output of following program
#include <stdio.h>
int fun(int n)
{
if (n == 4)
return n;
else
return 2*fun(n+1);
}
int main()
{
printf("%d ", fun(2));
return 0;
}
(A) 4
(B) 8
(C) 16
(D) Runtime Error
www.knowledgegate.in
www.knowledgegate.in
Q What does the following function do?
int fun(int x, int y)
{
if (y == 0)
return 0;
return (x + fun(x, y-1));
}
(A) x + y
(B) x + x*y
(C) x*y
www.knowledgegate.in
(D) xy www.knowledgegate.in
Q What does the following function do?
int fun(unsigned int n)
{
if (n == 0 || n == 1)
return n;
if (n%3 != 0)
return 0;
return fun(n/3);
}
www.knowledgegate.in
Q Output of following program?
#include<stdio.h>
void print(int n)
{
if (n > 4000)
return;
printf("%d ", n);
print(2*n);
printf("%d ", n);
}
int main()
{
print(1000);
getchar();
return 0;
}
(A) 1000 2000 4000
(B) 1000 2000 4000 4000 2000 1000
(C) 1000 2000 4000 2000 1000
(D) 1000 2000 2000 1000
www.knowledgegate.in
www.knowledgegate.in
Q Predict the output of following program
#include <stdio.h>
int f(int n)
{
if(n <= 1)
return 1;
if(n%2 == 0)
return f(n/2);
return f(n/2) + f(n/2+1);
}
int main()
{
printf("%d", f(11));
return 0;
}
(A) Stack Overflow (B) 3
(C) 4
www.knowledgegate.in
(D) 5
www.knowledgegate.in
Q What does fun2() do in general?
int fun(int x, int y)
{
if (y == 0)
return 0;
return (x + fun(x, y-1));
}
(A) queue
(B) stack
(C) tree
(D) list
www.knowledgegate.in
www.knowledgegate.in
Q Which one of the following is an application of Stack Data Structure?
(B) Recursion
www.knowledgegate.in
www.knowledgegate.in
Queue
• A queue is a linear data structure where elements are added at the rear and removed from
the front, following a First In, First Out (FIFO) principle. The first element inserted is the first
one to be removed, making it ideal for tasks that require orderly processing.
• As a non-primitive and homogeneous data structure, a queue ensures that all elements are of
the same type and are processed sequentially. This makes it useful for managing tasks like
printer spooling, process scheduling, and network traffic handling.
www.knowledgegate.in
www.knowledgegate.in
Representation of Queues
• Mostly each of our queues will be maintained by a linear array QUEUE and two pointer
variables: FRONT containing the location of the Front element of the queue and REAR,
containing the location of the rear element of the queue.
• Whenever an element is added to the queue, the value of REAR is increased by 1
• REAR = REAR + 1
• Whenever an element is deleted from the queue, the value of FRONT is increased by 1
• Front = Front + 1
• Total number of elements in a queue
• Rear – Front + 1
0 1 2 3 4 5 6 7
www.knowledgegate.in
www.knowledgegate.in
Q Which one of the following is an application of Queue Data Structure?
(B) When data is transferred asynchronously (data not necessarily received at same
rate as sent) between two processes
www.knowledgegate.in
www.knowledgegate.in
Insertion
0 1 2 3 4 5 6 7
www.knowledgegate.in
Deletion
0 1 2 3 4 5 6 7
www.knowledgegate.in
Q. Consider the following sequence of operations on an empty stack.
Push(54);push(52);pop();push(55);push(62);s=pop();
(a) 86
(b) 68
(c) 24
(d) 94
www.knowledgegate.in
www.knowledgegate.in
Analysis
0 1 2 3 4 5 6 7
www.knowledgegate.in
www.knowledgegate.in
Circular Queue
0 1 2 3 4 5 6 7
1. EnQ a, b, c
2. DeQ 1 element
3. EnQ d, e, f
4. EnQ g, h, I
5. DeQ 4 element
6. EnQ j, k, l, m, n
www.knowledgegate.in
www.knowledgegate.in
Circular Queue
Insertion
Enqueue(QUEUE, N, F, R, ITEM)
{
if ((F==0 && R==N-1) :: (F == R + 1))
Write over flow and exit
if (F = = -1)
Set F = 0 && R = 0
Else
R = (R + 1)%N
Queue[R] = ITEM
}
www.knowledgegate.in
www.knowledgegate.in
Circular Queue
Deletion 0 1 2 3 4 5 6 7
Dequeue(QUEUE, N, F, R, ITEM)
{
if (F == - 1)
Write under flow and exit
ITEM = QUEUE[F]
if (F = = R)
Set F = -1 && R = -1
Else
F = (F + 1)%N
Return item
}
www.knowledgegate.in
www.knowledgegate.in
Priority Queue
• A priority queue is a collection of elements such that each element has been
assigned a priority and such that the order in which elements are deleted and
processed comes from the following rules.
• An element of higher priority is processed before any element of lower
priority
• Two element with the same priority are processed according to the order in
which they were added to the queue.
www.knowledgegate.in
www.knowledgegate.in
Q A queue is implemented using a non-circular singly linked list. The queue has a head pointer
and a tail pointer, as shown in the figure. Let n denote the number of nodes in the queue. Let
'enqueue' be implemented by inserting a new node at the head, and 'dequeue' be implemented
by deletion of a node from the tail.
Which one of the following is the time complexity of the most time-efficient implementation of
'enqueue' and 'dequeue, respectively, for this data structure? (GATE - 2018) (2 Marks) [Asked in
Accenture 2020 ]
a) Θ(1), Θ(1)
b) Θ(1), Θ(n)
c) Θ(n), Θ(1)
d) Θ(n), Θ(n)
www.knowledgegate.in
www.knowledgegate.in
Q A Circular queue has been implemented using singly linked list where each node consists of a
value and a pointer to next node. We maintain exactly two pointers FRONT and REAR pointing to
the front node and rear node of queue. Which of the following statements is/are correct for
circular queue so that insertion and deletion operations can be performed in O(1) i.e. constant
time. (GATE - 2017) (2 Marks)
a) I only
b) II only
c) Both I and II
d) Neither I nor II
www.knowledgegate.in
www.knowledgegate.in
Q A circularly linked list is used to represent a Queue. A single variable p is used to access the
Queue. To which node should p point such that both the operations enQueue and deQueue can
be performed in constant time? (GATE - 2004) (2 Marks)
circularLinkedList
www.knowledgegate.in
www.knowledgegate.in
Q A queue is implemented using an array such that ENQUEUE and DEQUEUE operations are
performed efficiently. Which one of the following statements is CORRECT (n refers to the number
of items in the queue)? (GATE - 2016) (1 Marks)
a) Both operations can be performed in O(1) time
b) At most one operation can be performed in O(1) time but the worst case time for the other
operation will be Ω(n)
c) The worst case time complexity for both operations will be Ω(n)
www.knowledgegate.in
www.knowledgegate.in
Q Suppose implementation supports an instruction REVERSE, which reverses the order of elements on the stack, in
addition to the PUSH and POP instructions. Which one of the following statements is TRUE with respect to this
modified stack? (GATE - 2014) (2 Marks) [Asked in Goldman Sachs 2018]
a) A queue cannot be implemented using this stack.
b) A queue can be implemented where ENQUEUE takes a single instruction and DEQUEUE takes a sequence of two
instructions.
c) A queue can be implemented where ENQUEUE takes a sequence of three instructions and DEQUEUE takes a
single instruction.
d) A queue can be implemented where both ENQUEUE and DEQUEUE take a single instruction each.
www.knowledgegate.in
www.knowledgegate.in
Q Let Q denote a queue containing sixteen numbers and S be an empty stack. Head(Q) returns the
element at the head of the queue Q without removing it from Q. Similarly, Top(S) returns the element at
the top of S without removing it from S. Consider the algorithm given below. (GATE - 2016) (2 Marks)
The maximum possible number of iterations of the while loop in the algorithm is
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following operation along with Enqueue and Dequeue operations on queues, where k is a global parameter.
MultiDequeue(Q)
{
m=k
while (Q is not empty and m > 0)
{
Dequeue(Q)
m=m–1
}
}
What is the worst case time complexity of a sequence of n MultiDequeue() operations
on an initially empty queue? (GATE - 2013) (2 Marks)
a) Q(n)
b) Q(n + k)
c) Q(n k)
d) Q(n2)
www.knowledgegate.in
www.knowledgegate.in
Q Suppose you are given an implementation of a queue of integers. The operations that can be performed on the queue are:
i. isEmpty (Q) — returns true if the queue is empty, false otherwise.
ii. delete (Q) — deletes the element at the front of the queue and returns its value.
iii. insert (Q, i) — inserts the integer i at the rear of the queue.
Consider the following function:
void f (queue Q)
{
int i ;
if (!isEmpty(Q))
{
i = delete(Q);
f(Q);
insert(Q, i);
}
}
What operation is performed by the above function f? (GATE - 2007) (2 Marks)
[Asked in AMCAT 2017]
(A) Leaves the queue Q unchanged
(B) Reverses the order of the elements in the queue Q
(C) Deletes the element at the front of the queue Q and inserts it at the rear
keeping the other elements in the same order
(D) Empties the queue Q
www.knowledgegate.in
www.knowledgegate.in
Q Consider the queues Q1 containing four elements and Q2 containing none (shown as the Initial State in
the figure). The only operations allowed on these two queues are Enqueue(Q,element) and Dequeue(Q).
The minimum number of Enqueue operations on Q1 required to place the elements of Q1 in Q2 in reverse
order (shown as the Final State in the figure) without using any additional storage is___________. (GATE
2022) (2 MARKS)
www.knowledgegate.in
www.knowledgegate.in
Q A priority queue Q is used to implement a stack S that stores characters. PUSH(C) is
implemented as INSERT (Q, C, K) where K is an appropriate integer key chosen by the
implementation. POP is implemented as DELETEMIN(Q). For a sequence of operations, the keys
chosen are in (GATE - 1997) (2 Marks)
(A) Non-increasing order
www.knowledgegate.in
www.knowledgegate.in
Problem with Array
• Fixed size and reallocation: Arrays have a fixed size, which can lead to memory waste if the
allocated size is larger than the actual data. Resizing an array often requires creating a new
one and copying elements, which can be inefficient.
• Inefficient insertion and deletion: Adding or removing elements in the middle of an array
requires shifting the remaining elements, resulting in a higher time complexity (O(n))
compared to linked lists.
• Less flexible: Arrays can only store elements of the same data type, and their structure
cannot be easily adapted to different types (e.g., singly, doubly, circular) like linked lists.
0 1 2 3 4 5 6 7
www.knowledgegate.in
www.knowledgegate.in
Linked list
• A linked list is a dynamic data structure consisting of elements called nodes that are connected in a
linear sequence. Each node contains two main components:
• Data: This part stores the value or information of the node, which can be any data type like integers,
characters, or objects.
• Next Pointer: Known as the link field or next pointer, this part holds the address of the next node in
the list.
• The last node in a linked list has its next pointer set to NULL, indicating the end of the list. This means
there is no subsequent node to reference.
• A special pointer variable, commonly referred to as head (also known as start or first), points to the
first node in the list. If the list is empty—meaning it contains no nodes—the head pointer is set to
NULL.
struct node
{
int data;
struct node *next;
};
www.knowledgegate.in
www.knowledgegate.in
• Advantages of Linked Lists:
• Dynamic Sizing: They can grow or shrink at runtime, efficiently using memory without
needing a predefined size.
• Efficient Insertions and Deletions: Adding or removing elements is fast (O(1)) when the
position is known, without shifting other elements as in arrays.
• Versatility: Linked lists support various forms—singly, doubly, circular—and can store
different data types, offering flexibility for diverse applications.
• Disadvantages of Linked Lists:
• Slower Access Times: Accessing elements requires sequential traversal from the head,
resulting in (O(n) time complexity.
• Memory Overhead: Each node needs extra memory for pointers, increasing overall usage
compared to arrays.
• Complex Pointer Management: Handling pointers adds code complexity and risks errors
like memory leaks or segmentation faults.
www.knowledgegate.in
www.knowledgegate.in
Q Write a C-style pseudocode for Traversing a link list iteratively, where
pointer head have the address of the first node of the list?
void traverse(Node* head)
{
Node* ptr = head;
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Write a C-style pseudocode for Traversing a link list recursively, where
pointer head have the address of the first node of the list?
void traverse(Node* ptr)
{
if (ptr == NULL)
return;
printf("%d ", ptr->data);
traverse(ptr->next);
}
www.knowledgegate.in
www.knowledgegate.in
Q Write a C-style pseudocode for searching a key in a link list iteratively, where
pointer head have the address of the first node of the list?
Node* search(Node* head, int key)
{
Node* ptr = head;
while (ptr != NULL)
{
if (ptr->data == key)
return ptr;
else
ptr = ptr->next;
}
return NULL;
}
www.knowledgegate.in
www.knowledgegate.in
Q Write a C-style pseudocode for inserting a node with a key in the starting of link-list?
Typedef struct node
{
int data;
struct node* next;
};
www.knowledgegate.in
Q Write a C-style pseudocode for inserting a node with a key after a location in a link-list?
www.knowledgegate.in
www.knowledgegate.in
Q Write a C-style pseudocode for deleting a node from the starting of link-list?
www.knowledgegate.in
www.knowledgegate.in
Q Write a C-style pseudocode for deleting a node after a given location from the starting of link-list?
void deleteAfter(Node* loc)
{
if (loc == NULL)
return;
if (loc->next == NULL)
return;
Node* ptr = loc->next;
loc->next = ptr->next;
free(ptr);
}
www.knowledgegate.in
www.knowledgegate.in
Q Write a C-style pseudocode for reversing a link-list in a iteratively?
Void reverse(node** head)
{
if(*head!=null)
{
Struct node* p = *head;
Struct node* q = null;
Struct node* r;
While(p !=null)
{
r=q;
q=p;
p=p->next;
q->next = r;
}
*head = q;
}
www.knowledgegate.in
} www.knowledgegate.in
Q The following C function takes a single-linked list of integers as a parameter and rearranges the elements of the list. The function is called with the list
containing the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What will be the contents of the list after the function completes execution? (GATE-2008) (2
Marks) [Asked in Accenture 2020 ]
struct node
{ 1 2 3 4 5 6 7
int value;
struct node *next;
};
void rearrange(struct node *list)
{
struct node *p, * q;
int temp;
if ((!list) || !list->next)
return;
p = list;
q = list->next;
while(q)
{
temp = p->value;
p->value = q->value;
q->value = temp;
p = q->next;
q = p ? p->next:0;
}
}
(A) 1,2,3,4,5,6,7 (B) 2,1,4,3,6,5,7
(C) 1,3,2,5,4,7,6 (D) 2,3,4,5,6,7,1
www.knowledgegate.in
www.knowledgegate.in
Q The following C function takes a simply-linked list as input argument. It modifies the list by moving the last element to the front of the list and
returns the modified list. Some part of the code is left blank. Choose the correct alternative to replace the blank line. (GATE-2010) (2 Marks)
typedef struct node
{
int value;
struct node *next;
}Node;
www.knowledgegate.in
Q Consider the C code fragment given below. (GATE-2017) (1 Marks)
typedef struct node
{
int data;
node* next;
} node;
www.knowledgegate.in
Q Consider the function f defined below. (GATE-2003) (2 Marks) [Asked in Cognizant 2020]
struct item
{
int data;
struct item * next;
};
www.knowledgegate.in
Q What is the output of following function for start pointing to first node of
following linked list?
1->2->3->4->5->6
void fun(struct node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
(A) 1 4 6 6 4 1 (B) 1 3 5 1 3 5
(C) 1 2 3 5
www.knowledgegate.in
(D) 1 3 5 5 3 1
www.knowledgegate.in
Q Consider the following function to traverse a linked list.
void traverse(struct Node *head)
{
while (head->next != NULL)
{
printf("%d ", head->data);
head = head->next;
}
}
Which of the following is FALSE about above function?
(A) The function may crash when the linked list is empty
(B) The function doesn’t print the last node when the linked list is not empty
(D) none
www.knowledgegate.in
www.knowledgegate.in
Q The following function reverse() is supposed to reverse a singly linked list. There is one line missing at the end of the function.
struct node
{
int data;
struct node* next;
};
/* head_ref is a double pointer which points to head (or start) pointer of linked list */
static void reverse(struct node** head_ref)
{
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
/*ADD A STATEMENT HERE*/
}
What should be added in place of “/*ADD A STATEMENT HERE*/”,
so that the function correctly reverses a linked list.
www.knowledgegate.in
www.knowledgegate.in
Circular Linked List
• A singly circular linked list is a variation of a singly linked list where the last node points back
to the first node, forming a continuous loop. Unlike a standard singly linked list that ends with
a NULL pointer, the last node in a circular linked list references the first node.
• Circular Structure: The next pointer of the last node points to the first node, eliminating
the NULL reference and creating a circular flow.
• Efficient Operations: Useful for implementing data structures like queues and circular
buffers, allowing constant-time addition at the end and removal from the front.
• Traversal Considerations: Requires a stopping condition during traversal—such as
returning to the starting node or using a counter—to prevent infinite loops.
www.knowledgegate.in
www.knowledgegate.in
Header circular link list
• A header circular linked list is a singly circular linked list that begins with a special node called
the header node, which doesn't contain actual data but serves as a fixed reference point. This
simplifies operations like insertion and deletion at the beginning or end of the list by
eliminating special cases.
• Consistent Starting Point: The header node provides a uniform starting point, and the last
node's next pointer points back to it, maintaining the circular structure.
• Simplified Operations: With the header node always present, there's no need to handle
special cases for empty lists or edge nodes, reducing code complexity.
• Metadata Storage: The header node can store metadata such as the list's length,
optimizing performance for certain operations.
www.knowledgegate.in
www.knowledgegate.in
Doubly link list
• A doubly linked list is a data structure where each node contains a data element and two pointers: one
pointing to the previous node and one to the next node. This bidirectional linking allows for traversal
and manipulation of the list in both forward and backward directions, simplifying operations like
insertion or deletion at any position.
• Bidirectional Pointers: Each node has a next pointer to the subsequent node and a previous
pointer to the preceding node.
• Terminal Nodes: The previous pointer of the first node and the next pointer of the last node are
set to NULL, indicating the start and end of the list.
• Ease of Traversal: Enables efficient traversal and manipulation in both directions compared to
singly linked lists.
• Memory Overhead: Consumes more memory than singly linked lists due to the additional previous
pointer.
www.knowledgegate.in
www.knowledgegate.in
Header Circular Doubly Link List
• A header circular doubly linked list is a doubly linked list that includes a special header node and
forms a circular structure. The header node does not contain data but serves as a fixed reference
point, simplifying operations by eliminating special cases when inserting or deleting at the beginning
or end.
• Header Node: Provides a consistent starting point for traversal and manipulation, and can store
metadata like the list's length.
• Circular Structure: The last node's next pointer points back to the header node, and the header's
previous pointer points to the last node, allowing continuous traversal without encountering
NULL pointers.
• Bidirectional Links: Each node has next and previous pointers, enabling efficient traversal in both
forward and backward directions.
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node
of doubly linked list has previous pointer as prev and next pointer as next. (GATE-1996) (2 Marks)
void fun(struct node **head_ref)
{
struct node *temp = NULL;
struct node *current = *head_ref;
while (current != NULL)
{
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
if(temp != NULL )
*head_ref = temp->prev;
}
Assume that reference of head of following doubly linked list is passed to above function
1 <--> 2 <--> 3 <--> 4 <--> 5 <-->6.
What should be the modified linked list after the function call?
(A) 2 <--> 1 <--> 4 <--> 3 <--> 6 <-->5
(B) 5 <--> 4 <--> 3 <--> 2 <--> 1 <-->6.
(C) 6 <--> 5 <--> 4 <--> 3 <--> 2 <--> 1.
www.knowledgegate.in
(B) O(N)
(C) O(N2)
www.knowledgegate.in
www.knowledgegate.in
Q The concatenation of two lists is to be performed in O(1) time. Which of the
following implementations of a list should be used? (Gate-1997) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following points is/are true about Linked List data structure when
it is compared with array
(A) Arrays have better cache locality that can make them better in terms of
performance.
(B) It is easy to insert and delete elements in Linked List
(C) Random access is not allowed in a typical implementation of Linked Lists
(D) All of the above
www.knowledgegate.in
www.knowledgegate.in
Q In the worst case, the number of comparisons needed to search a single linked
list of length n for a given element is (Gate-2002) (1 Marks)
a) logn
b) n/2
c) log2n−1
d) n
www.knowledgegate.in
www.knowledgegate.in
Q Suppose each set is represented as a linked list with elements in arbitrary order.
Which of the operations among union, intersection, membership, cardinality will
be the slowest? (Gate-2004) (2 Marks) [Asked in AMCAT 2017]
(A) union only
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following statements: (GATE - 1996) (2 Marks) [Asked in TCS NQT 2019]
i) First-in-first out types of computations are efficiently supported by STACKS.
ii) Implementing LISTS on linked lists is more efficient than implementing LISTS on an array for
almost all the basic LIST operations.
iii) Implementing QUEUES on a circular array is more efficient than implementing QUEUES on a
linear array with two indices.
iv) Last-in-first-out type of computations are efficiently supported by QUEUES.
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following ANSI C program: Which one of the following statements below is correct about the program?(GATE 2021) (2 MARKS)
#include < stdio.h > (a) Upon execution, the program creates a linked-list of
#include < stdlib.h > five nodes
struct Node
{
int value; (b) Upon execution, the program goes into an infinite loop
struct Node *next;
}; (c) It has a missing return which will be reported as an
int main( ) error by the compiler
{
struct Node *boxE, *head, *boxN; int index=0; (d) It dereferences an uninitialized pointer that may result
boxE=head= (struct Node *) malloc(sizeof(struct Node));
head → value = index;
in a run-time error
for (index =1; index<=3; index++)
{
boxN = (struct Node *) malloc (sizeof(struct Node));
boxE → next = boxN;
boxN → value = index;
boxE = boxN;
}
for (index=0; index<=3; index++)
{
printf(“Value at index %d is %dn”, index, head → value);
head = head → next;
printf(“Value at index %d is %dn”, index+1, head → value);
}
www.knowledgegate.in
www.knowledgegate.in
Q Consider the problem of reversing a singly linked list. To take an example, given the linked list below,
Which one of the following statements is TRUE about the time complexity of algorithms that solve the above
problem in O(1) space? (GATE 2022) (1 MARKS)
(A) The best algorithm for the problem takes O (n) time in the worst case.
(B) The best algorithm for the problem takes O (n log n) time in the worst case.
(C) The best algorithm for the problem takes O (n^2 ) time in the worst case.
www.knowledgegate.in
www.knowledgegate.in
Q Let SLLdel be a function that deletes a node in a singly-linked list given a pointer to the node
and a pointer to the head of the list. Similarly, let DLLdel be another function that deletes a
node in a doubly-linked list given a pointer to the node and a pointer to the head of the list.
Let n denote the number of nodes in each of the linked lists. Which one of the following choices
is TRUE about the worst-case time complexity of SLLdel and DLLdel? (Gate-2023) (1 Marks)
(a) SLLdel is O(1) and DLLdel is O(n)
www.knowledgegate.in
www.knowledgegate.in
Q find nth node from the end of a link list?
www.knowledgegate.in
www.knowledgegate.in
Q Given pointer to a node X in a singly linked list. Only one pointer is given, pointer
to head node is not given, can we delete the node X from given linked list?
(A) Possible if X is not last node. Use following two steps (a) Copy the data of next
of X to X. (b) Delete next of X.
(D) Possible if X is not first node. Use following two steps (a) Copy the data of next
of X to X. (b) Delete next of X.
www.knowledgegate.in
www.knowledgegate.in
Tree
• A tree is a nonlinear data structure that represents hierarchical relationships between data items. It is
widely used due to its flexibility and versatility. The root node is the starting point, and each node
(except the root) is connected to exactly one parent node, forming a parent-child relationship.
• Root Node: The top-most node in the tree.
• Subtrees: A tree can be divided into smaller subsets called subtrees, each acting as an independent tree.
• Applications: Trees are used in file systems, database indexing, decision-making, and many more.
www.knowledgegate.in
www.knowledgegate.in
• Root Node: The top-most node, serving as the origin of the tree.
• Edge: The connection between two nodes. A tree with 'N' nodes has exactly 'N-1' edges.
• Parent Node: A node that has one or more children.
• Child Node: A node that descends from a parent node.
• Leaf (External) Node: A node with no children.
• Internal Node: A node with at least one child.
• Degree of Node: The number of children a node has.
• Level/Depth: Indicates the step count from the root (Level 0) to a particular node.
• Path: A sequence of nodes connected by edges.
• Subtree: A tree formed from a child node and its descendants.
www.knowledgegate.in
www.knowledgegate.in
Binary tree
• A binary tree is a type of tree data structure where each node can have at most two children,
commonly referred to as left and right child nodes. It is structured as a set of nodes with the following
properties:
• Empty Tree: A binary tree can be empty (no nodes).
• Root Node: If not empty, the tree has a unique root node (R).
• Subtrees: The remaining nodes are partitioned into two disjoint subtrees, T1 (left) and T2 (right).
• Representation of tree in memory
• Sequential representation – using an array info and left child and right child
• Linked Representation – using self-referential structure node
struct node {
int data;
struct node* left;
struct node* right;
}
www.knowledgegate.in
www.knowledgegate.in
Q Let T be a binary search tree with 15 nodes. The minimum and
maximum possible heights of T are: _______ (GATE-2017) (1 Marks)
(A) 4 and 15 respectively (B) 3 and 14 respectively
www.knowledgegate.in
www.knowledgegate.in
Q The height of a tree is the length of the longest root-to-leaf path in it.
The maximum and minimum number of nodes in a binary tree of height
5 are (GATE - 2015) (1 Marks)
(A) 63 and 6, respectively (B) 64 and 5, respectively
www.knowledgegate.in
www.knowledgegate.in
Q The height of a binary tree is the maximum number of edges in any root to leaf
path. The maximum number of nodes in a binary tree of height h is: (GATE-2007)
(1 Marks)
a) 2h−1 b) 2h−1 – 1
c) 2h+1– 1 d) 2h+1
www.knowledgegate.in
www.knowledgegate.in
Q In a binary tree, for every node the difference between the number of
nodes in the left and right subtrees is at most 2. If the height of the tree
is h>0, then the minimum number of nodes in the tree is (GATE-2005) (2
Marks)
a) 2 h−1 b) 2 h−1 + 1 c) 2 h − 1 d) 2 h
www.knowledgegate.in
www.knowledgegate.in
Q In a binary tree with n nodes, every node has an odd number of descendants.
Every node is considered to be its own descendant. What is the number of nodes
in the tree that have exactly one child? (GATE - 2010) (1 Marks)
(A) 0 (B) 1 (C) (n-1)/2 (D) n-1
www.knowledgegate.in
www.knowledgegate.in
Q if number of leaves in a tree is not a power of 2, then the tree
is not a binary tree? (GATE-1987) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Traversal of binary tree
• The process of visiting (checking and/or updating) each node in a tree data structure, exactly once in called tree
traversal. Such traversals are classified by the order in which the nodes are visited. Unlike linked lists, one-
dimensional arrays and other linear data structures, which are traversed in linear order, trees may be traversed
in multiple ways.
• They may be traversed in depth-first or breadth-first order. There are three common ways to traverse them in
depth-first order: in-order, pre-order and post-order. Beyond these basic traversals, various more complex or
hybrid schemes are possible, such as depth-limited searches like iterative deepening depth-first search.
• Some applications do not require that the nodes be visited in any particular order as long as each node is visited
precisely once. For other applications, nodes must be visited in an order that preserves some relationship.
• Pre-order (Root-Left-Right): Visit root, then left subtree, followed by right subtree.
• In-order (Left-Root-Right): Visit left subtree, then root, and finally right subtree.
• Post-order (Left-Right-Root): Visit left subtree, then right subtree, and root last.
www.knowledgegate.in
www.knowledgegate.in
Pre-order (Root L R) In-order (L root R) Post-order (L R Root)
F, B, A, D, C, E, G, I, H A, B, C, D, E, F, G, H, I A, C, E, D, B, H, I, G, F
www.knowledgegate.in
www.knowledgegate.in
Q which of the following binary trees has its inorder and preorder traversal as BCAD and ABCD,
respectively? (GATE-2004) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q which of the following is post order traversal of the above tree (GATE-1991) (1 Marks)
a) fegcbdba
b) gcbdafe
c) gcdbfea
d) fedgcba
www.knowledgegate.in
www.knowledgegate.in
Q What is common in three different types of traversals (Inorder,
Preorder and Post order)?
(A) Root is visited before right subtree
(B) Left subtree is always visited before right subtree
(C) Root is visited after left subtree
(D) All of the above
www.knowledgegate.in
www.knowledgegate.in
Q level order traversal of a rooted tree can be done by starting from the
root and performing (GATE-2004) (2 Marks)
a) preorder traversal b) inorder traversal
c) dfs d) bfs
www.knowledgegate.in
www.knowledgegate.in
Q The following three are known to be the preorder, inorder and post order sequences of
a binary tree. But it is not known which is which.
c) II is the inorder sequence, but nothing more can be said about the other two
sequences
www.knowledgegate.in
Q Consider the following statements.
• S1: The sequence of procedure calls corresponds to a preorder traversal of the
activation tree.
• S2: The sequence of procedure returns corresponds to a postorder traversal of
the activation tree.
Which one of the following options is correct? (GATE 2021)
(a) S1 is true and S2 is false
www.knowledgegate.in
www.knowledgegate.in
Q The post order traversal of a binary tree is 8, 9, 6, 7, 4, 5, 2, 3, 1. The inorder
traversal of the same tree is 8, 6, 9, 4, 7, 2, 5, 1, 3. The height of a tree is the length
of the longest path from the root to any leaf. The height of the binary tree above is
________. (GATE-2018) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q The inorder and preorder traversal of a binary tree are d b e a f c g and
a b d e c f g, respectively. The post order traversal of the binary tree is:
(GATE-2007) (2 Marks)
(A) d e b f g c a (B) e d b g f c a
(C) e d b f g c a (D) d e f g b c a
www.knowledgegate.in
www.knowledgegate.in
Q is it possible to construct a binary tree uniquely whose post order and
pre order traversal are given? (GATE-1987) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following pairs of traversals is not sufficient to build a
binary tree from the given traversals?
(A) Preorder and Inorder (B) Preorder and Post order
(C) Inorder and Post order (D) level order and post order
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following New-order strategy for traversing a binary tree: Visit the
root; Visit the right subtree using New-order Visit the left subtree using New-order
The New-order traversal of the expression tree corresponding to the reverse polish
expression 3 4 * 5 - 2 ˆ 6 7 * 1 + - is given by: (GATE-2016) (1 Marks)
a) + - 1 6 7 * 2 ˆ 5 - 3 4 * b) - + 1 * 6 7 ˆ 2 - 5 * 3 4
c) - + 1 * 7 6 ˆ 2 - 5 * 4 3 d) 1 7 6 * + 2 5 4 3 * - ˆ -
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following rooted tree with the vertex labeled P as the
root:The order in which the nodes are visited during an in-order traversal
of the tree is (GATE-2014) (1 Marks)
a) SQPTRWUV
b) SQPTUWRV
c) SQPTWUVR
D) SQPTRUWV
www.knowledgegate.in
www.knowledgegate.in
Q The height of a tree is defined as the number of edges on the longest path in the tree. The function shown in
the pseudocode below is invoked as height (root) to compute the height of a binary tree rooted at the tree
pointer root. (GATE-2012) (2 Marks)
www.knowledgegate.in
Q Consider the following C program segment
struct CellNode
{
struct CelINode *leftchild;
int element;
struct CelINode *rightChild;
}
www.knowledgegate.in
Q What does the following function do for a given binary tree?
int fun (struct node *root)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 0;
return 1 + fun(root->left) + fun(root->right);
}
www.knowledgegate.in
Q Following function is supposed to calculate the maximum depth or height of a Binary tree —( root is at level 1)
int maxDepth (struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return X;
else return Y;
}
}
What should be the values of X and Y so that the function works correctly?
(A) X = lDepth, Y = rDepth
(B) X = lDepth + 1, Y = rDepth + 1
(C) X = lDepth – 1, Y = rDepth -1
(D) None of the above
www.knowledgegate.in
www.knowledgegate.in
Binary search tree / Ordered tree / Sorted binary tree
• A binary search tree (BST) is a binary tree in which left subtree of a node contains a key less
than the node’s key and right subtree of a node contains only the nodes with key greater than
the node’s key. Left and right sub tree must each also be a binary search tree. Binary search
trees support three main operations: insertion of elements, deletion of elements, and lookup
(checking whether a key is present).
www.knowledgegate.in
www.knowledgegate.in
Q While inserting the elements 71, 65, 84, 69, 67, 83 in an empty binary
search tree (BST) in the sequence shown, the element in the lowest level
is (GATE-2015) (1 Marks)
(A) 65 (B) 67 (C) 69 (D) 83
www.knowledgegate.in
www.knowledgegate.in
Q The following numbers are inserted into an empty binary search tree in the given
order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the
height is the maximum distance of a leaf node from the root)? (GATE-2004) (1
Marks)
a) 2 b) 3 c) 4 d) 6
www.knowledgegate.in
www.knowledgegate.in
Q A binary search tree is generated by inserting in order the following
integers: 50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24
The number of nodes in the left subtree and right subtree of the root
respectively is (GATE-1996) (2 Marks)
a) (4,7) b) (7,4) c) (8,3) d) (3,8)
www.knowledgegate.in
www.knowledgegate.in
• Insertion
• The insertion operation in a binary tree is similar to a search.
• Start from the root and traverse down the tree:
• Left Subtree: Insert into the left if the new node’s key is less than the current node's key.
• Right Subtree: Insert into the right if it’s greater than or equal to the current node's key.
• Add the new node at an external position once the correct spot is found.
• Deletion
• Three main cases need to be handled when deleting a node:
• Node with No Children: Directly remove the node.
• Node with One Child: Remove the node and connect its child to its parent.
• Node with Two Children:
• Do not delete the node.
• Choose the in-order predecessor (maximum node of the left subtree) or the in-order successor
(minimum node of the right subtree).
• Replace the node’s value with the selected node.
• Remove the selected node from its original position (which will be either a leaf or a node with one child).
www.knowledgegate.in
www.knowledgegate.in
• The major advantage of binary search trees over other data structures is that the
related sorting algorithms and search algorithm such as in-order traversal can be very efficient;
they are also easy to code
Algorithm Average Worst case
Space O(n) O(n)
Search O(log n) O(n)
Insert O(log n) O(n)
Delete O(log n) O(n)
www.knowledgegate.in
www.knowledgegate.in
Q The pre-order traversal of a binary search tree is given by 12, 8, 6, 2, 7, 9, 10, 16,
15, 19, 17, 20. Then the post-order traversal of this tree is: (GATE-2017) (2 Marks)
a) 2, 6, 7, 8, 9, 10, 12, 15, 16, 17, 19, 20
b) 2, 7, 6, 10, 9, 8, 15, 17, 20, 19, 16, 12
c) 7, 2, 6, 8, 9, 10, 20, 17, 19, 15, 16, 12
d) 7, 6, 2, 10, 9, 8, 15, 16, 17, 20, 19, 12
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following is/are correct inorder traversal sequence(s) of binary
search tree(s)? (GATE-2015) (1 Marks)
1. 3, 5, 7, 8, 15, 19, 25
2. 5, 8, 9, 12, 10, 15, 25
3. 2, 7, 10, 8, 14, 16, 20
4. 4, 6, 7, 9, 18, 20, 25
a) 1 and 4 only b) 2 and 3 only c) 2 and 4 only d) 2 only
www.knowledgegate.in
www.knowledgegate.in
Q The preorder traversal sequence of a binary search tree is 30, 20, 10, 15, 25, 23,
39, 35, 42. Which one of the following is the post order traversal sequence of the
same tree? (GATE-2013) (1 Marks)
a) 10, 20, 15, 23, 25, 35, 42, 39, 30 b) 15, 10, 25, 23, 20, 42, 35, 39, 30
c) 15, 20, 10, 23, 25, 42, 35, 39, 30 d) 15, 10, 23, 25, 20, 35, 42, 39, 30
www.knowledgegate.in
www.knowledgegate.in
Q Post order traversal of a given binary search tree, T produces the following
sequence of keys 10, 9, 23, 22, 27, 25, 15, 50, 95, 60, 40, 29 Which one of the
following sequences of keys can be the result of an in-order traversal of the tree T?
(GATE - 2005) (1 Marks)
(A) 9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95
(B) 9, 10, 15, 22, 40, 50, 60, 95, 23, 25, 27, 29
(C) 29, 15, 9, 10, 25, 22, 23, 27, 40, 60, 50, 95
(D) 95, 50, 60, 40, 27, 23, 22, 25, 10, 9, 15, 29
www.knowledgegate.in
www.knowledgegate.in
Q A binary search tree contains the numbers 1,2,3,4,5,6,7,8. When the tree is
traversed in pre-order and the values in each node printed out, the sequence of
values obtained is 5,3,1,2,4,6,8,7. If the tree is traversed in post-order, the
sequence obtained would be (GATE - 2005) (1 Marks)
a) 8,7,6,5,4,3,2,1 b) 1,2,3,4,8,7,6,5
c) 2,1,4,3,6,7,8,5 d) 2,1,4,3,7,8,6,5
www.knowledgegate.in
www.knowledgegate.in
Q Suppose the numbers 7, 5, 1, 8, 3, 6, 0, 9, 4, 2 are inserted in that
order into an initially empty binary search tree. The binary search tree
uses the usual ordering on natural numbers. What is the in-order
traversal sequence of the resultant tree? (Gate-2003) (2 Marks)
(A) 7 5 1 0 3 2 4 6 8 9 (B) 0 2 4 3 1 6 5 9 8 7
(C) 0 1 2 3 4 5 6 7 8 9 (D) 9 8 6 4 2 3 0 1 5 7
www.knowledgegate.in
www.knowledgegate.in
Q A binary search tree contains the value 1,2,3,4,5,6,7,8. The tree is traversed in
pre-order and the values are printed out. Which of the following sequences is a
valid output? (Gate-1997) (2 Marks)
a) 5 3 1 2 4 7 8 6 b) 5 3 1 2 6 4 8 7
c) 5 3 2 4 1 6 7 8 d) 5 3 1 2 4 7 6 8
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
Q The number of ways in which the numbers 1, 2, 3, 4, 5, 6, 7 can be inserted in an
empty binary search tree, such that the resulting tree has height 6, is
_____________ Note: The height of a tree with a single node is 0. (GATE-2016) (1
Marks)
www.knowledgegate.in
www.knowledgegate.in
Q When searching for the key value 60 in a binary search tree, nodes containing
the key values 10, 20, 40, 50, 70, 80, 90 are traversed, not necessarily in the order
given. How many different orders are possible in which these key values can occur
on the search path from the root to the node containing the value 60? (GATE-
2007) (2 Marks)
a) 35 b) 64 c) 128 d) 5040
www.knowledgegate.in
www.knowledgegate.in
Q The numbers 1,2,.…n are inserted in a binary search tree in some order. In the
resulting tree, the right subtree of the root contains p nodes. The first number to
be inserted in the tree must be (GATE-2005) (1 Marks)
a) P b) p+1 c) n−p d) n−p+1
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
Q What is the worst case time complexity for search, insert and delete
operations in a general Binary Search Tree?
(A) O(n) for all
(B) O(Logn) for all
(C) O(Logn) for search and insert, and O(n) for delete
(D) O(Logn) for search, and O(n) for insert and delete
www.knowledgegate.in
www.knowledgegate.in
Q What are the worst-case complexities of insertion and deletion of a
key in a binary search tree? (GATE-2015) (1 Marks)
a) Θ(logn) for both insertion and deletion
b) Θ(n) for both insertion and deletion
c) Θ(n) for insertion and Θ(logn) for deletion
d) Θ(logn) for insertion and Θ(n) for deletion
www.knowledgegate.in
www.knowledgegate.in
Q Which one of the following is the tightest upper bound that
represents the time complexity of inserting an object into a binary
search tree of n nodes? (GATE-2013) (1 Marks)
a) O(1) b) O(Logn) c) O(n) d) O(n Logn)
www.knowledgegate.in
www.knowledgegate.in
Q You are given the post order traversal, P, of a binary search tree on the n
elements 1, 2, ..., n. You have to determine the unique binary search tree that has
P as its post order traversal. What is the time complexity of the most efficient
algorithm for doing this? (GATE-2008) (1 Marks)
a) θ(log n)
b) θ(n)
c) θ(n log n)
www.knowledgegate.in
www.knowledgegate.in
AVL tree
• In computer science, an AVL tree (named after inventors Adelson-Velsky and Landis) is a self-balancing binary
search tree. It was the first such data structure to be invented. In an AVL tree, the heights of the
two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is
done to restore this property.
Adelson-Velsky Landis
www.knowledgegate.in
www.knowledgegate.in
Balance factor
• In a binary tree the balance factor of a node N is defined to be the height difference Balance Factor(N): = Height
(LeftSubtree(N)) – Height (RightSubtree(N)) of its two child subtrees.
• A binary tree is defined to be an AVL tree if the invariant Balance Factor(N) ∈ {–1, 0, +1} holds for every node N in
the tree.
• A node N with Balance Factor(N) > 0 is called "left-heavy“
www.knowledgegate.in
www.knowledgegate.in
Insertion in an AVL tree
• Insert a node similarly as we do in binary search tree.
• After insertion start checking the balancing factor of each node in a bottom up fashion that is from
newly inserted node towards the root.
• Stop on the first node whose balancing factor is violated and go two steps towards the newly inserted
nodes. watch the movement, which is identified as the problem.
• After every insertion at most two rotations are sufficient to balance the AVL tree
Problem Solution
LL R
RR L
LR LR
RL RL
www.knowledgegate.in
www.knowledgegate.in
Q Consider an empty AVL tree and insert the following nodes in
sequence 21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3, 7?
www.knowledgegate.in
www.knowledgegate.in
Q Consider an empty AVL tree and insert the following
nodes in sequence a, z, x, i, d, n, m, r, s, j, b, c, g?
www.knowledgegate.in
www.knowledgegate.in
Q Create an AVL tree with 70, 60, 80, 50, 65 and 68 how many leaves are
there in the resultant tree?
a) 2 b) 3 c) 4 D) 5
www.knowledgegate.in
www.knowledgegate.in
Q What is the worst-case possible height of AVL tree?
(A) 2 Log2 n (B) 1.44 log2 n
www.knowledgegate.in
www.knowledgegate.in
Q What is the maximum height of any AVL-tree with 7 nodes? Assume
that the height of a tree with a single node is 0. (GATE-2009) (1 Marks)
(A) 2 (B) 3 (C) 4 (D) 5
www.knowledgegate.in
www.knowledgegate.in
Deletion in an AVL tree
AVL
Deletion
L R
L0 L1 L-1 R0 R1 R-1
RR RL RR LL LL LR
www.knowledgegate.in
www.knowledgegate.in
Deletion in an AVL tree
Q delete the following nodes in sequence 2, 3, 10, 18, 4, 9, 14, 7,
15 ?
www.knowledgegate.in
www.knowledgegate.in
Analysis of AVL tree
• Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number
of nodes in the tree prior to the operation.
• Insertions and deletions may require the tree to be rebalanced by one or more tree rotations.
www.knowledgegate.in
www.knowledgegate.in
Q insert the following keys in the order to build AVL tree: - A, Z,
B, Y, C, X, D, W, E, V, F, the root of the resultant tree is
a) C b) D c) E d) V
www.knowledgegate.in
www.knowledgegate.in
Q from the above tree if A, Z, B, Y, C are deleted, then what will
be the new root
a) C b) D c) E d) V
www.knowledgegate.in
www.knowledgegate.in
Q Suppose we have a balanced binary search tree T holding n numbers. We are given two
numbers L and H and wish to sum up all the numbers in T that lie between L and H. Suppose
there are m such numbers in T. If the tightest upper bound on the time to compute the sum is
O(nalogb n + mc logd n), the value of a + 10b + 100c + 1000d is ____. (GATE-2014) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following is TRUE? (GATE-2008) (1 Marks)
a) The cost of searching an AVL tree is Θ(logn) but that of a binary search tree is O(n)
b) The cost of searching an AVL tree is Θ(logn) but that of a complete binary tree
is Θ(nlogn)
c) The cost of searching a binary search tree is O(logn) but that of an AVL tree is Θ(n)
d) The cost of searching an AVL tree is Θ(nlogn) but that of a binary search tree is O(n)
www.knowledgegate.in
www.knowledgegate.in
Q A binary search tree T contains n distinct elements. What is the time complexity
of picking an element in T that is smaller than the maximum element in T? (GATE
2021)
(a) Θ(nlogn)
(b) Θ(n)
(c) Θ(logn)
(d) Θ(1)
www.knowledgegate.in
www.knowledgegate.in
Q Which one of the following sequences when stored in an array at
locations A[1],..., A[10] forms a max-heap? (Gate-2023) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Complete Binary Tree
• Consider a binary tree T, the maximum number of nodes at height h is 2 h nodes.
• The binary tree T is said to be complete binary tree, if all its level except possibly
the last, have the maximum number of nodes and if all the nodes at the last level
appear as far left as possible.
www.knowledgegate.in
www.knowledgegate.in
• One can easily determine the children and parent of a node k in any complete
tree T
• Specially the left and right children of the node K are 2*k, 2*k + 1 and the parent
of k is the node lower bound(k/2)
www.knowledgegate.in
www.knowledgegate.in
Q A scheme for storing binary trees in an array X is as follows. Indexing of X starts
at 1 instead of 0. the root is stored at X[1]. For a node stored at X[i], the left child, if
any, is stored in X[2i] and the right child, if any, in X[2i+1]. To be able to store any
binary tree on n vertices the minimum size of X should be. (GATE - 2006) (2 Marks)
[Asked in Hexaware 2020]
(A) log2n (B) n (C) 2n + 1 (D) 2n — 1
www.knowledgegate.in
www.knowledgegate.in
Q Let LASTPOST, LASTIN and LASTPRE denote the last vertex visited in a post order,
inorder and preorder traversal, respectively, of a complete binary tree. Which of
the following is always true? (GATE - 2000) (1 Marks)
(A) LASTIN = LASTPOST (B) LASTIN = LASTPRE
www.knowledgegate.in
www.knowledgegate.in
Heap
• Suppose H is a complete binary tree with n elements, H is called a Heap, if each node N of H
has following properties:
• The value of N is greater than to the value at each of the children of N then it is called
Max heap.
• A min heap is defined as the value at N is less than the value at any of the children of N.
www.knowledgegate.in
www.knowledgegate.in
Q A max-heap is a heap where the value of each parent is greater than or equal to the
values of its children. Which of the following is a max-heap? (GATE - 2011) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Consider a binary max-heap implemented using an array. Which one
of the following arrays represents a binary max-heap? (GATE - 2006)
(Marks)
(A) 23,17,14,6,13,10,1,12,7,5
(B) 23,17,14,6,13,10,1,5,7,12
(C) 23,17,14,7,13,10,1,5,6,12
(D) 23,17,14,7,13,10,1,12,5,7
www.knowledgegate.in
www.knowledgegate.in
Q Consider any array representation of an n element binary heap where
the elements are stored from index 1 to index n of the array. For the
element stored at index i of the array (i <= n), the index of the parent is
(GATE - 2001) (1 Marks) [Asked in Cognizant 2020]
(A) i – 1 (B) floor(i/2) (C) ceiling(i/2) (D) (i+1)/2
www.knowledgegate.in
www.knowledgegate.in
Q The number of possible min-heaps containing each value from {1, 2, 3,
4, 5, 6, 7} exactly once is _______. (Gate-2018) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q A complete binary min-heap is made by including each integer in [1, 1023] exactly once. The
depth of a node in the heap is the length of the path from the root of the heap to that node.
Thus, the root is at depth 0. The maximum depth at which integer 9 can appear is
_____________ (Gate-2016) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q The elements 32, 15, 20, 30, 12, 25, 16 are inserted one by one in the given
order into a Max Heap. The resultant Max Heap is. (GATE - 2004) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q The elements 32, 15, 20, 30, 12, 25, 16 are inserted one by one in the given
order into a Max Heap. The resultant Max Heap is. (GATE - 2004) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following array of elements. 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9,
100〉. The minimum number of interchanges needed to convert it into a max-heap
is (GATE - 2015) (2 Marks)
(A) 4 (B) 5 (C) 2 (D) 3
www.knowledgegate.in
www.knowledgegate.in
Q Consider a max heap, represented by the array: 40, 30, 20, 10, 15, 16, 17, 8, 4.
Now consider that a value 35 is inserted into this heap. After insertion, the new heap is (GATE -
2015) (2 Marks)
a) 40,30,20,10,15,16,17,8,4,35 b) 40,35,20,10,30,16,17,8,4,15
c) 40,30,20,10,35,16,17,8,4,15 d) 40,35,20,10,15,16,17,8,4,30
www.knowledgegate.in
www.knowledgegate.in
Q A priority queue is implemented as a Max-Heap. Initially, it has 5 elements. The
level-order traversal of the heap is: 10, 8, 5, 3, 2. Two new elements 1 and 7 are
inserted into the heap in that order. The level-order traversal of the heap after the
insertion of the elements is: (GATE - 2014) (2 Marks) [ Asked in Accenture]
www.knowledgegate.in
www.knowledgegate.in
Q Consider a binary max-heap implemented using an array. Which one of the
following arrays represents a binary max-heap? (GATE - 2009) (2 Marks)
(A) 25,12,16,13,10,8,14 (B) 25,12,16,13,10,8,14
www.knowledgegate.in
www.knowledgegate.in
Q What is the content of the array after two delete operations on the
correct answer to the previous question? (GATE - 2009) (2 Marks)
(A) 14,13,12,10,8 (B) 14,12,13,8,10
www.knowledgegate.in
www.knowledgegate.in
Q Consider a rooted Binary tree represented using pointers. The best upper bound
on the time required to determine the number of subtrees having exactly 4 nodes
O(na Logn b). Then the value of a + 10b is ________ (GATE-2015) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Let T be a full binary tree with 8 leaves. (A full binary tree has every level full.) Suppose two
leaves a and b of T are chosen uniformly and independently at random. The expected value of
the distance between a and b in T (ie., the number of edges in the unique path between a and b)
is (rounded off to 2 decimal places) _________. (GATE-2019) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q In a heap with n elements with the smallest element at the root, the
7th smallest element can be found in time (GATE - 2008) (1 Marks)
a) (n log n) b) (n) c) (log n) d) (1)
www.knowledgegate.in
www.knowledgegate.in
Q In a binary max heap containing n numbers, the smallest element can
be found in time (GATE - 2006) (1 Marks)
(A) 0(n) (B) O(logn) (C) 0(loglogn) (D) 0(1)
www.knowledgegate.in
www.knowledgegate.in
Q A data structure is required for storing a set of integers such that each of the
following operations can be done in O(logn) time, where n is the number of
elements in the set.
I) Deletion of the smallest element
II) Insertion of an element if it is not already present in the set
Which of the following data structures can be used for this purpose? (GATE - 2003)
(2 Marks)
a) A heap can be used but not a balanced binary search tree
b) A balanced binary search tree can be used but not a heap
c) Both balanced binary search tree and heap can be used
d) Neither balanced search tree nor heap can be used
www.knowledgegate.in
www.knowledgegate.in
Q We are given a set of n distinct elements and an unlabeled binary tree with n
nodes. In how many ways can we populate the tree with the given set so that it
becomes a binary search tree? (GATE - 2011) (2 Marks) [Asked in Capgemini 2016]
(A) 0 (B) 1 (C) n! (D) (1/(n+1)).2nCn
www.knowledgegate.in
www.knowledgegate.in
Q The maximum number of binary trees that can be formed with three
unlabelled nodes is: (GATE-2007) (1 Marks)
a) 1 b) 5 c) 4 d) 3
www.knowledgegate.in
www.knowledgegate.in
Q How many distinct binary search trees can be created out of 4 distinct
keys?
(A) 4 (B) 14 (C) 24 (D) 42
www.knowledgegate.in
www.knowledgegate.in
Q how many distinct BST can be constructed with 3 distinct
keys?
a) 4 b) 5 c) 6 d) 9
www.knowledgegate.in
www.knowledgegate.in
Q A complete n-ary tree is a tree in which each node has n children or no children.
Let I be the number of internal nodes and L be the number of leaves in a complete
n-ary tree. If L = 41, and I = 10, what is the value of n? (GATE - 2007) (2 Marks)
(A) 3 (B) 4 (C) 5 (D) 6
www.knowledgegate.in
www.knowledgegate.in
Q The number of leaf nodes in a rooted tree of n nodes, with each node
having 0 or 3 children is: (GATE - 2002) (2 Marks) [Asked in E-litmus 2018 ]
a) n/2 b) (n−1)/3 c) (n−1)/2 d) (2n+1)/3
www.knowledgegate.in
www.knowledgegate.in
Q A complete n-ary tree is one in which every node has 0 or n sons. If x is the
number of internal nodes of a complete n-ary tree, the number of leaves in it is
given by (GATE - 1998) (2 Marks)
a) x(n−1)+1 b) xn−1 c) xn+1 d) x(n+1)
www.knowledgegate.in
www.knowledgegate.in
Q In a complete k-ary tree, every internal node(n) has exactly k children
or no child. The number of leaves in such a tree with an internal node is:
(A) n.k (B) (n – 1) k+ 1
(C) n (k – 1) + 1 (D) n (k – 1)
www.knowledgegate.in
www.knowledgegate.in
Q A binary tree T has 20 leaves. The number of nodes in T having two
children is ______. (GATE - 2015) (1 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q In a binary tree, the number of internal nodes of degree 1 is 5, and the number
of internal nodes of degree 2 is 10. The number of leaf nodes in the binary tree is
(GATE - 2006) (1 Marks)
a) 10 b) 11 c) 12 d) 15
www.knowledgegate.in
www.knowledgegate.in
Q A binary tree T has n leaf nodes. The number of nodes of
degree 2 in T is (GATE-1995) (1 Marks)
a) log2n b) n−1 c) n d) 2n
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following nested representation of binary
trees: (X Y Z) indicates Y and Z are the left and right subtrees, respectively, of node X. Note
that Y and Z may be NULL, or further nested. Which of the following represents a valid
binary tree? (GATE - 2000) (1 Marks)
a) (1 2 (4 5 6 7)) b) (1 (2 3 4) 5 6) 7)
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following statements is false? (GATE - 1998) (1 Marks)
a) A tree with a n nodes has (n–1) edges
b) A labeled rooted binary tree can be uniquely constructed given its post order
and preorder traversal results.
c) A complete binary tree with n internal nodes has (n+1) leaves.
d) The maximum number of nodes in a binary tree of height h is 2h+1−1
www.knowledgegate.in
www.knowledgegate.in
Q Let H be a binary min-heap consisting of n elements implemented as an array.
What is the worst case time complexity of an optimal algorithm to find the
maximum element in H? (GATE 2021) (1 MARKS)
(A) Θ(1)
(B) Θ(logn)
(C) Θ(n)
(D) Θ(nlogn)
www.knowledgegate.in
www.knowledgegate.in
Graph
• Graph is a data structure that consists of following two components:
• A finite set of vertices also called as nodes.
• A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u,
v) is not same as (v, u) in case of a directed graph(di-graph).
• The pair of the form (u, v) indicates that there is an edge from vertex u to vertex v. The
edges may contain weight/value/cost.
www.knowledgegate.in
www.knowledgegate.in
• Graphs are used to represent many real-life applications: Graphs are used to represent
networks. The networks may include paths in a city or telephone network or circuit network.
• Graphs are also used in social networks like LinkedIn, Facebook. For example, in Facebook,
each person is represented with a vertex (or node). Each node is a structure and contains
information like person id, name, gender and locale.
www.knowledgegate.in
www.knowledgegate.in
Representation of Graph in Memory
• Following two are the most commonly used representations of a graph.
• Adjacency Matrix
• Adjacency List
• There are other representations also like, Incidence Matrix and Incidence List.
The choice of the graph representation is situation specific. It totally depends on
the type of operations to be performed and ease of use.
www.knowledgegate.in
www.knowledgegate.in
• Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of
vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge
from vertex i to vertex j.
• Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an
edge from vertex i to vertex j with weight w.
www.knowledgegate.in
www.knowledgegate.in
• Pros: Representation is easier to implement and follow. Removing an edge takes
O(1) time. Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are
efficient and can be done O(1).
• Cons: Consumes more space O(V2). Even if the graph is sparse(contains less
number of edges), it consumes the same space. Adding a vertex is O(V 2) time.
www.knowledgegate.in
www.knowledgegate.in
Q Which of the properties hold for the adjacency matrix A of a simple undirected unweighted graph
having n vertices? (GATE 2022) (2 MARKS)
(A) The diagonal entries of A2 are the degrees of the vertices of the graph.
(B) If the graph is connected, then none of the entries of A n-1 + In can be zero.
(C) If the sum of all the elements of A is at most 2(n-1), then the graph must be acyclic.
(D) If there is at least a 1 in each of A ’s rows and columns, then the graph must be connected.
www.knowledgegate.in
www.knowledgegate.in
Q Consider a simple undirected unweighted graph with at least three vertices. If A
is the adjacency matrix of the graph, then the number of 3-cycles in the graph is
given by the trace of (GATE 2022) (2 MARKS)
(a) A3
(b) A3 divided by 2
(c) A3 divided by 3
(d) A3 divided by 6
www.knowledgegate.in
www.knowledgegate.in
• Adjacency List: An array of lists is used. Size of the array is equal to the number of vertices. Let
the array be array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex.
This representation can also be used to represent a weighted graph. The weights of edges can
be represented as lists of pairs.
www.knowledgegate.in
www.knowledgegate.in
Graph Traversal
• Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree.
• The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same
node again. To avoid processing a node more than once, we use a Boolean visited array.
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following are valid and invalid DFS traversal sequence
a) 1, 3, 7, 8, 5, 2, 4, 6 b) 1, 2, 5, 8, 6, 3, 7, 4
c) 1, 3, 6, 7, 8, 5, 2, 4 d) 1, 2, 4, 5, 8, 6, 7, 3
www.knowledgegate.in
www.knowledgegate.in
• A standard DFS implementation puts each vertex of the graph into one of two
categories:
• Visited
• Not Visited
• The purpose of the algorithm is to mark each vertex as visited while avoiding
cycles.
www.knowledgegate.in
www.knowledgegate.in
• The DFS algorithm works as follows:
• Start by putting any one of the graph's vertices on top of a stack.
• Take the top item of the stack and add it to the visited list.
• Create a list of that vertex's adjacent nodes. Add the ones which aren't in the
visited list to the top of stack.
• Keep repeating steps 2 and 3 until the stack is empty.
www.knowledgegate.in
www.knowledgegate.in
DFS(v)
{
visited(v) = 1
For all x adjacent to v
{
if (x is not visited)
DFS(x)
}
}
www.knowledgegate.in
www.knowledgegate.in
theoretical computer science, DFS is typically used to traverse an entire graph,
and takes time O(|V|+|E|), where |V|is the number of vertices and |E| the
number of edges.
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
DFS-iterative (G, s)
{
let S be stack
Push( s )
while ( S is not empty)
{
v = pop(S)
if v is not marked as visited
{
mark v as visited
for all neighbors w of v in Graph G:
{
if w is not marked as visited:
push( w )
}
}
}
}
www.knowledgegate.in
www.knowledgegate.in
Q Consider the following sequence of nodes for the undirected graph given below.
1) a b e f d g c 2) a b e f c g d 3) a d g e b c f 4) a d b c g e f
A Depth First Search (DFS) is started at node a. The nodes are listed in the order they are first
visited. Which all of the above is (are) possible output(s)? (Gate-2008) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Suppose depth first search is executed on the graph below starting at some unknown
vertex. Assume that a recursive call to visit a vertex is made only after first checking that
the vertex has not been visited earlier. Then the maximum possible recursion depth
(including the initial call) is _________. (Gate-2014) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Let G be a graph with n vertices and m edges. What is the tightest upper bound
on the running time on Depth First Search of G? Assume that the graph is
represented using adjacency matrix.(Gate-2014) (1 Marks)
(A) O(n) (B) O(m+n) (C) O(n2) (D) O(mn)
www.knowledgegate.in
www.knowledgegate.in
Q Let T be a depth first search tree in an undirected graph G. Vertices u and v are leaves of this
tree T. The degrees of both u and v in G are at least 2. which one of the following statements is
true? (Gate-2006) (2 Marks)
(A) There must exist a vertex w adjacent to both u and v in G
(B) There must exist a vertex w whose removal disconnects u and v in G
(C) There must exist a cycle in G containing u and v
(D) There must exist a cycle in G containing u and all its neighbors in G.
www.knowledgegate.in
www.knowledgegate.in
Q Let G be an undirected graph. Consider a depth-first traversal of G, and let T be the resulting
depth-first search tree. Let u be a vertex in G and let v be the first new (unvisited) vertex visited
after visiting u in the traversal. Which of the following statements is always true? (GATE-2000) (2
Marks)
(A) {u,v} must be an edge in G, and u is a descendant of v in T
(B) {u,v} must be an edge in G, and v is a descendant of u in T
(C) If {u,v} is not an edge in G then u is a leaf in T
(D) If {u,v} is not an edge in G then u and v must have the same parent in T
www.knowledgegate.in
www.knowledgegate.in
(UGC - June – 2017)
www.knowledgegate.in
www.knowledgegate.in
Breadth First Traversal (or Search)
• Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal
of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we
may come to the same node again.
• To avoid processing a node more than once, we use a Boolean visited array. For
simplicity, it is assumed that all vertices are reachable from the starting vertex,
i.e. the graph is connected
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following are valid and invalid BFS traversal sequence
a) 1, 3, 2, 5, 4, 7, 6, 8 b) 1, 3, 2, 7, 6, 4, 5, 8
c) 1, 2, 3, 5, 4, 7, 6, 8 d) 1, 2, 3, 7, 5, 6, 4, 8
www.knowledgegate.in
www.knowledgegate.in
BFS(v)
{
visited(v) = 1
insert[V,Q]
While(Q != Phi)
{
u = Delete(Q);
for all x adjacent to u
{
if (x is not visited)
{
visited(x) = 1
insert(x,Q)
}
}
}
}
www.knowledgegate.in
www.knowledgegate.in
The time complexity can be expressed as O(|V|+|E|), since every vertex
and every edge will be explored in the worst case. |V| is the number of
vertices and |E| is the number of edges in the graph. Note that
O(|E|)may vary between O(1) and O(|V|2).
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
www.knowledgegate.in
Q Breath First Search (BFS) has been implemented using queue data structure.
Which one of the following is a possible order of visiting the nodes in the graph
above? (Gate-2017) (1 Marks)
a) MNOPQR b) NQMPOR c) QMNROP d) POQNMR
www.knowledgegate.in
www.knowledgegate.in
Q The Breadth First Search algorithm has been implemented using the queue data
structure. One possible order of visiting the nodes of the following graph is (Gate-
2008) (1 Marks)
(A) MNOPQR (B) NQMPOR (C) QMNPRO (D) QMNPOR
www.knowledgegate.in
www.knowledgegate.in
Q An articulation point in a connected graph is a vertex such that removing the vertex and its incident
edges disconnects the graph into two or more connected components. Let T be a DFS tree obtained by
doing DFS in a connected undirected graph G. Which of the following options is/are correct? (GATE 2021)
(2 MARKS)
(a) Root of T can never be an articulation point in G.
www.knowledgegate.in
www.knowledgegate.in
Q Consider a complete binary tree with 7 nodes. Let A denote the set of first 3
elements obtained by performing Breadth-First Search (BFS) starting from the root.
Let B denote the set of first 3 elements obtained by performing Depth-First Search
(DFS) starting from the root. The value of ∣A−B∣ is _____________ . (Gate-2021)
(2 Marks) [Asked in Accenture 2022]
a) 1
b) 2
c) 3
d) 4
www.knowledgegate.in
www.knowledgegate.in
Q Breadth First Search (BFS) is started on a binary tree beginning from the root vertex.
There is a vertex t at a distance four from the root. If t is the n-th vertex in this BFS
traversal, then the maximum possible value of n is ________ (Gate-2016) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Let G = (V, E) be a simple undirected graph, and s be a particular vertex in it called the source.
For x ∈ V, let d(x) denote the shortest distance in G from s to x. A breadth first search (BFS) is
performed starting at s. Let T be the resultant BFS tree. If (u, v) is an edge of G that is not in T,
then which one of the following CANNOT be the value of d(u) – d(v)? (Gate-2015)(2 Marks)
(A) -1 (B) 0 (C) 1 (D) 2
www.knowledgegate.in
www.knowledgegate.in
Q Consider the tree arcs of a BFS traversal from a source node W in an unweighted, connected,
undirected graph. The tree T formed by the tree arcs is a data structure for computing. (Gate-
2014) (2 Marks)
a) the shortest path between every pair of vertices.
b) the shortest path from W to every vertex in the graph.
c) the shortest paths from W to only those nodes that are leaves of T.
d) the longest path in the graph
www.knowledgegate.in
www.knowledgegate.in
Q Level order traversal of a rooted tree can be done by starting from the root and
performing (Gate-2004) (1 Marks)
(A) preorder traversal (B) inorder traversal
(C) depth first search (D) breadth first search
www.knowledgegate.in
www.knowledgegate.in
Q Consider an undirected unweighted graph G. Let a breadth-first traversal of G be done starting from a node r. Let
d(r, u) and d(r, v) be the lengths of the shortest paths from r to u and v respectively, in G. lf u is visited before v
during the breadth-first traversal, which of the following statements is correct? (GATE-2001) (2 Marks)
(A) d(r, u) < d (r, v) (B) d(r, u) > d(r, v) (C) d(r, u) <= d (r, v) (D) None of the above
www.knowledgegate.in
www.knowledgegate.in
Q The most efficient algorithm for finding the number of connected components in
an undirected graph on n vertices and m edges has time complexity. (Gate-2008)(1
Marks)
a) O(n) b) O(m) c) O(m+n) d) O(m.n)
www.knowledgegate.in
www.knowledgegate.in
Q In an adjacency list representation of an undirected simple graph G = (V, E), each edge (u, v)
has two adjacency list entries: [v] in the adjacency list of u, and [u] in the adjacency list of v.
These are called twins of each other. A twin pointer is a pointer from an adjacency list entry to its
twin. If |E| = m and |V | = n, and the memory size is not a constraint, what is the time
complexity of the most efficient algorithm to set the twin pointer in each entry in each adjacency
list?(Gate-2016) (2 Marks)
(A) Θ(n2)
(B) Θ(m+n)
(C) Θ(m2)
(D) Θ(n4)
www.knowledgegate.in
www.knowledgegate.in
Introduction to hashing
• The main objective of a data structure is to efficiently store data, but the most frequent
operation on any data structure is search. Even for insertion and deletion, searching is
required as a preliminary step.
• Search time in a data structure primarily depends on the number of elements and the
structure type:
• Unsorted Array: O(n)
• Sorted Array: O(log n)
• Linked List: O(n)
• Binary Tree (BT): O(n)
• Binary Search Tree (BST): O(n) in worst case
• AVL Tree: O(log n)
• Hashing optimizes search operations by providing constant time complexity for lookups in the
average case — making it a powerful tool for managing and accessing data.
www.knowledgegate.in
www.knowledgegate.in
• Hashing is a technique where the search time is independent of the number of items. The
main idea is to use a key value (like phone numbers, Aadhar card, roll numbers, etc.) to
directly find the address in memory, making the search process fast and efficient.
• Hash Function: Converts a large key into a smaller number that serves as an index in the hash
table. This transformation is represented as: H: K → L where K is the set of keys and L is the
set of memory locations.
• Hash Table:
• A special data structure where the keys are used to calculate the index, storing values at
these indexes. Unused entries are set to nil or empty pointers.
www.knowledgegate.in
www.knowledgegate.in
Q Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and
the hash function x mod 10, which of the following statements are true? (Gate-
2004) (1 Marks)
i. 9679, 1989, 4199 hash to the same value
ii. 1471, 6171 has to the same value
iii. All elements hash to the same value
iv. Each element hashes to a different value
(A) i only (B) ii only (C) i and ii only (D) iii or iv
www.knowledgegate.in
www.knowledgegate.in
• Collision: - It is possible that two different set of keys K1 and K2 will yield the
same hash address. This situation is called collision. The technique to resolve
collision is called collision resolution.
• Note: Irrespective of how good a hash function is, collisions are bound to occur.
Therefore, to maintain the performance of a hash table, it is important to
manage collisions through various collision resolution techniques.
• Characteristics of good hash function
• Easy to compute and understand
• Efficiently computable- It must take less time to compute
• Should uniformly distribute the keys (Each table position equally likely for
each key) and should not result in clustering.
• Must have low collision rate
www.knowledgegate.in
www.knowledgegate.in
Most popular hash function
• Division-remainder method: The size of the number of items in the table is estimated. That
number is then used as a divisor into each original value or key to extract a quotient and a
remainder.
• The remainder is the hashed value. (Since this method is liable to produce a number of
collisions, any search mechanism would have to be able to recognize a collision and offer an
alternate search mechanism.)
• H(K) = K(mod m)
• H(K) = K(mod m) + 1
www.knowledgegate.in
www.knowledgegate.in
Q Which of the following statement(s) is/are TRUE? (Gate-2006) (1 Marks)
I. A hash function takes a message of arbitrary length and generates a fixed-length code.
II. A hash function takes a message of fixed length and generates a code of variable
length.
III. A hash function may give the same hash value for distinct messages.
(a) I only (b) II and III only (c) I and III only (d) II only
www.knowledgegate.in
www.knowledgegate.in
Collision resolution technique
• Open Addressing/closed hashing - In Open Addressing, all elements are stored in the hash
table itself. i.e. collision is resolved by probing or searching through alternate locations in the
Hash table itself in a particular sequence.
• When searching for an element, we one by one examine table slots until the desired element
is found or it is clear that the element is not in the table. So, at any point, size of table must be
greater than or equal to total number of keys.
• It is of three types linear probing, quadratic probing, double hashing
www.knowledgegate.in
www.knowledgegate.in
Linear probing
• Linear Probing is a collision resolution technique in which the hash table is searched sequentially
starting from the position given by the hash function until a matching key or an empty slot is found.
Using linear probing, insert, remove and search operations can be implemented in O(1), as long as
the load factor of the hash table is a constant strictly less than one.
• Insert(k): Keep probing until an empty slot is found. Once an empty slot is found, insert k.
• Search(k): Keep probing until slot’s key doesn’t become equal to k or an empty slot is reached.
• Delete(k): Delete operation is interesting. If we simply delete a key, then search may fail. So slots
of deleted keys are marked specially as “deleted”. Insert can insert an item in a deleted slot, but
search doesn’t stop at a deleted slot.
• In Linear Probing, the position for a key k is calculated using the following hash function:
• h(k,i)=(h′(k)+i)mod Where:
• h′(k) is the primary hash function applied to the key k.
• i is the probe number, ranging from 0 to m−1.
• m is the size of the hash table.
www.knowledgegate.in
www.knowledgegate.in
Q A hash table contains 10 buckets and uses linear probing to resolve collision. The
key values are integers and the hash function used is key%10, if the values 43 165
62 123 142 are inserted in the table, in what location would the key value 142 be
inserted? (Gate-2005) (1 Marks)
A) 2 b) 3 c) 4 d) 6
www.knowledgegate.in
www.knowledgegate.in
Q The keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted into an initially empty hash
table of length 10 using open addressing with hash function h(k) = k mod 10 and
linear probing. What is the resultant hash table? (Gate-2009) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
Q consider a hash table of size 11 that uses open addressing with linear probing. Let h(k)=
k mod 11 be the hash function used. A sequence of records with keys 43 36 92 87 11 4 71
13 14 is inserted into an initially empty hash table, indexing is from 0, what is the index of
the bin into which the last record is inserted? (Gate-2008) (2 Marks)
a) 3 b) 4 c) 6 d) 7
www.knowledgegate.in
www.knowledgegate.in
Q Consider a hash table of size seven, with starting index zero, and a hash function (3x + 4)mod7.
Assuming the hash table is initially empty, which of the following is the contents of the table
when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing? Note that ‘_’
denotes an empty location in the table. (Gate-2007) (2 Marks)
(A) 8, _, _, _, _, _, 10 (B) 1, 8, 10, _, _, _, 3
(C) 1, _, _, _, _, _,3 (D) 1, 10, 8, _, _, _, 3
www.knowledgegate.in
www.knowledgegate.in
Q A hash table of length 10 uses open addressing with hash function h(k)=k mod 10, and
linear probing. After inserting 6 values into an empty hash table, the table is as shown
below. Which one of the following choices gives a possible order in
which the key values could have been inserted in the table?
(Gate-2010) (2 Marks)
(A) 46, 42, 34, 52, 23, 33
www.knowledgegate.in
www.knowledgegate.in
Q A hash table with ten buckets with one slot per bucket is shown in the following figure.
The symbols S1 to S7 initially entered using a hashing function with linear probing. The
maximum number of comparisons needed in searching an item that is not present is
(Gate-1989) (2 Marks)
www.knowledgegate.in
www.knowledgegate.in
• Advantages:
• Fast and Simple: Easy to implement and has good locality of reference.
• Efficient on Standard Hardware: Performs well due to sequential memory
access.
• Disadvantages:
• Primary Clustering Issue: Collisions can lead to long probe sequences.
• Sensitive to Hash Function: Requires a high-quality hash function to avoid
performance degradation.
www.knowledgegate.in
www.knowledgegate.in
Q Which among the following statement(s) is(are) true?
a) A hash function takes a message of arbitrary length and generates a fixed length code
b) A hash function takes a message of fixed length and generates a code of variable length
c) A hash function may give same hash value for distinct messages
Choose the correct answer from the options given below: (Gate-2005) (1 Marks) (NET 2020 OCT)
www.knowledgegate.in
www.knowledgegate.in
• Primary Clustering:
• Occurs in linear probing when collisions cause keys to form a contiguous cluster.
• Each new key hashed into the cluster makes it grow, leading to longer probe sequences.
• Secondary Clustering:
• Happens when multiple keys hash to the same location and follow the same probe
sequence.
• Affects both linear and quadratic probing, caused by poor hash functions, leading to slow
access times.
www.knowledgegate.in
www.knowledgegate.in
Quadratic probing
• Definition: Quadratic probing resolves collisions by adding successive values of a quadratic
polynomial to the original hash index until an empty slot is found.
• Hash Function:
• h(k,i)=(h′(k)+f(i2))mod m
www.knowledgegate.in
www.knowledgegate.in
• Advantage
• Quadratic probing can be a more efficient algorithm in a closed hashing table, since it
better avoids the clustering problem that can occur with linear probing, although it is not
immune.
• It also provides good memory caching because it preserves some locality of reference;
however, linear probing has greater locality and, thus, better cache performance.
• Disadvantage
• Quadratic probing lies between the two in terms of cache performance and clustering.
www.knowledgegate.in
www.knowledgegate.in
• Performance of Open Addressing: Like Chaining, performance of hashing can be evaluated
under the assumption that each key is equally likely to be hashed to any slot of table (simple
uniform hashing)
• m = Number of slots in hash table
• n = Number of keys to be inserted in hash table
• Load factor α = n/m (< 1)
• Expected time to search/insert/delete < 1/(1 - α)
• So Search, Insert and Delete take (1/(1 - α)) time
www.knowledgegate.in
www.knowledgegate.in
Q Given a hash table T with 25 slots that stores 2000 elements, the load factor α
for T is __________ (Gate-2015) (1 Marks)
(A) 80 (B) 0.0125 (C) 8000 (D) 1.25
www.knowledgegate.in
www.knowledgegate.in
Q Consider a hash function that distributes keys uniformly. The hash table size is
20. After hashing of how many keys will the probability that any new key hashed
collides with an existing one exceed 0.5. (Gate-2007) (2 Marks)
(A) 5 (B) 6 (C) 7 (D) 10
www.knowledgegate.in
www.knowledgegate.in
Chaining
• The idea is to make each cell of hash table point to a linked list of records that
have same hash function value. In chaining, we place all the elements that hash
to the same slot into the same linked list.
• Advantage: - Chaining is simple
• Disadvantage: -but requires additional memory outside the table.
www.knowledgegate.in
www.knowledgegate.in
S.N Separate Chaining Open Addressing
o.
1. Chaining is Simpler to implement. Open Addressing requires more computation.
2. In chaining, Hash table never fills up, we can In open addressing, table may become full.
always add more elements to chain.
3. Chaining is Less sensitive to the hash function Open addressing requires extra care for to avoid
or load factors. clustering and load factor.
4. Chaining is mostly used when it is unknown Open addressing is used when the frequency and
how many and how frequently keys may be number of keys is known.
inserted or deleted.
5. Cache performance of chaining is not good as Open addressing provides better cache performance
keys are stored using linked list. as everything is stored in the same table.
6. Wastage of Space (Some Parts of hash table in In Open addressing, a slot can be used even if an
chaining are never used). input doesn’t map to it.
7. Chaining uses extra space for links. No links in Open addressing
www.knowledgegate.in
www.knowledgegate.in
Q An advantage of chained hash table (external hashing) over the open
addressing scheme is (Gate-1996) (1 Marks)
(A) Worst case complexity of search operations is less
www.knowledgegate.in
www.knowledgegate.in
Q Consider a hash table with 9 slots. The hash function is ℎ(k) = k mod 9. The collisions
are resolved by chaining. The following 9 keys are inserted in the order: 5, 28, 19, 15, 20,
33, 12, 17, 10. The maximum, minimum, and average chain lengths in the hash table,
respectively, are (Gate-2014) (2-Marks) [ Asked in Accenture]
www.knowledgegate.in
www.knowledgegate.in
Q Consider a hash table with 100 slots. Collisions are resolved using chaining.
Assuming simple uniform hashing, what is the probability that the first 3 slots are
unfilled after the first 3 insertions? (Gate-2014) (2 Marks)
(A) (97 × 97 × 97)/1003 (B) (99 × 98 × 97)/1003
(C) (97 × 96 × 95)/1003 (D) (97 × 96 × 95)/(3! × 1003)
www.knowledgegate.in
www.knowledgegate.in
Double Hashing
• Definition: Double hashing is a collision resolution technique that uses a second hash
function to determine the interval for probing, ensuring that consecutive elements use
different probe sequences.
• Hash Function:
• h(i,k)=(h1(k)+i⋅h2(k))mod |T|
• h1(k) and h2(k) are two independent hash functions.
• i is the probe number.
• ∣T∣ is the size of the hash table.
• Key Advantages:
• Reduces clustering more effectively than linear or quadratic probing.
• Provides near-random distribution, minimizing collisions and improving search efficiency.
www.knowledgegate.in
www.knowledgegate.in
Q Consider a double hashing scheme in which the primary hash function is h 1(k) = k mod 23, and
the secondary hash function is h2(k) = 1+(k mod 19). Assume that the table size is 23. Then the
address returned by probe 1 in the probe sequence (assume that the probe sequence begins at
probe 0) for key value k = 90 is ________ .? (Gate-2020) (2-Marks)
www.knowledgegate.in
www.knowledgegate.in
Q Suppose we are given n keys, m hash table slots, and two simple uniform hash
functions h1 and h2 . Further suppose our hashing scheme uses h1 for the odd keys and h2
for the even keys. What is the expected number of keys in a slot? (GATE 2022) (1 MARKS)
(A) m/n
(B) n/m
(C) 2n/m
(D) n/2m
www.knowledgegate.in
www.knowledgegate.in
Q Consider a dynamic hashing approach for 4-bit integer keys:
(A) There is a main hash table of size 4.
(B) The 2 least significant bits of a key is used to index into the main hash table.
(C) Initially, the main hash table entries are empty.
(D) Thereafter, when more keys are hashed into it, to resolve collisions, the set of all
keys corresponding to a main hash table entry is organized as a binary tree that grows on demand.
(E) First, the 3rd least significant bit is used to divide the keys into left and right subtrees.
(F) To resolve more collisions, each node of the binary tree is further sub-divided into left and right subtrees based on the 4th
least significant bit.
(G) A split is done only if it is needed, i.e., only when there is a collision.
Consider the following state of the hash table. Which of the following sequences of key insertions can cause the above state of
the hash table (assume the keys are in decimal notation)? (GATE 2021) (2 MARKS)
(A) 5,9,4,13,10,7
(B) 9,5,10,6,7,1
(C) 10,9,6,7,5,13
(D) 9,5,13,6,10,14
www.knowledgegate.in
www.knowledgegate.in
Q Which one of the following hash functions on integers will distribute
keys most uniformly over 10 buckets numbered 0 to 9 for i ranging from
0 to 2020? (Gate-2015) (2-Marks)
(A) h(i) =i2 mod 10 (B) h(i) =i3 mod 10
(C) h(i) = (11 ∗ i2) mod 10 (D) h(i) = (12 ∗ i) mod 10
www.knowledgegate.in
www.knowledgegate.in