DS Sanchit Sir Notes
DS Sanchit Sir Notes
DS Sanchit Sir Notes
• An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value, i.e., the memory location of the
first element of the array (generally denoted by the name of the array).
• Each element can be uniquely identified by their index in the array (in a similar way as you
could identify your friends by the step on which they were on in the above example).
• Size of an array
o Number of elements = (Upper bound – Lower Bound) + 1
o Size = number of elements * Size of each elements in bytes
▪ Lower bound index of the first element of the array
▪ Upper bound index of the last element of the array
One Dimensional array
o Address of the element at kth index
o a[k] = B + W*k
o 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
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] ?
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)
(A) An array of 50 numbers (B) An array of 100 numbers
(C) An array of 500 numbers (D) A dynamically allocated array of 550 numbers
Answer: (A)
Two-Dimensional array
• The two-dimensional array can be defined as an array of arrays. The 2D array is organized
as matrices which can be represented as the collection of rows and columns. However, 2D
arrays are created to implement a relational database lookalike data structure. It provides
ease of holding the bulk of data at once which can be passed to any number of functions
wherever required.
• data_type array_name[rows][columns];
int disp[2][4] = {
};
OR
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Row Major 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.
• 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.
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?
Ans: a
N-Dimensional array
N-Dimensional array
A([L1]---[U1]), ([L2]---[U2]), ([L3]---[U3]), ([L4]---[U4])--------([LN]---[UN])
Location of A [I, j, k, ----, x] =
B + (i-L1) (U2-L2+1) (U3-L3+1) (U4-L4+1) ----(Un-Ln+1)
+ (j-L2)(U3-L3+1) (U4-L4+1) ----(Un-Ln+1)
+(k-L3)(U4-L4+1) ----(Un-Ln+1)
+
+
+
+( x-Ln)
Ans: c
Ans: a
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)
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]);
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
Answer: (B)
0 1 2 3 4 5 6 7 8 9
00 10 11 20 21 22 30 31 32 33
0 1 2 3 4 5 6 7 8 9
00 10 20 30 11 21 31 22 32 33
= B + no of element present in (j-L2) + no of element present in the
current column before us
= B + n + n-1 + n-2 + ----- + n-(j-1) + (i-j)
= B + nj – (1+2+3----+j-1) + (i-j)
= B + nj – (j)(j-1)/2 + (i-j)
A[i][j] = A[j][i]
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 M1 × M2 will be (Gate-2004) (2 Marks)
(A) best if A is in row-major, and B is in column- major order
(B) best if both are in row-major order
(C) best if both are in column-major order
(D) independent of the storage scheme
Answer: (D)
STACK
• A stack is a non-primitive linear data structure. it is an ordered list in which addition of a
new data item and deletion of already existing data item is done from only one end known
as top of stack (TOS).
• The element which is added in last will be first to be removed and the element which is
inserted first will be removed in last.
• That is why it is called last in first out (LIFO) or first in last out (FILO) type of list.
• Most frequently accessible element in the stack is the top most element, whereas the least
accessible element is the bottom of the stack.
Stack Implementation
• Stack is generally implemented in two ways.
• Static Implementation: - Here array is used to create stack. it is a simple technique but is
not a flexible way of creation, as the size of stack has to be declared during program design,
after that size implementation is not efficient with respect to memory utilization.
• Dynamic implementation: - It is also called linked list representation and uses pointer to
implement the stack type of data structure.
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
Answer: (B)
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.
TOP = TOP + 1
S[TOP] = x
exit
}
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.
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 (top 1< top 2) 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)
(A) (top1 = MAXSIZE/2) and (top2 = MAXSIZE/2+1)
(B) top1 + top2 = MAXSIZE
(C) (top1= MAXSIZE/2) or (top2 = MAXSIZE)
(D) top1= top2 -1
Answer: (D)
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 (C) n(X + Y)-X (D) Y + 2X
Answer: (C)
Application of Stack
Q Which one of the following is an application of Stack Data Structure?
(A) Managing function call (B) recursion
(C) Arithmetic expression evaluation (D) All of the above
Answer: (D)
Stack Permutation
Q if the input sequence is 1, 2, 3, 4, 5 then identify the wrong stack permutation (possible pop
sequence)?
a) 3, 5, 4, 2, 1 b) 2, 4, 3, 5, 1 c) 4, 3, 5, 2, 1 d) 5, 4, 3, 1, 2
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
b
Evaluation of arithmetic expression
• An expression is defined as a number of operands or data items combined using several
operators. There are basically three of notation to represent an expression.
• Infix notation: the operator is written in between the operands. e.g. A+B. the reason why
this notation is called infix is the place of operator in the expression.
• Prefix notation: In which the operator is written before the operands it is also called as
polish notation. e.g. +AB
• Postfix: In the postfix notation the operator are written after the operands, so it is called
the postfix notation. It is also known as suffix notation or recursive polish notation. AB+
• Postfix notation is type of notation which is most suitable for a computer to calculate any
expression. It is universally accepted notation for designing arithmetic and logical unit
(ALU) of the CPU.
• Any expression entered into the computer is first converted into postfix notation, stored in
stack and then calculated.
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) abc × + def ^ ^ – (B) abc × + de ^ f ^ –
(C) ab + c × d – e ^ f ^ (D) – + a × bc ^ ^ def
Answer: (A)
Q Consider an expression log(x!), convert it into both prefix and post fix notation?
Q The following postfix expression with single digit operands is evaluated using a stack 8 2 3 ^
/23*+51*-
Note that ^ is the exponentiation operator. The top two elements of the stack after the first *
is evaluated are: (GATE - 2007) (2 Marks)
(A) 6, 1 (B) 5, 7 (C) 3, 2 (D) 1, 5
Answer: (A)
Q To evaluate an expression without any embedded function calls: (GATE - 2002) (1 Marks)
(A) One stack is enough
(B) Two stacks are needed
(C) As many stacks as the height of the expression tree are needed
(D) A Turing machine is needed in the general case
Answer: (A)
Void fun(int x)
{
if (x > 0)
{
Printf(“%d”, x);
fun(x - 1);
}
}
Q Find the output of the following pseudo code?
Void main()
{
salman(3);
}
Void salman(int x)
{
if (x > 0)
{
Salman(x-1);
Printf(“%d”, x);
Salman(x - 1);
}
}
Tower of hanoi: suppose there are three pegs lablled as A, B and C and suppose on peg A
there are placed a finite number n of disks with decreasing size. the object of the game is to
move the disks from peg A to peg C using peg B as an auxiliary.
Rules:
only one disk may be moved at a time specially only the top disk on any peg may be involved
to any other peg
at no time can a larger disk be placed on smaller disk.
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
}
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?
(A) Prints binary representation of n in reverse order
(B) Prints binary representation of n
(C) Prints the value of Logn
(D) Prints the value of Logn in reverse order
Answer: (B)
if (n == 0)
return;
printf("%d", n%2);
fun(n/2);
}
(A) 11001 (B) 10011 (C) 11111 (D) 00000
Answer: (B)
Q Consider the following recursive function fun (x, y). What is the value of fun (4, 3)
#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
Answer: (C)
#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
Answer: (B)
int main()
{
printf("%d", f(11));
return 0;
}
(A) Stack Overflow (B) 3 (C) 4 (D) 5
Answer: (D)
Q Consider the following recursive C function. If get(6) function is being called in main() then
how many times will the get() function be invoked before returning to the main()? (GATE -
2015) (2 Marks)
void get (int n)
{
if (n < 1) return;
get(n-1);
get(n-3);
printf("%d", n);
}
(A) 15 (B) 25 (C) 35 (D) 45
Answer: (B)
}
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 (D) 2
Answer: (D)
{
if (y == 0)
return 0;
return (x + fun(x, y-1));
}
int main()
{
int n = 8;
print(n, 1);
(A) 1 7 2 6 3 5 4 4 4 4 (B) 1 7 2 6 3 5 4 4
(C) 1 7 2 6 3 5 (D) 1 2 3 4 5 6 7 8
Answer: (B)
Explanation: For a given number n, the program prints all distinct pairs of positive integers
with sum equal to n.
Q
#include<stdio.h>
void crazy(int n, int a, int b)
{
if (n <= 0)
return;
crazy(n-1, a, b+n);
printf("%d %d %d\n",n,a,b);
crazy(n-1, b, a+n);
}
int main()
{
crazy(3,4,5);
return 0;
}
Q What is the return value of following function for 484? What does it to in general?
bool fun(int n)
{
int sum = 0;
for (int odd = 1; n > sum; odd = odd+2)
sum = sum + odd;
return (n == sum);
}
(A) False, it checks whether a given number is power of 3
(B) False, it checks whether a given number is even or not
(C) False, it checks whether a given number is odd or not
(D) True, it checks whether a given number is perfect square.
Answer: (D)
Explanation: The given function adds all odd numbers 1, 3, 5, 7, 9, 11…. till the sum is smaller
than n. If the sum becomes equal to n, then it returns true. This is basically a test for perfect
square numbers. All perfect square numbers can be written as sum of odd numbers.
4=1+3
9 = 1 + 3 + 50
16 = 1 + 3 + 5 + 7
36 = 1 + 3 + 5 + 7 + 9
49 = 1 + 3 + 5 + 7 + 9 + 11
• In computer science queue are used in multiple places e.g. in time sharing system program
with the same priority from a queue waiting to be executed.
• A queue is a non-primitive linear data structure. it is homogeneous collection of elements.
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.
• The condition FRONT = null will indicate that the queue is empty. Whenever an element is
deleted from the queue, the value of FRONT is increased by 1
o Front = Front + 1
• Whenever an element is added to the queue, the value of REAR is increased by 1
o REAR = REAR + 1
• This means that after N insertion the rear element of the queue will occupy QUEUE[N] or
queue will occupy the last part of the array. This may occur even though the queue itself
may not contain many elements.
• Total number of elements in a queue
o Rear – Front + 1
Insertion
Deletion
if (F == - 1)
Write under flow and exit
ITEM = QUEUE[F]
if (F = = R)
Set F = -1 && R = -1
Else
F=F+1
}
Circular Queue
Insertion
Deletion
Set F = -1 && R = -1
Else if (F = N-1)
Set F = 0
Else
F=F+1
Return item
}
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.
o An element of higher priority is processed before any element of lower priority
o Two element with the same priority are processed according to the order in which
they were added to the queue.
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)
(A) rear node (B) front node
(C) not possible with a single pointer (D) node next to front
Answer: (A)
Q Following is C like pseudo code of a function that takes a Queue as an argument, and uses a
stack S to do processing.
}
What does the above function do in general?
(A) Removes the last from Q (B) Keeps the Q same as it was before the call
(C) Makes Q empty (D) Reverses the Q
Answer: (D)
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.
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)
(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
Answer: (B)
Q How many stacks are needed to implement a queue. Consider the situation where no other
data structure like arrays, linked list is available to you.
(A) 1 (B) 2 (C) 3 (D) 4
Answer: (B)
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)
a) Θ(1), Θ(1) b) Θ(1), Θ(n) c) Θ(n), Θ(1) d) Θ(n), Θ(n)
ANSWER-B
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)
I. Next pointer of front node points to the rear node.
II. Next pointer of rear node points to the front node.
a) I only b) II only c) Both I and II d) Neither I nor II
ANSWER-B
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)
d) Worst case time complexity for both operations will be Ω(log n)
ANSWER-A
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
Ans: 256
void insert(Q, x)
{
void delete(Q)
{
if(stack-empty(S2)) then
if(stack-empty(S1)) then
{
print(“Q is empty”);
return;
}
x=pop(S2);
}
Let n insert and m (<=n) delete operations be performed in an arbitrary order on an empty
queue Let x and y be the number of push and pop operations performed respectively in the
process. Which one of the following is true for all m and n? (GATE-2006) (1 Marks)
(A) n+m <= x < 2n and 2m <= y <= n+m (B) n+m <= x < 2n and 2m<= y <= 2n
(C) 2m <= x < 2n and 2m <= y <= n+m (D) 2m <= x <2n and 2m <= y <= 2n
Answer: (A)
• A linked list is a linear collection of data elements called nodes, where the linear order is
given by the means of pointers.
• Each node is divided into two parts the first part is the information part of the node,
which contains data.
• The second part called linked field or next pointer field, contains the address of the next
node of the list.
• The pointer of the last node contains a null pointer, which is an invalid address (0 or
negative value).
• The linked also contains a list pointer variable called start/first/head which contain the
address of the first node in the list.
• A special case is the list that has no nodes, such a list is called null list or empty list and is
denoted by a null pointer in the variable start/first/head.
struct node {
int data;
};
Advantage of link list
• Slow access: - It does not allow direct search, supports only sequential search even if
link list is sorted. i.e. If we want to access a particular node then we have to start from
the first node.
• A good amount of space is wasted in storing pointers. For e.g. 4 bytes (on 32-bit CPU) to
store a reference to the next node.
Operation on link list
Traversing a link list means starting from the first node and read or process each node os the
list exactly once
Void main()
{
Traverse(*head, key)
}
Void main()
{
Traverse(*head, key)
}
Void main()
{
Traverse(*head, key )
}
Void main()
{
Traverse(*head, key )
}
Else
{
Return null;
}
}
Void main()
{
Insert(*head, int key)
}
Void main()
{
Insert(*head, int key, location)
}
Void main()
{
delete(*head)
}
Void main()
{
delete(*location);
}
Void main()
{
reverse(struct node* head)
}
}
(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
Answer: (B)
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)
(A) q = NULL; p->next = head; head = p; (B) q->next = NULL; head = p; p->next = head;
(C) head = p; p->next = q; q->next = NULL; (D) q->next = NULL; p->next = head; head = p;
Answer: (D)
{
int data;
struct item * next;
};
}
For a given linked list p, the function f returns 1 if and only if
(A) the list is empty or has exactly one element
(B) the elements in the list are sorted in non-decreasing order of data value
(C) the elements in the list are sorted in non-increasing order of data value
(D) not all elements in the list have the same data value.
Answer: (B)
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.
if(temp != NULL )
*head_ref = temp->prev;
}
Assume that reference of head of following doubly linked list is passed to above function
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. (D) 6 <--> 5 <--> 4 <--> 3 <--> 1 <--> 2
Answer: (C)
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)
(A) union only (B) intersection, membership
(C) membership, cardinality (D) union, intersection
Answer: (D)
Assuming that m and n point to valid NULL- terminated linked lists, invocation of join will
a) append list m to the end of list n for all inputs
b) either cause a null pointer dereference or append list m to the end of list n
c) cause a null pointer dereference for all inputs.
d) append list n to the end of list m for all inputs.
ANSWER- D
Q N items are stored in a sorted doubly linked list. For a delete operation, a pointer is provided
to the record to be deleted. For a decrease-key operation, a pointer is provided to the record
on which the operation is to be performed. An algorithm performs the following operations on
the list in this order: Θ(N) delete, O(log N) insert, O(log N) find, and Θ(N) decrease-key What is
the time complexity of all these operations put together (Gate-2016) (2 Marks)
ANSWER- C
a) (ii) and (iii) are true b) (i) and (ii) are true
c) (iii) and (iv) are true d) (ii) and (iv) are true
Ans: a
Header link list
• A header linked list is a linked list which always contains a special node, called head node at
the beginning of the list. This special node in general used to store number of nodes
present in the linked list or some other meta data
.
• Header circular link list are frequently used instead of ordinary linked list, because many
operations are much easier to state and implement using header list.
• Null pointer is not used and hence all pointer contains valid address.
o loop condition while(ptr != start)
Doubly link list
• The list which can be traversed in two directions: in the unusual forward direction from the
beginning of the list to the ends or in the end direction from the end of the list to the
beginning of the list.
• Furthermore given the location LOC of a node N in the list, one now has immediate access
to both the next node and the preceding node of the list. This means in particular that one
is able to delete N from the list without traversing any part of the list.
Header circular doubly link list
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
Answer: (d)
Q In the worst case, the number of comparisons needed to search a singly linked list of length
n for a given element is
(A) log2n (B) n/2 (C) log2 n – 1 (D) n
Answer: (D)
Q What does the following function do for a given Linked List with first node as head?
fun1(head->next)
printf("%d ", head->data);
}
(A) Prints all nodes of linked lists (B) Prints all nodes of linked list in reverse order
(C) Prints alternate nodes of Linked List (D) Prints alternate nodes in reverse order
Answer: (B)
Q What is the output of following function for start pointing to first node of following linked
list?
1->2->3->4->5->6
}
(A) 1 4 6 6 4 1 (B) 1 3 5 1 3 5 (C) 1 2 3 5 (D) 1 3 5 5 3 1
Answer: (D)
Q The following function reverse() is supposed to reverse a singly linked list. There is one line
missing at the end of the function.
}
What should be added in place of “/*ADD A STATEMENT HERE*/”, so that the function
correctly reverses a linked list.
(A) *head_ref = prev; (B) *head_ref = current;
(C) *head_ref = next; (D) *head_ref = NULL;
Answer: (A)
Q What are the time complexities of finding 8th element from beginning and 8th element
from end in a singly linked list?
Let n be the number of nodes in linked list, you may assume that n > 8.
(A) O(1) and O(n) (B) O(1) and O(1) (C) O(n) and O(1) (D) O(n) and O(n)
Answer: (A)
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.
(B) Possible if size of linked list is even.
(C) Possible if size of linked list is odd
(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.
Answer: (A)
Q You are given pointers to first and last nodes of a singly linked list, which of the following
operations are dependent on the length of the linked list?
(A) Delete the first element (B) Insert a new element as a first element
(C) Delete the last element of the list (D) Add a new element at the end of the list
Answer: (C)
Root
• The first/Top most node is called as Root Node. We always have exactly one root node
in every tree. We can say that root node is the origin of tree data structure.
Edge
• In a tree data structure, the connecting link between any two nodes is called as EDGE. In
a tree with 'N' number of nodes there will be exactly of 'N-1' number of edges.
Siblings
• In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In
simple words, the nodes with same parent are called as Sibling nodes.
Leaf
• In a tree data structure, the node which does not have a child is called as LEAF Node. In
simple words, a leaf is a node with no child.
• In a tree data structure, the leaf nodes are also called as External Nodes. External node
is also a node with no child. In a tree, leaf node is also called as 'Terminal' node.
Internal Nodes
• In a tree data structure, the node which has at least one child is called as INTERNAL
Node. In simple words, an internal node is a node with at least one child.
• In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The
root node is also said to be Internal Node if the tree has more than one node. Internal
nodes are also called as 'Non-Terminal' nodes.
Degree
• In a tree data structure, the total number of children of a node is called as DEGREE of
that Node. In simple words, the Degree of a node is total number of children it has. The
highest degree of a node among all the nodes in a tree is called as 'Degree of Tree'
Sub Tree
• In a tree data structure, each child from a node forms a subtree recursively. Every child
node will form a subtree on its parent node.
Note- in data structures tree are not natural trees they will always grow from root to leaves
downwards.
Binary tree
• A binary tree T is defined as a finite set of elements called nodes such that,
o T is empty (null tree)
o T contain a distinguished node R, called the root of T, and the remaining nodes of
T form an ordered pair of disjoint binary tree T1 and T2
• Direct: - A tree T in which any node can have maximum two children (left and right)
• Representation of tree in memory
o Sequential representation – using an array info and left child and right child
o Linked Representation – using self-referential structure node
struct node {
int data;
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)
(f)
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
ANSWER C
Q Level of a node is distance from root to that node. For example, level of root is 1 and
levels of left and right children of root is 2. The maximum number of nodes on level i of a
binary tree is. In the following answers, the operator ‘^’ indicates power.
(A) 2(i-1) (B) 2I (C) 2(i+1) (D) 2[(i+1)/2]
Answer: (A)
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
Answer: (C)
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
Answer: (A)
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
(C) 32 and 6, respectively (D) 31 and 5, respectively
Answer: (A)
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
(C) 4 and 14 respectively (D) 3 and 15 respectively
Answer: (B)
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
canonically 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.
• These steps can be done in any order. If (L) is done before (R), the process is called left-
to-right traversal, otherwise it is called right-to-left traversal. The following methods
show left-to-right traversal:
Pre-order (NLR)
Pre-order: F, B, A, D, C, E, G, I, H.
In-order: A, B, C, D, E, F, G, H, I.
Post-order: A, C, E, D, B, H, I, G, F.
Q if the binary tree in fig is traversed in inorder, then the order in which the nodes will be
visited is……. (GATE-1991) (1 Marks)
Q which of the following is post order traversal of the above tree (GATE-1996) (1 Marks)
Q which of the following binary trees has its inorder and preorder traversal as BCAD and
ABCD, respectively? (GATE-2004) (1 Marks)
Q
a) 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
ANSWER a
Q is it possible to construct a binary tree uniquely whose post order and pre order traversal
are given? (GATE-1987) (1 Marks)
(f)
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
Answer: (B)
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
Answer: (B)
Ans: a
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 * - ˆ -
ANSWER - c
struct CellNode
{
struct CelINode *leftchild;
int element;
struct CelINode *rightChild;
}
}
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
Answer: (B)
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)
The appropriate expression for the two boxes B1 and B2 are
(A) B1 : (1 + height(n->right)), B2 : (1 + max(h1,h2))
(B) B1 : (height(n->right)), B2 : (1 + max(h1,h2))
(C) B1 : height(n->right), B2 : max(h1,h2)
(D) B1 : (1 + height(n->right)), B2 : max(h1,h2)
Ans : a
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.
• A binary search tree is a rooted binary tree, whose internal nodes each store a key (and
optionally, an associated value) and each have two distinguished sub-trees, commonly
denoted left and right. The tree additionally satisfies the binary search property, which
states that the key in each node must be greater than or equal to any key stored in the
left sub-tree, and less than or equal to any key stored in the right sub-tree
• 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
Operations
Binary search trees support three main operations: insertion of elements, deletion of
elements, and lookup (checking whether a key is present).
Searching
We begin by examining the root node. If the tree is null, the key we are searching for does
not exist in the tree. Otherwise, if the key equals that of the root, the search is successful
and we return the node. If the key is less than that of the root, we search the left subtree.
Similarly, if the key is greater than that of the root, we search the right subtree. This
process is repeated until the key is found or the remaining subtree is null. If the searched
key is not found after a null subtree is reached, then the key is not present in the tree.
Insertion
Insertion begins as a search would begin; if the key is not equal to that of the root, we
search the left or right subtrees as before. Eventually, we will reach an external node and
add the new key-value pair (here encoded as a record 'newNode') as its right or left child,
depending on the node's key. In other words, we examine the root and recursively insert
the new node to the left subtree if its key is less than that of the root, or the right subtree if
its key is greater than or equal to the root.
Deletion
• Deleting a node with no children: simply remove the node from the tree.
• Deleting a node with one child: remove the node and replace it with its child.
• Deleting a node with two children: call the node to be deleted D. Do not delete D.
Instead, choose either its in-order predecessor node or its in-order successor node as
replacement node E (s. figure). Copy the user values of E to D.[note 2] If E does not have a
child simply remove E from its previous parent G. If E has a child, say F, it is a right child.
Replace E with F at E's parent.
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)(means root at level 0)?
(A) 2 (B) 3 (C) 4 (D) 6
Answer: (B)
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
Answer: (B)
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
Answer: (C)
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
ANSWER A
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
ANSWER- B
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
Answer: (A)
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
ANSWER D
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
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) (2 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
Answer: (D)
10
/ \
5 20
/ / \
4 15 30
/
11
If we randomly search one of the keys present in above BST, what would be the expected
number of comparisons?
(A) 2.75 (B) 2.25 (C) 2.57 (D) 3.25
Answer: (C)
Explanation: Expected number of comparisons = (1*1 + 2*2 + 3*3 + 4*1)/7 = 18/7 = 2.57
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
Answer: (A)
Q In delete operation of BST, we need inorder successor (or predecessor) of a node when
the node to be deleted has both left and right child as non-empty. Which of the following is
true about inorder successor needed in delete operation?
(A) Inorder Successor is always a leaf node
(B) Inorder successor is always either a leaf node or a node with empty left child
(C) Inorder successor may be an ancestor of the node
(D) Inorder successor is always either a leaf node or a node with empty right child
Answer: (B)
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) θ(nlog n) d) None of the above, as the tree cannot be uniquely determined
ANSWER B
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(nLogn)
ANSWER C
Q The worst-case running time to search for an element in a balanced in a binary search
tree with n2^n elements is (GATE-2013) (1 Marks)
(A) (B) (C) (D)
ANSWER C
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)
ANSWER 100
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
ANSWER B
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)
(A) 60 (B) 110 (C) 210 (D) 50
Answer: (B)
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)
(A) O(Logn)
(B) O(n)
(C) O(nLogn)
(D) none of the above, as the tree cannot be uniquely determined.
Answer: (B)
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.
• 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.
Problem Solution
LL R
RR L
LR LR
RL RL
• After every insertion at most two rotations are sufficient to balance the AVL tree
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?
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?
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
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)
ANSWER 3
Deletion in an AVL tree
AVL
Deletion
L R
L0 L1 L-1 R0 R1 R-1
RR RL RR LL LL LR
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
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
Ans: a
Complete Binary Tree
• Consider a binary tree T, the maximum number of nodes at height h is 2h 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.
• 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)
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
(C) LASTPRE = LASTPOST (D) None of the above
Answer: (D)
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)
(A) log2n (B) n (C) 2n + 1 (D) 2n — 1
Answer: (D)
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:
o The value of N is greater than to the value at each of the children of N then it is
called Max heap.
o A min heap is defined as the value at N is less than the value at any of the children of
N.
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)
(A) i – 1 (B) floor(i/2) (C) ceiling(i/2) (D) (i+1)/2
Answer: (B)
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)
Answer: (B)
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
Answer: (C)
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)
Answer: (A)
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
Answer: (D)
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
(C) 25,14,16,13,10,8,12 (D) 25,14,12,13,10,8,16
Answer: (C)
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
(C) 14,13,8,12,10 (D) 14,13,12,8,10
Answer: (D)
Q We have a binary heap on n elements and wish to insert n more elements (not necessarily
one after another) into this heap. The total time required for this is (GATE - 2008) (1 Marks)
(A) Q(logn) (B) Q(n) (C) Q(nlogn) (D) Q(n^2)
Answer: (B)
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)
Answer: (D)
Explanation: The 7th smallest element must be in first 7 levels.
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)
Answer: (A)
Q Given two max heaps of size n each, what is the minimum possible time complexity to make
a one max-heap of size from elements of two max heaps?
(A) O(nLogn) (B) O(nLogLogn) (C) O(n) (D) O(nLogn)
Answer: (C)
Explanation: We can build a heap of 2n elements in O(n) time. Following are the steps. Create
an array of size 2n and copy elements of both heaps to this array. Call build heap for the array
of size 2n. Build heap operation takes O(n) time.
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)
ANSWER – 8
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)
(ANSWER-80)
Q Which of the following Binary Min Heap operation has the highest time complexity?
(A) Inserting an item under the assumption that the heap has capacity to accommodate one
more item
(B) Merging with another heap under the assumption that the heap has capacity to
accommodate items of other heap
(C) Deleting an item from heap
(D) Decreasing value of a key
Answer: (B)
Explanation: The merge operation takes O(n) time, all other operations given in question take
O(Logn) time.
Q in the following array representation of binary heap, how many nodes are in the right
subtree of the root of the heap? 11,23,19,31,27,26,31,46,45,38,35,37,63,82,71,95?
a) 5 b) 6 c) 7 d) 8
Tree in general
Q How many distinct binary search trees can be created out of 4 distinct keys?
(A) 4 (B) 14 (C) 24 (D) 42
Answer: (B)
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
ANSWER 5
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)
(A) 0 (B) 1 (C) n! (D) (1/(n+1)).2nCn
Answer: (B)
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
Answer: (C)
Q In a complete k-ary tree, every internal node has exactly k children or no child. The number
of leaves in such a tree with an internal node is:
(A) nk (B) (n – 1) k+ 1 (C) n (k – 1) + 1 (D) n (k – 1)
Answer: (C)
Q What are the main applications of tree data structure?
a) Manipulate hierarchical data
b) Make information easy to search (see tree traversal).
c) Form of a multi-stage decision-making, like Chess Game
d) all
Ans: d
Q Let T(n) be the number of different binary search trees on n distinct elements. Then (GATE -
2003) (1 Marks)
where x is
(A) n-k+1 (B) n-k (C) n-k-1 (D) n-k-2
Answer: (B)
Explanation: The idea is to make a key root, put (k-1) keys in one subtree and remaining n-k
keys in another subtree.
Q Which data structure is most efficient to find the top 10 largest items out of 1 million items
stored in file?
(A) Min heap (B) Max heap (C) BST (D) Sorted array
Answer: (A)
Q A data structure is required for storing a set of integers such that each of the following
operations can be done in (log n) time, where n is the number of elements in the set. (GATE -
2003) (2 Marks)
o Deletion of the smallest element
o 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?
(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 binary search tree nor heap can be used
Answer: (B)
(GATE-2019) (2 Marks)
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)
Answer 1
Graph
• Graph is a data structure that consists of following two components:
o A finite set of vertices also called as nodes.
o 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.
• 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.
Representation of Graph in Memory
• Following two are the most commonly used representations of a graph.
o Adjacency Matrix
o 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.
• 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 for undirected graph is always symmetric.
• 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.
• 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(V^2). Even if the graph is sparse(contains less number of edges), it
consumes the same space. Adding a vertex is O(V^2) time.
Please see this for a sample Python implementation of adjacency matrix.
• 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.
Graph Traversal
• A standard DFS implementation puts each vertex of the graph into one of two categories:
o Visited
o Not Visited
• The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
let S be stack
S.push( s ) //Inserting s in stack
mark s as visited
while ( S is not empty)
{
v = S.top( )
S.pop( ) //Pop a vertex from stack to visit next
for all neighbours w of v in Graph G:
{
if w is not visited:
S.push( w ) //Push all the neighbors of v in stack that are not visited
mark w as visited
}
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)
(A) 1 and 3 only (B) 2 and 3 only (C) 2, 3 and 4 only (D) 1, 2, and 3
Answer: (B)
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)
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
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
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)
}
}
}
}
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
Ans: d
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
Answer: (D)
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
Answer: (C)
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
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
Answer: (C)
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)
Answer: (C)
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)
Answer: (B) .
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) (1 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
Answer: (B)
Q Let T be a depth first search tree in an undirected graph G. Vertices u and n are leaves of this
tree T. The degrees of both u and n 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 n in G
(B) There must exist a vertex w whose removal disconnects u and n in G
(C) There must exist a cycle in G containing u and n
(D) There must exist a cycle in G containing u and all its neighbours in G.
Answer: (B)
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) (n) (B) (m) (C) (m + n) (D) (mn)
Answer: (C) Explanation:
Q How many undirected graphs (not necessarily connected) can be constructed out of a given
set V= {V 1, V 2,…V n} of n vertices ?
(A) n(n-l)/2 (B) 2^n (C) n! (D) 2^(n(n-1)/2)
Answer: (D)
Q Given two vertices in a graph s and t, which of the two traversals (BFS and DFS) can be used
to find if there is path from s to t?
(A) Only BFS (B) Only DFS (C) Both BFS and DFS (D) Neither BFS nor DFS
Answer: (C)
Q Let G be a simple undirected graph. Let TD be a depth first search tree of G. Let TB be a
breadth first search tree of G. Consider the following statements. (I) No edge of G is a cross
edge with respect to TD. (A cross edge in G is between two nodes neither of which is an
ancestor of the other in TD). (II) For every edge (u, v) of G, if u is at depth i and v is at depth j in
TB, then ∣i − j∣ = 1. Which of the statements above must necessarily be true? (Gate-2018) (2
Marks)
a) I only b) II only c) Both I and II d) Neither I nor II
(ANSWER-A)
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
ANSWER B
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)
Ans: 31
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
Ans: d