Professional Documents
Culture Documents
ARTICLES
GATE
PLACEMENTS
PUZZLES
CONTRIBUTE
WHATS NEW
JOBS
APPS
INTERVIEW CORNER
Linked List
Question 1
WRONG
What does the following function do for a given Linked List with first node as head?
void fun1(struct node* head)
{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
Run on IDE
Prints all nodes of linked lists
Prints all nodes of linked list in reverse order
Linked List
Discuss it
Question 1 Explanation:
fun1() prints the given Linked List in reverse manner. For Linked List 1->2->3->4->5, fun1() prints 5->4->3-
>2->1. See http://www.geeksforgeeks.org/practice-questions-for-linked-list-and-recursion/
Question 2
WRONG
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.
D The size of array has to be pre-decided, linked lists can change their size any time.
Question 2 Explanation:
See http://www.geeksforgeeks.org/linked-list-vs-array/ for explanation.
Question 3
CORRECT
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.
void fun(struct node **head_ref)
{
struct node *temp = NULL;
struct node *current = *head_ref;
if(temp != NULL )
*head_ref = temp->prev;
}
Run on IDE
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?
Linked List
Discuss it
Question 3 Explanation:
The given function reverses the given doubly linked list. See Reverse a Doubly Linked List for details.
Question 4
WRONG
Which of the following sorting algorithms can be used to sort a random linked list with minimum time
complexity?
A Insertion Sort
B Quick Sort
Heap Sort
Merge Sort
Linked List
Discuss it
Question 4 Explanation:
Both Merge sort and Insertion sort can be used for linked lists. The slow random-access performance of a
linked list makes other algorithms (such as quicksort) perform poorly, and others (such as heapsort)
completely impossible. Since worst case time complexity of Merge Sort is O(nLogn) and Insertion sort is
O(n^2), merge sort is preferred. See following for implementation of merge sort using Linked
List.http://www.geeksforgeeks.org/merge-sort-for-linked-list/
Question 5
WRONG
The following function reverse() is supposed to reverse a singly linked list. There is one line missing at the
end of the function.
/* Link list node */
struct node
{
int data;
struct node* next;
};
B *head_ref = current;
*head_ref = next;
D *head_ref = NULL;
Linked List
Discuss it
Question 5 Explanation:
*head_ref = prev; At the end of while loop, the prev pointer points to the last node of original linked list. We
need to change *head_ref so that the head pointer now starts pointing to the last node. See the following
complete running program. 1
Question 6
WRONG
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);
}
Run on IDE
A 146641
135135
C 1235
135531
Linked List
Discuss it
Question 6 Explanation:
fun() prints alternate nodes of the given Linked List, first from head to end, and then from end to head. If
Linked List has even number of nodes, then skips the last node.
Question 7
WRONG
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.
typedef struct node
{
int value;
struct node *next;
}Node;
Question 7 Explanation:
See question 1 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-24/
Question 8
CORRECT
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?
struct node
{
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;
}
}
Run on IDE
A 1,2,3,4,5,6,7
2,1,4,3,6,5,7
C 1,3,2,5,4,7,6
D 2,3,4,5,6,7,1
Linked List
Discuss it
Question 8 Explanation:
The function rearrange() exchanges data of every node with its next node. It starts exchanging data from
the first node itself.
Question 9
WRONG
In the worst case, the number of comparisons needed to search a singly linked list of length n for a given
element is (GATE CS 2002)
A log 2 n
B n/2
log 2 n 1
n
Linked List
Discuss it
Question 9 Explanation:
In the worst case, the element to be searched has to be compared with all elements of linked list.
Question 10
WRONG
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 CS 2004)
A union only
B intersection, membership
membership, cardinality
union, intersection
Linked List
Discuss it
Question 10 Explanation:
For getting intersection of L1 and L2, search for each element of L1 in L2 and print the elements we find
in L2. There can be many ways for getting union of L1 and L2. One of them is as follows a) Print all the
nodes of L1 and print only those which are not present in L2. b) Print nodes of L2. All of these methods
will require more operations than intersection as we have to process intersection node plus other nodes.
Question 11
WRONG
Consider the function f defined below.
struct item
{
int data;
struct item * next;
};
int f(struct item *p)
{
return (
(p == NULL) ||
(p->next == NULL) ||
(( P->data <= p->next->data) && f(p->next))
);
}
Run on IDE
For a given linked list p, the function f returns 1 if and only if (GATE CS 2003)
the elements in the list are sorted in non-decreasing order of data value
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.
Linked List
Discuss it
Question 11 Explanation:
The function f() works as follows 1) If linked list is empty return 1 2) Else If linked list has only one element
return 1 3) Else if node->data is smaller than equal to node->next->data and same thing holds for rest of
the list then return 1 4) Else return 0
Question 12
WRONG
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
B front node
Linked List
Discuss it
Question 12 Explanation:
Answer is not "(b) front node", as we can not get rear from front in O(1), but if p is rear we can implement
both enQueue and deQueue in O(1) because from rear we can get front in O(1). Below are sample
functions. Note that these functions are just sample are not working. Code to handle base cases is
missing. 1
Question 13
WRONG
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.
O(1) and O(n)
Linked List
Discuss it
Question 13 Explanation:
Finding 8th element from beginning requires 8 nodes to be traversed which takes constant time. Finding
8th from end requires the complete list to be traversed.
Question 14
WRONG
Is it possible to create a doubly linked list using only one pointer with every node.
A Not Possible
Linked List
Discuss it
Question 14 Explanation:
XOR Linked List A Memory Efficient Doubly Linked List | Set 1
Question 15
CORRECT
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?
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.
Possible if X is not first node. Use following two steps (a) Copy the data of next of X to X. (b)
D Delete next of X.
Linked List
Discuss it
Question 15 Explanation:
Following are simple steps.
struct node *temp = X->next;
X->data = temp->data;
X->next = temp->next;
free(temp);
Question 16
CORRECT
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?
Linked List
Discuss it
Question 16 Explanation:
a) Can be done in O(1) time by deleting memory and changing the first pointer. b) Can be done in O(1)
time, see push() here c) Delete the last element requires pointer to previous of last, which can only be
obtained by traversing the list. d) Can be done in O(1) by changing next of last and then last.
Question 17
WRONG
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;
}
}
Run on IDE
Which of the following is FALSE about above function?
The function doesn't print the last node when the linked list is not empty
The function is implemented incorrectly because it changes head
Question 18
WRONG
Let P be a singly linked list. Let Q be the pointer to an intermediate node x in the list. What is the worst-
case time complexity of the best known algorithm to delete the node x from the list?
A O(n)
O(log2 n)
C O(logn)
O(1)
Linked List GATE-IT-2004
Discuss it
Question 18 Explanation:
A simple solution is to traverse the linked list until you find the node you want to delete. But this solution
requires pointer to the head node which contradicts the problem statement. Fast solution is to copy the
data from the next node to the node to be deleted and delete the next node. Something like following.
// Find next node using next pointer
node_ptr->data = temp->data;
node_ptr->next = temp->next;
free(temp);
Time complexity of this approach is O(1) Refer this for implementation. Note that this approach doesn't
work when node to deleted is last node. Since the question says intermediate node, we can use this
approach.
Question 19
WRONG
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
A O(Log2N)
O(N)
O(N2)
D (N2 Log N)
Question 19 Explanation:
The time complexity of decrease-key operation is (1) since we have the pointer to the record where we
have to perform the operation. However, we must keep the doubly linked list sorted and after the
decrease-key operation we need to find the new location of the key. This step will take (N) time and
since there are (N) decrease-key operations, the time complexity becomes O(N). Note that the other
three operations have a lower bound than this one.
Stack
Question 1
WRONG
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;
}
Stack
Discuss it
Question 1 Explanation:
See method 2 of http://www.geeksforgeeks.org/binary-representation-of-a-given-number/ for explanation.
Question 2
WRONG
Which one of the following is an application of Stack Data Structure?
Question 2 Explanation:
See http://en.wikipedia.org/wiki/Stack_(abstract_data_type)#Applications
Question 3
WRONG
Which of the following is true about linked list implementation of stack?
In push operation, if new nodes are inserted at the beginning of linked list, then in pop operation,
A nodes must be removed from end.
In push operation, if new nodes are inserted at the end, then in pop operation, nodes must be
Question 4
WRONG
Consider the following pseudocode that uses a stack
declare a stack of characters
while ( there are more characters in the word to read )
{
read a character
push the character on the stack
}
while ( the stack is not empty )
{
pop a character off the stack
write the character to the screen
}
Run on IDE
What is output for input "geeksquiz"?
A geeksquizgeeksquiz
ziuqskeeg
geeksquiz
D ziuqskeegziuqskeeg
Stack
Discuss it
Question 4 Explanation:
Since the stack data structure follows LIFO order. When we pop() items from stack, they are popped in
reverse order of their insertion (or push())
Question 5
WRONG
Following is an incorrect pseudocode for the algorithm which is supposed to determine whether a
sequence of parentheses is balanced:
declare a character stack
while ( more input is available)
{
read a character
if ( the character is a '(' )
push it on the stack
else if ( the character is a ')' and the stack is not empty )
pop a character off the stack
else
print "unbalanced" and exit
}
print "balanced"
Run on IDE
Which of these unbalanced sequences does the above code think is balanced?
Source: http://www.cs.colorado.edu/~main/questions/chap07q.html
((())
B ())(()
(()()))
D (()))()
Stack
Discuss it
Question 5 Explanation:
At the end of while loop, we must check whether the stack is empty or not. For input ((()), the stack
doesn't remain empty after the loop. See http://www.geeksforgeeks.org/check-for-balanced-parentheses-
in-an-expression/ for details.
Question 6
WRONG
The following postfix expression with single digit operands is evaluated using a stack:
823^/23*+51*-
Note that ^ is the exponentiation operator. The top two elements of the stack after the first * is evaluated
are:
6, 1
5, 7
C 3, 2
D 1, 5
Stack
Discuss it
Question 6 Explanation:
The algorithm for evaluating any postfix expression is fairly straightforward:
1. While there are input tokens left
(Error) The user has not input sufficient values in the expression.
* Else, Pop the top n values from the stack.
* Evaluate the operator, with the values as arguments.
* Push the returned results, if any, back onto the stack.
2. If there is only one value in the stack
o That value is the result of the calculation.
3. If there are more values in the stack
o (Error) The user input has too many values.
Source for algorithm: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_postfix_algorithm Let us
run the above algorithm for the given expression. First three tokens are values, so they are simply pushed.
After pushing 8, 2 and 3, the stack is as follows
8, 2, 3
Next two tokens are values, so they are simply pushed. After pushing 2 and 3, the stack is as follows
1, 2, 3
Question 7
WRONG
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
A n(X+ Y)
3Y + 2X
n(X + Y)-X
D Y + 2X
Stack
Discuss it
Question 7 Explanation:
We can easily arrive at the result by taking few examples.
Question 8
WRONG
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 (topl< 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 CS 2004)
Question 8 Explanation:
If we are to use space efficiently then size of the any stack can be more than MAXSIZE/2. Both stacks will
grow from both ends and if any of the stack top reaches near to the other top then stacks are full. So the
condition will be top1 = top2 -1 (given that top1 < top2)
Question 9
WRONG
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
abc + def ^ ^ -
abc + de ^ f ^ -
C ab + c d - e ^ f ^
D - + a bc ^ ^ def
Stack GATE-CS-2004
Discuss it
Question 9 Explanation:
^ is right assosciative.
See http://g
eeksquiz.com/stack-set-2-infix-to-postfix/ This solution is contributed by parul Sharma.
Question 10
WRONG
To evaluate an expression without any embedded function calls:
One stack is enough
Stack GATE-CS-2002
Discuss it
Question 10 Explanation:
Any expression can be converted into Postfix or Prefix form.
Prefix and postfix evaluation can be done using a single stack.
For example : Expression '10 2 8 * + 3 -' is given. PUSH 10 in the stack. PUSH 2 in the stack. PUSH 8 in
the stack. When operator '*' occurs, POP 2 and 8 from the stack. PUSH 2 * 8 = 16 in the stack. When
operator '+' occurs, POP 16 and 10 from the stack. PUSH 10 * 16 = 26 in the stack. PUSH 3 in the stack.
When operator '-' occurs, POP 26 and 3 from the stack. PUSH 26 - 3 = 23 in the stack. So, 23 is the
answer obtained using single stack.
Please comment below if you find anything wrong in the above post.
Question 11
WRONG
The result evaluating the postfix expression 10 5 + 60 6 / * 8 is
A 284
213
142
D 71
Question 11 Explanation:
http://geeksquiz.com/stack-set-4-evaluation-postfix-expression/
Question 12
WRONG
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)?
A 6
4
3
D 2
Question 12 Explanation:
f(S) = 0, max(f(S), 0) = 0, i = 2 f(S)new = max(f(S), 0) + i = 0 + 2 = 2
f(S) = 2, max(f(S), 0) = 2, i = -3 f(S)new = max(f(S), 0) + i = 2 - 3 = -1
f(S) = -1, max(f(S), 0) = 0, i = 2 f(S)new = max(f(S), 0) + i = 0 + 2 = 2
f(S) = 2, max(f(S), 0) = 2, i = -1 f(S)new = max(f(S), 0) + i = 2 - 1 = 1
f(S) = 1, max(f(S), 0) = 1, i = 2 f(S)new = max(f(S), 0) + i = 1 + 2 = 3
Please comment below if you find anything wrong in the above post.
Question 13
CORRECT
Consider the following C program:
#include
#define EOF -1
void push (int); /* push the argument on the stack */
int pop (void); /* pop the top of the stack */
void flagError ();
int main ()
{ int c, m, n, r;
while ((c = getchar ()) != EOF)
{ if (isdigit (c) )
push (c);
else if ((c == '+') || (c == '*'))
{ m = pop ();
n = pop ();
r = (c == '+') ? n + m : n*m;
push (r);
}
else if (c != ' ')
flagError ();
}
printf("% c", pop ());
}
Run on IDE
What is the output of the program for the following input ? 5 2 * 3 3 2 + * +
A 15
25
C 30
D 150
Question 13 Explanation:
The function of the program is:- 1) If the current character is a digit it pushes into stack
2) Else if the current character is operator, it pops two elements and then performs the
operation. Finally it pushes the resultant element into stack. Initially stack s is empty. 5 2
* 3 3 2 + * + 1) 5 -> It pushes into s 2) 2 -> It pushes into s 3) * -> It pops two elements n
= 2, m=5 n*m = 10 It pushes 10 into s 4) 3 -> It pushes into s 5) 3 -> It pushes into s 6)
2 -> It pushes into s 7) + -> n=2, m=3 n+m=5 It pushes 5 into s 8) * -> n=5, m=3 n*m=15
It pushes 15 into s 9) + -> n=15, m=10 n+m = 25 It pushes 25 into s. Finally the result
value is the only element present in stack. This solution is contributed by Anil Saikrishna
Devarasetty. Result = 25
Question 14
CORRECT
Suppose a stack is to be implemented with a linked list instead of an array. What would be the effect on
the time complexity of the push and pop operations of the stack implemented using linked list (Assuming
stack is implemented efficiently)?
Question 14 Explanation:
Stack can be implemented using link list having O(1) bounds for both insertion as well as deletion by
inserting and deleting the element from the beginning of the list.
Question 15
WRONG
Consider n elements that are equally distributed in k stacks. In each stack, elements of it are arranged in
ascending order (min is at the top in each of the stack and then increasing downwards). Given a queue of
size n in which we have to put all n elements in increasing order. What will be the time complexity of the
best known algorithm?
O(n logk)
B O(nk)
O(n2)
D O(k2)
Stack GATE 2017 Mock
Discuss it
Question 15 Explanation:
In nlogk it can be done by creating a min heap of size k and adding all the top - elements of all the stacks.
After extracting the min , add the next element from the stack from which we have got our 1st minimum.
Time Complexity = O(k) (For Creating Heap of size k) + (n-k)log k (Insertions into the heap).
ARTICLES
GATE
PLACEMENTS
PUZZLES
CONTRIBUTE
WHATS NEW
JOBS
APPS
INTERVIEW CORNER
Queue
Question 1
WRONG
Following is C like pseudo code of a function that takes a Queue as an argument, and uses a stack S to
do processing.
void fun(Queue *Q)
{
Stack S; // Say it creates an empty stack S
C Makes Q empty
Reverses the Q
Question 1 Explanation:
The function takes a queue Q as an argument. It dequeues all items of Q and pushes them to a stack S.
Then pops all items of S and enqueues the items back to Q. Since stack is LIFO order, all items of queue
are reversed.
Question 2
WRONG
Which one of the following is an application of Queue Data Structure?
When data is transferred asynchronously (data not necessarily received at same rate as sent)
B between two processes
Load Balancing
All of the above
Queue
Discuss it
Question 2 Explanation:
See http://www.geeksforgeeks.org/applications-of-queue-data-structure/ for details.
Question 3
WRONG
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
2
3
D 4
Queue
Discuss it
Question 3 Explanation:
A queue can be implemented using two stacks. See following for
implementation.http://www.geeksforgeeks.org/queue-using-stacks/
Question 4
CORRECT
How many queues are needed to implement a stack. Consider the situation where no other data structure
like arrays, linked list is available to you.
A 1
C 3
D 4
Queue
Discuss it
Question 4 Explanation:
A stack can be implemented using two queues. Please see following for
details.http://www.geeksforgeeks.org/implement-stack-using-queue/
Question 5
WRONG
A priority queue can efficiently implemented using which of the following data structures? Assume that the
number of insert and peek (operation to see the current highest priority item) and extraction (remove the
highest priority item) operations are almost same.
A Array
Linked List
Heap Data Structures like Binary Heap, Fibonacci Heap
Queue
Discuss it
Question 5 Explanation:
See http://en.wikipedia.org/wiki/Priority_queue
Question 6
CORRECT
Which of the following is true about linked list implementation of queue?
In push operation, if new nodes are inserted at the beginning of linked list, then in pop operation,
A nodes must be removed from end.
In push operation, if new nodes are inserted at the end, then in pop operation, nodes must be
B removed from the beginning.
Both of the above
Queue
Discuss it
Question 6 Explanation:
To keep the First In First Out order, a queue can be implemented using linked list in any of the given two
ways.
Question 7
WRONG
Suppose a circular queue of capacity (n 1) elements is implemented with an array of n elements.
Assume that the insertion and deletion operation are carried out using REAR and FRONT as array index
variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full and queue empty
are
Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT
Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR
Queue
Discuss it
Question 7 Explanation:
Suppose we start filling the queue.
( REAR+1)%n = (4+1)%5 = 0
FRONT is also 0.
Question 8
WRONG
A Priority-Queue is implemented as a Max-Heap. Initially, it has 5 elements. The level-order traversal of
the heap is given below: 10, 8, 5, 3, 2 Two new elements 1 and 7 are inserted in the heap in that order.
The level-order traversal of the heap after the insertion of the elements is:
A 10, 8, 7, 5, 3, 2, 1
10, 8, 7, 2, 3, 1, 5
C 10, 8, 7, 1, 2, 3, 5
10, 8, 7, 3, 2, 1, 5
Queue
Discuss it
Question 8 Explanation:
See question 4 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-22/
Question 9
WRONG
An implementation of a queue Q, using two stacks S1 and S2, is given below:
void insert(Q, x) {
push (S1, x);
}
void delete(Q){
if(stack-empty(S2)) then
if(stack-empty(S1)) then {
print(Q is empty);
return;
}
else while (!(stack-empty(S1))){
x=pop(S1);
push(S2,x);
}
x=pop(S2);
}
Run on IDE
Let n insert and m (<=n) delete operations be performed in an arbitrary order on an empty queue Q. 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?
n+m <= x < 2n and 2m <= y <= n+m
Queue
Discuss it
Question 9 Explanation:
The order in which insert and delete operations are performed matters here. The best case: Insert and
delete operations are performed alternatively. In every delete operation, 2 pop and 1 push operations are
performed. So, total m+ n push (n push for insert() and m push for delete()) operations and 2m pop
operations are performed. The worst case: First n elements are inserted and then m elements are
deleted. In first delete operation, n + 1 pop operations and n push operation are performed. Other than
first, in all delete operations, 1 pop operation is performed. So, total m + n pop operations and 2n push
operations are performed (n push for insert() and n push for delete())
Question 10
WRONG
Consider the following operation along with Enqueue and Dequeue operations on queues, where k is a
global parameter.
MultiDequeue(Q){
m=k
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 CS 2013) (A) (B) (C) (D)
A
B
C C
D D
Queue
Discuss it
Question 10 Explanation:
Since the queue is empty initially, the condition of while loop never becomes true. So the time complexity
is [Tex]\Theta(n)[/Tex].
Question 11
WRONG
Consider the following pseudo code. Assume that IntQueue is an integer queue. What does the function
fun do?
void fun(int n)
{
IntQueue q = new IntQueue();
q.enqueue(0);
q.enqueue(1);
for (int i = 0; i < n; i++)
{
int a = q.dequeue();
int b = q.dequeue();
q.enqueue(b);
q.enqueue(a + b);
ptint(a);
}
}
Run on IDE
Prints numbers from 0 to n-1
Queue
Discuss it
Question 11 Explanation:
The function prints first n Fibonacci Numbers. Note that 0 and 1 are initially there in q. In every iteration of
loop sum of the two queue items is enqueued and the front item is dequeued.
Question 12
WRONG
Consider the following operation along with Enqueue and Dequeue operations on queues, where k is a
global parameter.
MultiDequeue(Q){
m=k
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 CS 2013)
(A)
(B)
(C)
(D)
A
B
C C
D D
Question 12 Explanation:
See http://geeksquiz.com/data-structures-queue-question-10-2/
Question 13
WRONG
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?
A queue can be implemented where ENQUEUE takes a single instruction and DEQUEUE takes a
Question 13 Explanation:
To DEQUEUE an item, simply POP. To ENQUEUE an item, we can do following 3 operations 1)
REVERSE 2) PUSH 3) REVERSE
Question 14
WRONG
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)?
Both operations can be performed in O(1) time
At most one operation can be performed in O(1) time but the worst case time for the other
C The worst case time complexity for both operations will be (n)
Question 14 Explanation:
We can use circular array to implement both in O(1) time. See below article for details.
Queue Introduction and Array Implementation
Question 15
CORRECT
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.
A 16
B 32
256
D 64
Question 15 Explanation:
The worst case happens when the queue is sorted in decreasing order. In worst case, loop runs n*n
times.
Queue: 4 3 2 1
Stack: Empty
321
3214
Empty
214
2143
Empty
143
1432
Empty
432
32
14
324
24
13
243
43
12
3
124
34
12
123
Empty
1234
Question 16
CORRECT
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);
}
}
Run on IDE
What operation is performed by the above function f ?
Question 16 Explanation:
As it is recursive call, and removing from front while inserting from end, that means last element will be
deleted at last and will be inserted 1st in the new queue. And like that it will continue till first call executes
insert(Q,i) function.
So, the queue will be in reverse.
Question 17 Explanation:
Number of nodes is maximum for a perfect binary tree.
Question 18
WRONG
A binary tree T has 20 leaves. The number of nodes in T having two children is
18
19
C 17
Question 18 Explanation:
Sum of all degrees = 2 * |E|. Here considering tree as a k-ary tree :
Sum of degrees of leaves + Sum of degrees for Internal Node except root + Root's degree = 2 * (No. of
nodes - 1).
L + (I-1)*(k+1) + k = 2 * (L + I - 1)
L + k*I - k + I -1 + k = 2*L + 2I - 2
K*I + 1 - I = L
(K-1)*I + 1 = L
Given k = 2, L=20
==> (2-1)*I + 1 = 20
==> I = 19
See Handshaking Lemma and Interesting Tree Properties for proof. This solution is contributed by Anil
Saikrishna Devarasetty
Question 19
WRONG
Consider a complete binary tree where the left and the right subtrees of the root are max-heaps. The
lower bound for the number of operations to convert the tree to a heap is
(logn)
(n)
C (nlogn)
D (n2)
Question 19 Explanation:
The answer to this question is simply max-heapify function. Time complexity of max-heapify is O(Log n)
as it recurses at most through height of heap.
// A recursive method to heapify a subtree with root at given index
// This method assumes that the subtrees are already heapified
void MinHeap::MaxHeapify(int i)
int l = left(i);
int r = right(i);
int largest = i;
largest = l;
largest = r;
if (largest != i)
{
swap(&harr[i], &harr[largest]);
MinHeapify(largest);
Question 20
CORRECT
An array of integers of size n can be converted into a heap by adjusting the heaps rooted at each internal
node of the complete binary tree starting at the node (n - 1) /2, and doing this adjustment up to the root
node (root node is at index 0) in the order (n - 1)/2, (n - 3)/ 2, ....., 0. The time required to construct a
heap in this manner is
A O(log n)
O(n)
C O (n log log n)
D O(n log n)
Question 20 Explanation:
The above statement is actually algorithm for building a Heap of an input array A.
BUILD-HEAP(A)
heapsize := size(A);
do HEAPIFY(A, i);
end for
END
Upper bound of time complexity is O(n) for above algo See- http://www.geeksforgeeks.org/g-fact-85/
Question 21
CORRECT
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:
A 2h - 1
2h - 1 + 1
C 2h - 1
D 2h
Question 21 Explanation:
Let there be n(h) nodes at height h.
n(h) = 2*n(h-1) + 1
n(h) = 2*n(h-1) + 1 - 2
= 2*n(h-1) - 1
Now if try all options, only option (b) satisfies above recurrence.
n(h) = 2h - 1 + 1
So if we substitute
n(h-1) = 2h-2 + 1, we should get n(h) = 2h-1 + 1
n(h) = 2*n(h-1) - 1
= 2*(2h-2 + 1) -1
= 2h-1 + 1.
Question 22
WRONG
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 ________ [This Question was originally a Fill-in-the-blanks Question]
A 15
16
31
D 32
Binary Trees GATE-CS-2016 (Set 2)
Discuss it
Question 22 Explanation:
It would be node number 31 for given distance 4. For example if we consider at distance 2, below
highlighted node G can be the farthest node at position 7.
A
/ \
B C
/\ /\
D E F G
Question 23
CORRECT
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
A 10
11
C 12
D 15
Question 23 Explanation:
In a binary tree, the number of leaf nodes is always 1 more than number of internal nodes with 2 children,
refer http://www.geeksforgeeks.org/handshaking-lemma-and-interesting-tree-properties/ So, Number of
Leaf Nodes = Number of Internal nodes with 2 children + 1 Number of Leaf Nodes = 10 + 1 Number of
Leaf Nodes = 11
Question 24
WRONG
The following three are known to be the preorder, inorder and postorder sequences of a binary tree. But it
is not known which is which.
MBCAFHPYK
KAMCBYPFH
MABCKYFPH
Pick the true statement from the following.
I and II are preorder and inorder sequences, respectively
B I and III are preorder and postorder sequences, respectively
C II is the inorder sequence, but nothing more can be said about the other two sequences
Question 24 Explanation:
The approach to solve this question is to first find 2 sequences whose first and last element is same. The
reason being first element in the Pre-order of any binary tree is the root and last element in the Post-order
of any binary tree is the root. Looking at the sequences given, Pre-order = KAMCBYPFH Post-order =
MBCAFHPYK Left-over sequence MABCKYFPH will be in order. Since we have all the traversals
identified, let's try to draw the binary tree if possible.
I. Post
order
II. Pre order
III. Inorder This solution is contributed by Pranjul Ahuja.
Question 25
WRONG
A binary tree with n > 1 nodes has n1, n2 and n3 nodes of degree one, two and three respectively. The
degree of a node is defined as the number of its neighbors.
n3 can be expressed as
A n1 + n2 - 1
n1 - 2
[((n1 + n2)/2)]
D n2 - 1
Question 25 Explanation:
Question 26
WRONG
A binary tree with n > 1 nodes has n1, n2 and n3 nodes of degree one, two and three respectively. The
degree of a node is defined as the number of its neighbors.
Starting with the above tree, while there remains a node v of degree two in the tree, add an edge between
the two neighbors of v and then remove v from the tree. How many edges will remain at the end of the
process?
2 * n1 - 3
n2 + 2 * n1 - 2
C n3 - n2
D n2 + n1 - 2
Question 26 Explanation:
With reference to figure of answer of previous question:
Binary Search Trees
Question 1
WRONG
What is the worst case time complexity for search, insert and delete operations in a general Binary
Search Tree?
O(n) for all
O(Logn) for all
Question 1 Explanation:
In skewed Binary Search Tree (BST), all three operations can take O(n). See the following example BST
and operations.
10
20
30
40
Search 40.
Delete 40
Insert 50.
Question 2
WRONG
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?
Inorder Successor is always a leaf node
Inorder successor is always either a leaf node or a node with empty left child
Question 2 Explanation:
Let X be the node to be deleted in a tree with root as 'root'. There are three cases for deletion 1) X is a
leaf node: We change left or right pointer of parent to NULL (depending upon whether X is left or right
child of its parent) and we delete X 2) One child of X is empty: We copy values of non-empty child to X
and delete the non-empty child 3) Both children of X are non-empty: In this case, we find inorder
successor of X. Let the inorder successor be Y. We copy the contents of Y to X, and delete Y. Sp we need
inorder successor only when both left and right child of X are not empty. In this case, the inorder
successor Y can never be an ancestor of X. In this case, the inorder successor is the leftmost node in
right subtree of X. Since it is leftmost node, the left child of Y must be empty.
Question 3
CORRECT
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 CS 2011)
A 0
C n!
D (1/(n+1)).2nCn
Question 3 Explanation:
There is only one way. The minimum value has to go to the leftmost node and the maximum value to the
rightmost node. Recursively, we can define for other nodes.
Question 4
WRONG
How many distinct binary search trees can be created out of 4 distinct keys?
A 4
14
24
D 42
Binary Search Trees
Discuss it
Question 4 Explanation:
See question 2 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-23/ for explanation.
The link also has a generalized solution.
Question 5
WRONG
Which of the following traversal outputs the data in sorted order in a BST?
A Preorder
Inorder
C Postorder
Level order
Binary Search Trees
Discuss it
Question 5 Explanation:
Inorder traversal of a BST outputs data in sorted order. Read here for details.
Question 6
CORRECT
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?
A 7510324689
B 0243165987
0123456789
D 9864230157
Question 6 Explanation:
In-order traversal of a BST gives elements in increasing order. So answer c is correct without any doubt.
Question 7
CORRECT
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 CS 2004)
A 2
C 4
D 6
Question 7 Explanation:
Constructed binary search tree will be..
10
/ \
1 15
\ / \
3 12 16
Question 8
WRONG
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 postorder traversal sequence of the same tree?
Question 8 Explanation:
The following is the constructed tree
30
/ \
20 39
/ \ / \
10 25 35 42
\ /
15 23
Question 9
WRONG
Consider the following Binary Search Tree
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?
2.75
B 2.25
2.57
D 3.25
Question 9 Explanation:
Expected number of comparisons = (1*1 + 2*2 + 3*3 + 4*1)/7 = 18/7 = 2.57
Question 10
CORRECT
Which of the following traversals is sufficient to construct BST from given traversals 1) Inorder 2) Preorder
3) Postorder
Either 2 or 3 is sufficient
C 2 and 3
D 1 and 3
Binary Search Trees
Discuss it
Question 10 Explanation:
When we know either preorder or postorder traversal, we can construct the BST. Note that we can always
sort the given traversal and get the inorder traversal. Inorder traversal of BST is always sorted.
Question 11
WRONG
Consider the following code snippet in C. The function print() receives root of a Binary Search Tree (BST)
and a positive integer k as arguments.
// A BST node
struct node {
int data;
struct node *left, *right;
};
int count = 0;
10 20
/\ / \
8 12 16 25
10
16
C 20
D 20 10
Question 12
CORRECT
Consider the same code as given in above question. What does the function print() do in general? The
function print() receives root of a Binary Search Tree (BST) and a positive integer k as arguments.
// A BST node
struct node {
int data;
struct node *left, *right;
};
int count = 0;
Question 12 Explanation:
The function basically does reverse inorder traversal of the given Binary Search Tree. The reverse inorder
traversal produces data in reverse sorted order. Whenever a nod is visited, count is incremented by 1 and
data of a node is printed only when count becomes k.
Question 13
CORRECT
You are given the postorder 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 postorder traversal. What is the time complexity
of the most efficient algorithm for doing this?
A O(Logn)
O(n)
C O(nLogn)
Question 13 Explanation:
One important thing to note is, it is Binary Search Tree, not Binary Tree. In BST, inorder traversal can
always be obtained by sorting all keys. See method 2 of http://www.geeksforgeeks.org/construct-bst-from-
given-preorder-traversa/ for details. Same technique can be used for postorder traversal.
Question 14
CORRECT
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(n alogb n + mc logd n), the value of a +
10b + 100c + 1000d is ____.
A 60
110
C 210
D 50
Question 14 Explanation:
int getSum(node *root, int L, int H)
// Base Case
if (root == NULL)
return 0;
if (root->key < L)
return getSum(root->left, L, H)
getSum(root->right, L, H);
The above always takes O(m + Logn) time. Note that the code first traverses across height to find the
node which lies in range. Once such a node is found, it recurs for left and right children. Two recursive
calls are made only if the node is in range. So for every node that is in range, we make at most one extra
call (here extra call means calling for a node that is not in range).
Question 15
CORRECT
Let T(n) be the number of different binary search trees on n distinct elements.
Then , where x is
A n-k+1
n-k
C n-k-1
D n-k-2
Question 15 Explanation:
A
The idea is to make a key root, put (k-1) keys in one subtree and remaining n-k keys in other subtree.
Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
properties
The left sub-tree of a node has a key less than or equal to its parent node's
key.
The right sub-tree of a node has a key greater than to its parent node's key.
Now construction binary search trees from n distinct number- Lets for simplicity consider
n distinct numbers as first n natural numbers (starting from 1) If n=1 We have only one
possibility, therefore only 1 BST. If n=2 We have 2 possibilities , when smaller number is
root and bigger number is the right child or second when the bigger number is root and
smaller number as left
child.
If n=3 We
have 5 possibilities. Keeping each number first as root and then arranging the
remaining 2 numbers as in case of n=2.
If n=4 Wehave 14
possibilities. Taking each number as root and arranging smaal numbers as left subtree
and larger numbers as right
subtree. Thu
s we can conclude that with n distinct numbers, if we take k as root then all the
numbers smaller than k will left subtree and numbers larger than k will be right subtree
where the the right subtree and left subtree will again be constructed recursively like the
root. Therefore,
This solution
is contributed by Parul Sharma.
Question 16
WRONG
What are the worst-case complexities of insertion and deletion of a key in a binary search tree?
Question 17
CORRECT
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
A 65
67
C 69
D 83
Question 17 Explanation:
Here is The Insertion Algorithm For a Binary Search Tree :
Insert(Root,key)
if(Root is NULL)
Insert(Root.left,key)
Else
Insert(Root.right,key)
}
Creating the BST one by one using the above algorithm in the below given image :
This solution is
contributed by Pranjul Ahuja.
Question 18
WRONG
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. [This question was originally a Fill-in-the-Blanks question]
A 2
4
64
D 32
[1..6]
[2..7]
Question 19
WRONG
Suppose that we have numbers between 1 and 100 in a binary search tree and want to search for the
number 55. Which of the following sequences CANNOT be the sequence of nodes examined?
Question 19 Explanation:
In BST on right side of parent number should be greater than it, but in C after 47, 43 appears that is
wrong.
Question 20
CORRECT
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?
35
B 64
C 128
D 5040
Question 20 Explanation:
There are two set of values, smaller than 60 and greater than 60. Smaller values 10, 20, 40 and 50 are
visited, means they are visited in order. Similarly, 90, 80 and 70 are visited in order.
= 7!/(4!3!)
= 35
Question 21
CORRECT
A Binary Search Tree (BST) stores values in the range 37 to 573. Consider the following sequence of
keys.
Suppose the BST has been unsuccessfully searched for key 273. Which all of the above sequences list
nodes in the order in which we could have encountered them in the search?
II and III only
D III only
Question 21 Explanation:
Key to be searched 273:
I) 81, 537, 102, 439, 285, 376, 305 is not correct
We cannot go to 376 from 285 as 273 is smaller than 285.
II) 52, 97, 121, 195, 242, 381, 472 is not correct.
We cannot go to 472 from 381 as 273 is smaller than 381.
Question 22
WRONG
A Binary Search Tree (BST) stores values in the range 37 to 573. Consider the following sequence of
keys.
I. 81, 537, 102, 439, 285, 376, 305
II. 52, 97, 121, 195, 242, 381, 472
III. 142, 248, 520, 386, 345, 270, 307
IV. 550, 149, 507, 395, 463, 402, 270
Which of the following statements is TRUE?
I, II and IV are inorder sequences of three different BSTs
II is an inorder sequence of some BST where 121 is the root and 52 is a leaf
Question 22 Explanation:
A: I and IV are not in ascending order
B: If 439 is root, It should be 1st element in preorder
D: IV is a postorder sequence of some BST with 149 as the root, => False
Question 23
CORRECT
How many distinct BSTs can be constructed with 3 distinct keys?
A 4
5
C 6
D 9
Question 23 Explanation:
2n
Cn/(n+1) = 6C3/4 = 5
Question 1
WRONG
The worst case running time to search for an element in a balanced in a binary search tree with n2^n
elements is
(A)
(B)
(C)
(D)
B B
D D
Question 1 Explanation:
Time taken to search an element is [Tex]\Theta (h) [/Tex] where h is the height of Binary Search Tree
(BST). The growth of height of a balanced BST is logerthimic in terms of number of nodes. So the worst
case time to search an element would be [Tex]\Theta (Log(n*2^n)) [/Tex] which is [Tex]\Theta (Log(n) +
Log(2^n)) [/Tex] Which is [Tex]\Theta (Log(n) + n) [/Tex] which can be written as [Tex]\Theta (n) [/Tex].
Question 2
CORRECT
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.
A 2
C 4
D 5
Question 2 Explanation:
AVL trees are binary trees with the following restrictions. 1) the height difference of the children is at most
1. 2) both children are AVL trees Following is the most unbalanced AVL tree that we can get with 7 nodes
a
/ \
/ \
b c
/ \ /
/ \ /
d e g
Question 3
CORRECT
What is the worst case possible height of AVL tree?
2Logn
A Assume base of log is 2
1.44log n
D Theta(n)
Question 3 Explanation:
See http://lcm.csa.iisc.ernet.in/dsa/node112.html
Question 4
CORRECT
Which of the following is AVL Tree?
A
100
/ \
50 200
/ \
10 300
B
100
/ \
50 200
/ / \
10 150 300
/
5
C
100
/ \
50 200
/ \ / \
10 60 150 300
/ \ \
5 180 400
A Only A
A and C
C A, B and C
D Only B
Question 4 Explanation:
A Binary Search Tree is AVL if balance factor of every node is either -1 or 0 or 1. Balance factor of a node
X is [(height of X->left) - (height of X->right)]. In Tree B, the node with value 50 has balance factor 2. That
is why B is not an AVL tree.
Question 5
WRONG
Consider the following AVL tree.
60
/ \
20 100
/ \
80 120
B
100
/ \
60 120
/ \ /
20 70 80
C
80
/ \
60 100
/ \ \
20 70 120
D
80
/ \
60 100
/ / \
20 70 120
A A
B
C
D D
Question 5 Explanation:
Refer following for steps used in AVL insertion. AVL Tree | Set 1 (Insertion)
After insertion of 70, tree becomes following
60
/ \
20 100
/ \
80 120
/
70
We start from 50 and travel up. We keep travelling up till we find an unbalanced node. In above case, we
reach the node 60 and see 60 got unbalanced after insertion and this is Right Left Case. So we need to
apply two rotations
60 60 80
/ \ / \ / \ \
/ \
70 120
Question 6
WRONG
Which of the following is a self-adjusting or self-balancing Binary Search Tree
A Splay Tree
AVL Tree
Question 6 Explanation:
See Splay Tree, AVL Tree and Red Black Tree
Question 7
WRONG
Consider the following left-rotate and right-rotate functions commonly used in self-adjusting BSTs
T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
y x
/\ Right Rotation / \
x T3 - - - > T1 y
/\ <------- /\
T1 T2 Left Rotation T2 T3
Which of the following is tightest upper bound for left-rotate and right-rotate operations.
O(1)
O(Logn)
C O(LogLogn)
D O(n)
Question 7 Explanation:
The rotation operations (left and right rotate) take constant time as only few pointers are being changed
there. Following are C implementations of left-rotate and right-rotate 1
Question 8
WRONG
Which of the following is true
The AVL trees are more balanced compared to Red Black Trees, but they may cause more
Question 8 Explanation:
Red Black Tree with n nodes has height <= 2Log2(n+1) AVL Tree with n nodes has height less than
Log(5(n+2)) - 2. Therefore, the AVL trees are more balanced compared to Red Black Trees, but they
may cause more rotations during insertion and deletion. So if your application involves many frequent
insertions and deletions, then Red Black trees should be preferred. And if the insertions and deletions are
less frequent and search is more frequent operation, then AVL tree should be preferred over Red Black
Tree.
Question 9
WRONG
Which of the following is true about Red Black Trees?
The path from the root to the furthest leaf is no more than twice as long as the path from the root
Question 9 Explanation:
See http://en.wikipedia.org/wiki/Red%E2%80%93black_tree
Question 10
WRONG
Which of the following is true about AVL and Red Black Trees?
In AVL tree insert() operation, we first traverse from root to newly inserted node and then from
newly inserted node to root. While in Red Black tree insert(), we only traverse once from root to
node,
In both AVL and Red Black insert operations, we traverse twiceL first traverse root to newly
C inserted node and then from newly inserted node to root.
Question 10 Explanation:
Refer Red Black Tree Insertion and AVL Tree Insertion
Question 11
WRONG
What is the worst case possible height of Red-Black tree? Assume base of Log as 2 in all options
2Log(n+1)
1.44 Logn
C 4Logn
Question 11 Explanation:
Refer Wiki Page of Red-Black Tree
Question 12
CORRECT
Is the following statement valid? A Red-Black Tree which is also a perfect Binary Tree can have all black
nodes
Yes
B No
Question 12 Explanation:
A perfect BST with all black nodes doesn't violate any of the Red-Black tree properties.
Question 13
WRONG
Which of the following operations are used by Red-Black trees to maintain balance during
insertion/deletion?
a) Recoloring of nodes
Only a
B Only b
Both a and b
D Neither a nor b
Question 13 Explanation:
Both recoloring and rotation operations are used during insertion and deletion.
Question 14
CORRECT
A program takes as input a balanced binary search tree with n leaf nodes and computes the value of a
function g(x) for each node x. If the cost of computing g(x) is min{no. of leaf-nodes in left-subtree of x, no.
of leaf-nodes in right-subtree of x} then the worst-case time complexity of the program is
A (n)
(nLogn)
C (n2)
D (n2log n)
Question 14 Explanation:
The recurrence relation for the recursive function is
= 4 * T(N/2) + 3(n/2)
Where i = lg(N)
= lg((2n - 1) / 2)
O((2*i - 1) * (n/2))
O(n * ln(n))
Source: http://www.nid.iitkgp.ernet.in/DSamanta/courses/IT60101_2/Archives/Assignment-%20IC
%20Binary%20Trees%20Solutions.pdf
Question 15
WRONG
Which of the following is TRUE?
The cost of searching an AVL tree is (log n) but that of a binary search tree is O(n)
The cost of searching an AVL tree is (log n) but that of a complete binary tree is (n log n)
C The cost of searching a binary search tree is O (log n ) but that of an AVL tree is (n)
D The cost of searching an AVL tree is (n log n) but that of a binary search tree is O(n)
Question 15 Explanation:
AVL tree is a balanced tree.
AVL tree's time complexity of searching = (logn)
But a binary search tree, may be skewed tree, so in worst case BST searching time = (n)
Question 16
WRONG
Given two Balanced binary search trees, B1 having n elements and B2 having m elements, what is the
time complexity of the best known algorithm to merge these trees to form another balanced binary tree
containing m+n elements ?
O(m+n)
O(mlogn)
C O(nlogm)
D O(m2 + n2)
Question 16 Explanation:
O(m+n) as we can first perform inorder on both the trees and store them in two separate arrays. Now we
have two sorted sequences and we can merge them in O(m+n) using standard merge algorithm and on
the final sorted array we can use the binary search to create the tree using Recursion. Recursively adding
middle element at the root and repeating the same process for left and right subarrays.
Graph
Question 1
WRONG
Which of the following is an advantage of adjacency list representation over adjacency matrix
representation of a graph?
DFS and BSF can be done in O(V + E) time for adjacency list representation. These operations
take O(V^2) time in adjacency matrix representation. Here is V and E are number of vertices and
edges respectively.
C Adding a vertex in adjacency list representation is easier than adjacency matrix representation.
Question 1 Explanation:
See http://www.geeksforgeeks.org/graph-and-its-representations/
Question 2
WRONG
The degree sequence of a simple graph is the sequence of the degrees of the nodes in the graph in
decreasing order. Which of the following sequences can not be the degree sequence of any graph? I. 7,
6, 5, 4, 4, 3, 2, 1 II. 6, 6, 6, 6, 3, 3, 2, 2 III. 7, 6, 6, 4, 4, 3, 2, 2 IV. 8, 7, 7, 6, 4, 2, 1, 1
I and II
B III and IV
C IV only
II and IV
Graph
Discuss it
Question 2 Explanation:
See Question 3 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-25/ for explanation.
Question 3
WRONG
The time complexity of computing the transitive closure of a binary relation on a set of n elements is
known to be:
O(n)
B O(nLogn)
C O(n ^ (3/2))
O(n^3)
Graph
Discuss it
Question 3 Explanation:
See question 3 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-22/
Question 4
WRONG
The most efficient algorithm for finding the number of connected components in an undirected graph on n
vertices and m edges has time complexity. (A) (n) (B) (m) (C) (m + n) (D) (mn)
A A
B
C
D D
Graph
Discuss it
Question 4 Explanation:
Connected components can be found in O(m + n) using Tarjan's algorithm. Once we have connected
components, we can count them.
Question 5
CORRECT
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 CS
2001)
Graph
Discuss it
Question 5 Explanation:
d(r, u) and d(r, v) will be equal when u and v are at same level, otherwise d(r, u) will be less than d(r, v)
Question 6
CORRECT
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!
2^(n(n-1)/2)
Graph
Discuss it
Question 6 Explanation:
In an undirected graph, there can be maximum n(n-1)/2 edges. We can choose to have (or not have) any
of the n(n-1)/2 edges. So, total number of undirected graphs with n vertices is 2^(n(n-1)/2).
Question 7
WRONG
Which of the following statements is/are TRUE for an undirected graph? P: Number of odd degree
vertices is even Q: Sum of degrees of all vertices is even
A P Only
B Q Only
Both P and Q
Neither P nor Q
Graph
Discuss it
Question 7 Explanation:
P is true for undirected graph as adding an edge always increases degree of two vertices by 1. Q is true:
If we consider sum of degrees and subtract all even degrees, we get an even number because every
edge increases the sum of degrees by 2. So total number of odd degree vertices must be even.
Question 8
WRONG
Consider an undirected random graph of eight vertices. The probability that there is an edge between a
pair of vertices is 1/2. What is the expected number of unordered cycles of length three?
A 1/8
B 1
7
8
Graph
Discuss it
Question 8 Explanation:
A cycle of length 3 can be formed with 3 vertices. There can be total 8C3 ways to pick 3 vertices from 8.
The probability that there is an edge between two vertices is 1/2. So expected number of unordered
cycles of length 3 = (8C3)*(1/2)^3 = 7
Question 9
WRONG
Given an undirected graph G with V vertices and E edges, the sum of the degrees of all vertices is
A E
2E
V
D 2V
Graph
Discuss it
Question 9 Explanation:
Since the given graph is undirected, every edge contributes as 2 to sum of degrees. So the sum of
degrees is 2E.
Question 10
WRONG
How many undirected graphs (not necessarily connected) can be constructed out of a given set V = {v1,
v2, ... vn} of n vertices?
A n(n-1)/2
B 2n
n!
2n(n-1)/2
Graph GATE-CS-2001
Discuss it
Question 10 Explanation:
There are total n*(n-1)/2 possible edges. For every edge, there are to possible options, either we pick it or
don't pick. So total number of possible graphs is 2 n(n-1)/2.
Question 11
WRONG
What is the maximum number of edges in an acyclic undirected graph with n vertices?
n-i
B n
C n+1
2n-1
Graph GATE-IT-2004
Discuss it
Question 11 Explanation:
n * (n - 1) / 2 when not cyclic. An acyclic graph with the maximum number of edges is actually a spanning
tree and therefore, correct answer is n-1 edges. So Answer is A
Question 12
WRONG
Let G be a weighted undirected graph and e be an edge with maximum weight in G. Suppose there is a
minimum weight spanning tree in G containing the edge e. Which of the following statements is always
TRUE?
There exists a cutset in G having all edges of maximum weight.
Question 12 Explanation:
Background : Given a connected and undirected graph, a spanning tree of that graph is a subgraph that
is a tree and connects all the vertices together.
1. A spanning tree has exactly V - 1 edges.
2. A single graph can have many different spanning trees. A minimum spanning tree (MST) or
minimum weight spanning tree for a weighted, connected and undirected graph is a
spanning tree with weight less than or equal to the weight of every other spanning tree. The
weight of a spanning tree is the sum of weights given to each edge of the spanning tree.
3. There can be more that one possible spanning trees of a graph. For example, the graph
in this question has 6 possible spanning trees.
4. MST has lightest edge of every cutset. Remember Prim's algorithm which basically picks
the lightest edge from every cutset.
Choices of this question : a) There exists a cutset in G having all edges of maximum weight : This
is correct. If there is a heaviest edge in MST, then there exist a cut with all edges with weight equal to
heavies edge. See point 4 discussed in above background.
b) There exists a cycle in G having all edges of maximum weight : Not always TRUE. The cutset of
heaviest edge may contain only one edge. In fact there may be overall one edge of heavies weight which
is part of MST (Consider a graph with two components which are connected by only one edge and this
edge is the heavies) c) Edge e cannot be contained in a cycle. Not Always True. The curset may form
cycle with other edges. d) All edges in G have the same weight Not always True. As discussed in option
b, there can be only one edge of heaviest weight.
Question 13
WRONG
Q84 Part_B
A sink in a directed graph is a vertex i such that there is an edge from every vertex j i to i and there is no
edge from i to any other vertex. A directed graph G with n vertices is represented by its adjacency matrix
A, where A[i] [j] = 1 if there is an edge directed from vertex i to j and 0 otherwise. The following algorithm
determines whether there is a sink in the graph G.
i=0
do {
j = i + 1;
if (j < n) E2;
flag = 1;
for (j = 0; j < n; j++)
flag = 0;
if (flag)
printf("Sink exists");
else
(!A[i][j] | | A[j][i])
(A[i][j] | | !A[j][i])
Graph Gate IT 2005
Discuss it
Question 13 Explanation:
Below explanation is for Previous Part of this question: For vertex i to be a sink, there should be no
The above pseudo code checks every vertex i for sink, starting from i = 0. It basically checks every vertex
j after i for being a sink. The trick in pseudo code is, it doesn't check for j smaller than i. The i picked by
this loop may not be sink. It basically makes sure that we don't ignore a potential sink. The check whether
i is actually a sink or not is done later after do while loop. Vertex i is a potential sink while A[i][j] is zero
Thus, E1 : !A[i][j] If the above condition is false, then i is not a sink. All j < i can also not be a sink
because there is no edge from i to j. Now, the next potential sink can be j. So, E2 : i = j Explanation for
this question The following pseudo code basically checks if the potential sink picked by the code above
is actually a sink or not.
flag = 1;
flag = 0;
flag equals to 0 means i is not a sink. The code sets the flag 0 as soon as it finds out that i is not a
sink.
A node i is not a sink if either of the following
two conditions become true for any j not equal to i.
A[i][j] is 1 for any j
OR
A[j][i] is 0 for any j
E3 : (A[i][j] | | !A[j][i]) Therefore option D is correct
Question 14
CORRECT
Q85 Part_A Consider a simple graph with unit edge costs. Each node in the graph represents a router.
Each node maintains a routing table indicating the next hop router to be used to relay a packet to its
destination and the cost of the path to the destination through that router. Initially, the routing table is
empty. The routing table is synchronously updated as follows. In each updation interval, three tasks are
performed.
1. A node determines whether its neighbours in the graph are accessible. If so, it sets the tentative
cost to each accessible neighbour as 1. Otherwise, the cost is set to .
2. From each accessible neighbour, it gets the costs to relay to other nodes via that neighbour (as
the next hop).
3. Each node updates its routing table based on the information received in the previous two steps
by choosing the minimum cost.
For the graph given above, possible routing tables for various nodes after they have stabilized, are shown
in the following options. Identify the correct table.
1) Table for node A
A - -
B B 1
C C 1
D B 3
E C 3
F C 4
Table for node C
A A 1
B B 1
2)
C - -
D D 1
E E 1
F E 3
Table for node B
A A 1
B - -
3)
C C 1
D D 1
E C 2
F D 2
Table for node D
A B 3
B B 1
4)
C C 1
D - -
E E 1
F F 1
A A
B B
D D
Question 14 Explanation:
This solution is contributed by Sandeep Pandey.
Question 15
WRONG
Q85 Part_B Consider a simple graph with unit edge costs. Each node in the graph represents a router.
Each node maintains a routing table indicating the next hop router to be used to relay a packet to its
destination and the cost of the path to the destination through that router. Initially, the routing table is
empty. The routing table is synchronously updated as follows. In each updation interval, three tasks are
performed.
1. A node determines whether its neighbours in the graph are accessible. If so, it sets the tentative
cost to each accessible neighbour as 1. Otherwise, the cost is set to .
2. From each accessible neighbour, it gets the costs to relay to other nodes via that neighbour (as
the next hop).
3. Each node updates its routing table based on the information received in the previous two steps
by choosing the minimum cost.
For the graph given above, possible routing tables for various nodes after they have stabilized, are shown
in the following options. Identify the correct table.
Table for node A
A - -
B B 1
1)
C C 1
D B 3
E C 3
F C 4
Table for node C
A A 1
B B 1
2)
C - -
D D 1
E E 1
F E 3
3)Table for node B
A A 1
B - -
C C 1
D D 1
E C 2
F D 2
Table for node D
A B 3
B B 1
4)
C C 1
D - -
E E 1
F F 1
Continuing from the earlier problem, suppose at some time t, when the costs have stabilized, node A goes
down. The cost from node F to node A at time (t + 100) is
>100 but finite
C 3
Question 16
CORRECT
The cyclomatic complexity of the flow graph of a program provides
an upper bound for the number of tests that must be conducted to ensure that all statements have
A been executed at most once
a lower bound for the number of tests that must be conducted to ensure that all statements have
B been executed at most once
an upper bound for the number of tests that must be conducted to ensure that all statements have
Question 17
WRONG
What is the largest integer m such that every simple connected graph with n vertices and n edges
contains at least m different spanning trees?
A 1
2
3
D n
Question 17 Explanation:
A graph is connected iff all nodes can be traversed from each node. For a graph with n nodes, there will
be n-1 minimum number of edges.
Given that there are n edges, that means a cycle is there in the graph.
The simplex graph with these conditions may be:
Now we can make a different spanning tree by removing one edge from the cycle, one at a time.
Minimum cycle length can be 3, So, there must be atleast 3 spanning trees in any such Graph.
Question 18
CORRECT
For the undirected, weighted graph given below, which of the following sequences of edges represents a
correct execution of Prim's algorithm to construct a Minimum Spanning Tree?
A (a, b), (d, f), (f, c), (g, i), (d, a), (g, h), (c, e), (f, h)
B (c, e), (c, f), (f, d), (d, a), (a, b), (g, h), (h, f), (g, i)
(d, f), (f, c), (d, a), (a, b), (c, e), (f, h), (g, h), (g, i)
D (h, g), (g, i), (h, f), (f, c), (f, d), (d, a), (a, b), (c, e)
Question 18 Explanation:
In prims algorithm we start with any node and keep on exploring minimum cost neighbors of nodes
already covered.
Question 19
WRONG
Consider a directed graph with n vertices and m edges such that all edges have same edge weights. Find
the complexity of the best known algorithm to compute the minimum spanning tree of the graph?
O(m+n)
B O(m logn)
O(mn)
D O(n logm)
Question 19 Explanation:
Its a special case in which all edge weights are equal, so dfs would work and resultant depth first tree
would be the spanning tree. So the answer would be O(m+n).
Question 20
CORRECT
You are given a graph containing n vertices and m edges and given that the graph doesnt contain cycle
of odd length. Time Complexity of the best known algorithm to find out whether the graph is bipartite or
not is ?
A O(m+n)
O(1)
C O(mn)
D O(n2)
Question 20 Explanation:
It is by definition that a graph is bipartite iff it does not contain odd length cycles. So the answer is O(1).
For more background reading, check this
linkhttps://proofwiki.org/wiki/Graph_is_Bipartite_iff_No_Odd_Cycles
Question 21
WRONG
Let G be a simple graph with 20 vertices and 8 components. If we delete a vertex in G, then number of
components in G should lie between ____.
A 8 and 20
8 and 19
7 and 19
D 7 and 20
Question 21 Explanation:
Case 1: If the vertex we are deleting from G is an isolated vertex, which is a component by itself, then
number of components in G becomes 7.
Case 2: If G is a start Graph, then by deleting the cut vertex of G, we get 19 components.
Hence, number of components in G should lie between 7 and 19.
Hash
Question 1
WRONG
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?
Question 1 Explanation:
See question 2 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-24/
Question 2
WRONG
How many different insertion sequences of the key values using the same hash function and linear
probing will result in the hash table shown above?
A 10
20
30
D 40
Hash
Discuss it
Question 2 Explanation:
See question 3 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-24/
Question 3
WRONG
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?
A A
B
C
D D
Hash
Discuss it
Question 3 Explanation:
To get the idea of open addressing concept, you can go through below lines from Wikipedia . Open
addressing, or closed hashing, is a method of collision resolution in hash tables. With this method a hash
collision is resolved by probing, or searching through alternate locations in the array (the probe sequence)
until either the target record is found, or an unused array slot is found, which indicates that there is no
such key in the table. Well known probe sequences include: linear probing in which the interval between
probes is fixed--often at 1. quadratic probing in which the interval between probes increases linearly
(hence, the indices are described by a quadratic function). double hashing in which the interval between
probes is fixed for each record but is computed by another hash function.
Question 4
WRONG
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.
A 8, _, _, _, _, _, 10
1, 8, 10, _, _, _, 3
1, _, _, _, _, _,3
D 1, 10, 8, _, _, _, 3
Hash
Discuss it
Question 4 Explanation:
Please see http://lcm.csa.iisc.ernet.in/dsa/node38.html for closed hashing and probing. Let us put values
1, 3, 8, 10 in the hash of size 7. Initially, hash table is empty
- - - - - - -
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 1 is 0, so let us put the value at 0
1 - - - - - -
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 3 is 6, so let us put the value at 6
1 - - - - - 3
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 8 is 0, but 0 is already occupied, let us put the value(8) at next
available space(1)
1 8 - - - - 3
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 10 is 6, but 6 is already occupied, let us put the value(10) at next
available space(2)
1 8 10 - - - 3
0 1 2 3 4 5 6
Question 5
WRONG
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? 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 (GATE CS 2004)
i only
B ii only
i and ii only
D iii or iv
Hash
Discuss it
Question 5 Explanation:
Hash function given is mod(10).
9679, 1989 and 4199 all these give same hash value i.e 9
Question 6
WRONG
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?
(97 97 97)/1003
(99 98 97)/1003
C (97 96 95)/1003
Question 6 Explanation:
Simple Uniform hashing function is a hypothetical hashing function that evenly distributes items into the
slots of a hash table. Moreover, each item to be hashed has an equal probability of being placed into a
slot, regardless of the other elements already placed. (Source: https://en.wikipedia.org/wiki/SUHA_
%28computer_science%29).
Probability that the first 3 slots are unfilled after the first 3 insertions =
Question 7
WRONG
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?
Question 7 Explanation:
Since mod 10 is used, the last digit matters. If you do cube all numbers from 0 to 9, you get following
Number Cube Last Digit in Cube
0 0 0
1 1 1
2 8 8
3 27 7
4 64 4
5 125 5
6 216 6
7 343 3
8 512 2
9 729 9
Therefore all numbers from 0 to 2020 are equally divided in 10 buckets. If we make a table for square, we
don't get equal distribution. In the following table. 1, 4, 6 and 9 are repeated, so these buckets would have
more entries and buckets 2, 3, 7 and 8 would be empty.
Number Square Last Digit in Cube
0 0 0
1 1 1
2 4 4
3 9 9
4 16 6
5 25 5
6 36 6
7 49 9
8 64 4
9 81 1
Question 8
WRONG
Given a hash table T with 25 slots that stores 2000 elements, the load factor for T is __________
80
B 0.0125
8000
D 1.25
Question 8 Explanation:
load factor = (no. of elements) / (no. of table slots) = 2000/25 = 80
Question 9
CORRECT
Which of the following statement(s) is TRUE?
1. A hash function takes a message of arbitrary length and generates a fixed length code.
2. A hash function takes a message of fixed length and generates a code of variable length.
3. A hash function may give the same hash value for distinct messages.
A I only
Question 9 Explanation:
Hash function is defined as any function that can be used to map data of arbitrary size
of data to a fixed size data.. The values returned by a hash function are called hash
values, hash codes, digests, or simply hashes : Statement 1 is correct Yes, it is
possible that a Hash Function maps a value to a same location in the memmory that's
why collision occurs and we have different technique to handle this problem : Statement
3 is coorect. eg : we have hash function, h(x) = x mod 3 Acc to Statement 1, no matter
what the value of 'x' is h(x) results in a fixed mapping location. Acc. to Statement 3, h(x)
can result in same mapping mapping location for different value of 'x' e.g. if x = 4 or x =
7 , h(x) = 1 in both the cases, although collision occurs. This solution is contributed by Mohit
Gupta.
Question 10
WRONG
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.
A 5
B 6
7
10
Hash Gate IT 2007
Discuss it
Question 10 Explanation:
For each entry probability of collision is 1/20 {as possible total spaces =20, and an entry will go into only 1
place}
Say after inserting x values probability becomes
(1/20).x =
X=10
Array
Question 1
WRONG
A program P reads in 500 integers in the range [0..100] exepresenting 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 CS 2005)
An array of 50 numbers
An array of 100 numbers
Array
Discuss it
Question 1 Explanation:
See question 1 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-22/
Question 2
WRONG
Which of the following operations is not O(1) for an array of sorted data. You may assume that array
elements are distinct.
Find the ith largest element
Delete an element
Array
Discuss it
Question 2 Explanation:
The worst case time complexity for deleting an element from array can become O(n).
Question 3
WRONG
The minimum number of comparisons required to determine if an integer appears more than n/2 times in
a sorted array of n integers is
(A) (n)
(B) (logn)
(C) (log*n)
(D) (n)
A
B
C C
D D
Question 3 Explanation:
The Best way to find out whether an integer appears more than n/2 times in a sorted array(Ascending
Order) of n integers, would be binary search approach. 1. The First occurence of an element can be
found out in O(log(n)) time using divide and conquer technique,lets say it is i. 2. The Last occurrence of
an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is j. 3. Now
number of occuerence of that element(count) is (j-i+1). Overall time complexity = log n +log n +1 =
O(logn) See Check for Majority Element in a sorted array This solution is contributed by Nirmal
Bharadwaj
Question 4
WRONG
Let A be a square matrix of size n x n. Consider the following program. What is the expected output?
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]);
Run on IDE
The matrix A itself
B Transpose of matrix A
C Adding 100 to the upper diagonal elements and subtracting 100 from diagonal elements of A
Question 4 Explanation:
If we take look at the inner statements of first loops, we can notice that the statements swap A[i][j] and A[j]
[i] for all i and j. Since the loop runs for all elements, every element A[l][m] would be swapped twice, once
for i = l and j = m and then for i = m and j = l. Swapping twice means the matrix doesnt change.
Source: http://www.geeksforgeeks.org/data-structures-algorithms-set-34/
Question 5
CORRECT
An algorithm performs (logN) find operations, N insert operations, (logN) 1/2 operations, and
1/2
(logN)1/2 decrease-key operations on a set of data items with keys drawn from a linearly ordered set. For a
delete operation, a pointer is provided to the record that must be deleted. For the decrease-key operation,
a pointer is provided to the record that has its key decreased. Which one of the following data structures is
the most suited for the algorithm to use, if the goal is to achieve the best total asymptotic complexity
considering all the operations?
Unsorted array
B Min-heap
C Sorted array
Question 5 Explanation:
The time complexity of insert in unsorted array is O(1), O(Logn) in Min-Heap, O(n) in sorted array and
sorted DLL.
1. For unsorted array, we can always insert an element at end and do insert in O(1) time
2. For Min Heap, insertion takes O(Log n) time. Refer Binary Heap operations for details.
3. For sorted array, insert takes O(n) time as we may have to move all elements worst case.
4. For sorted doubly linked list, insert takes O(n) time to find position of element to be
inserted.
Since number of insertion operations is asymptotically higher, unsorted array is preferred.
Question 6
WRONG
Consider an array consisting of ve and +ve numbers. What would be the worst time comparisons an
algorithm can take in order to segregate the numbers having same sign altogether i.e all +ve on one side
and then all -ve on the other ?
N-1
B N
N+1
D (N*(N-1))/2
Array GATE 2017 Mock
Discuss it
Question 6 Explanation:
Here we can use the partition algorithm of quick sort for segregation and answer will be N-1.
Choose the first element as pivot whatever may be its sign we dont care and keep an extra index at pivot
position .
Misc
Question 1
WRONG
Which data structure is used for balancing of symbols?
Stack
Queue
C Tree
D Graph
Misc
Discuss it
Question 1 Explanation:
Stack is used for balancing of symbols. This is extensively used by the compiler to check for missing or
additional symbols. The start of the symbol(like (, [, {) are pushed to the stack. When the end of the
symbol(like ), \, }) are encountered, it is matched with the corresponding peek element of the stack. If the
match is found, the element is popped, else error is flashed.
Question 2
CORRECT
Which data structure is used in redo-undo feature?
Stack
B Queue
C Tree
D Graph
Misc
Discuss it
Question 2 Explanation:
Stack data structure is most suitable to implement redo-undo feature. This is because the stack is
implemented with LIFO(last in first out) order which is equivalent to redo-undo feature i.e. the last re-do is
undo first.
Question 3
WRONG
Which data structure is most efficient to find the top 10 largest items out of 1 million items stored in file?
Min heap
Max heap
C BST
D Sorted array
Misc
Discuss it
Question 3 Explanation:
Min heap of size 10 is sufficient to find the top 10 largest items. The algorithm can be given as follows: 1.
Create the min heap with first 10 items. 2. For each remaining item, check if 2.1 The item is greater than
the item stored in the head of the min heap. 2.1.1 If yes, replace it with this new item. Balance the min
heap. 2.1.2 If no, do nothing. At last, the min heap will contain the top 10 largest items.
Question 4
WRONG
The best data structure to check whether an arithmetic expression has balanced parentheses is a (GATE
CS 2004)
queue
stack
C tree
D list
Misc
Discuss it
Question 4 Explanation:
There are three types of parentheses [ ] { } (). Below is an arbit c code segment which has parentheses of
all three types. 1 Stack is a straightforward choice for checking if left and right parentheses are balanced.
Here is a algorithm to do the same. 1
Question 5
CORRECT
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.
o Delection of the smallest element
Which of the following data structures can be used for this purpose?
Misc
Discuss it
Question 5 Explanation:
A self-balancing balancing binary search tree containing n items allows the lookup, insertion, and removal
of an item in O(log n) worst-case time. Since it's a BST, we can easily find out minimum element in
O(nlogn). See our post http://geeksforgeeks.org/?p=1333 for details. Since Heap is a balanced binary tree
(or almost complete binary tree), insertion complexity for heap is O(logn). Also complexity to get minimum
in a min heap is O(logn) because removal of root node causes a call to heapify (after removing the first
element from the array) to maintain the heap tree property. But a heap cannot be used for the above
purpose as the question says - insert an element if it is not already present. For a heap, we cannot find
out in O(logn) if an element is present or not. Thanks to game for providing the correct solution.
Question 6
WRONG
The most appropriate matching for the following pairs
X: depth first search 1: heap
Y: breadth-first search 2: queue
Z: sorting 3: stack
is (GATE CS 2000):
A X1 Y2 Z-3
X3 Y1 Z-2
X3 Y2 Z-1
D X2 Y3 Z-1
Misc
Discuss it
Question 6 Explanation:
Stack is used for Depth first Search Queue is used for Breadth First Search Heap is used for sorting
Question 7
WRONG
Which among the following data structures is best suited for storing very large numbers (numbers that
cannot be stored in long long int). Following are the operations needed for these large numbers.
Array
Linked List
C Binary Tree
D Hash
Misc
Discuss it
Question 7 Explanation:
The only two choices that make sense are Array and Linked List. Since array sizes are limited, they can
create problems for following operations. X = X*Y where X and Y are very large numbers.
Question 8
WRONG
Which data structure is best suited for converting recursive implementation to iterative implementation of
an algorithm?
Queue
Stack
C Tree
D Graph
Misc
Discuss it
Question 8 Explanation:
Since function calls are executed in Last In First Out order, stack is the data structure for converting
recursive to iterative implementation.
Question 9
CORRECT
Consider a situation where a client receives packets from a server. There may be differences in speed of
the client and the server. Which data structure is best suited for synchronization?
Queue
C Stack
D Priority Queue
Misc
Discuss it
Question 9 Explanation:
Since packets need to be processed in First In First Out order, a queue can be used for synchronization.
Question 10
CORRECT
Which of the following data structures is best suited for efficient implementation of priority queue?
A Array
B Linked List
Heap
D Stack
Misc
Discuss it
Question 10 Explanation:
Refer http://geeksquiz.com/binary-heap/
Question 11
WRONG
Which data structure in a compiler is used for managing information about variables and their attributes?
Symbol table
Semantic stack
D Parse Table
Question 11 Explanation:
Symbol table is a data structure used by a language translator such as a compiler or interpreter, where
each identifier in a program's source code is associated with information relating to its declaration or
appearance in the source, such as its type, scope level and sometimes its location
(Source: http://en.wikipedia.org/wiki/Symbol_table)
Question 12
CORRECT
An Abstract Data Type (ADT) is:
A Same as an abstract class
A data type type for which only the operations defined on it can be used, but none else
Misc GATE-CS-2005
Discuss it
Question 12 Explanation:
See http://en.wikipedia.org/wiki/Abstract_data_type
Question 13
WRONG
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.
o Delection of the smallest element
Which of the following data structures can be used for this purpose?
A heap can be used but not a balanced binary search tree
A balanced binary search tree can be used but not a heap
Misc GATE-CS-2003
Discuss it
Question 13 Explanation:
First well discuss about heap and balanced bst and its time complexities for basic operations like
insertion, deletion, find. Heap:- Let us consider it as min heap 1) Insertion: O(logn) 2) Delete Min: O(logn)
(Just replace root with INT_MAX and heapify) 3) Find: O(n) Balanced BST:- 1) Insertion: O(logn) 2)
Delete Min: O(logn) 3) Find: O(logn) Statement 1: 1) Deletion of smallest element can be done in O(logn)
in both data structures Statement 2: 1) Insertion of an element if it is not already present in the set In
heap, we can perform this operation in O(n) because we have to perform linear search here, where as in
BST we can perform this in O(logn) See Question 4 of http://www.geeksforgeeks.org/data-structures-and-
algorithms-set-3/ This solution is contributed by Anil Saikrishna Devarasetty
Question 14
WRONG
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.
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 ____________
2
5
C 6
D 18
Question 14 Explanation:
Initially
1 2 5 14
3 4 6 23
10 12 18 25
31
When 1 is removed, it is replaced by the smallest adjacent which is 2.
2 2 5 14
3 4 6 23
10 12 18 25
31
When 2 is moved in place of 1, it is replaced by smallest adjacent which is 4
2 4 5 14
3 4 6 23
10 12 18 25
31
When 4 is moved in place of 2, it is replaced by smallest adjacent which is 6
2 4 5 14
3 6 6 23
10 12 18 25
31
When 6 is moved in place of 4, it is replaced by smallest adjacent which is 18.
2 4 5 14
3 6 18 23
10 12 18 25
31
When 18 is moved in place of 6, it is replaced by smallest adjacent which is 25.
2 4 5 14
3 6 18 23
10 12 25 25
31
When 25 is moved in place of 18, it is replaced by smallest adjacent which is .
2 4 5 14
3 6 18 23
10 12 25
31
Question 15
WRONG
A -1
1
0
B and B+ Trees
Question 1
CORRECT
Consider a B+-tree in which the maximum number of keys in a node is 5. What is the minimum number of
keys in any non-root node? (GATE CS 2010)
A 1
C 3
D 4
B and B+ Trees
Discuss it
Question 1 Explanation:
Since the maximum number of keys is 5, maximum number of children a node can have is 6. Bydefinition
of B Tree, minimum children that a node can have would be 6/2 = 3. Therefore, minimum number of keys
that a node can have becomes 2 (3-1).
Question 2
WRONG
Which one of the following is a key factor for preferring B-trees to binary search trees for indexing
database relations?
Question 2 Explanation:
A disk block contains fairly large number of keys. Unlike BST where each node contains only one key, B-
Tree is designed to contain large number of keys so that tree height is small.
Question 3
WRONG
B+ trees are preferred to binary trees in databases because (GATE CS 2000)
C Disk data transfer rates are much less than memory data transfer rates
Question 3 Explanation:
Disk access is slow and B+ Tree provide search in less number of disk hits. This is primarily because
unlike binary seach trees, B+ trees have very high fanout (typically on the order of 100 or more), which
reduces the number of I/O operations required to find an element in the tree.
Question 4
WRONG
Which of the following is FALSE about B/B+ tree
B/B+ trees grow upward while Binary Search Trees grow downward.
Time complexity of search operation in B/B+ tree is better than Red Black Trees in general.
C Number of child pointers in a B/B+ tree node is always equals to number of keys in it plus one.
A B/B+ tree is defined by a term minimum degree. And minimum degree depends on hard disk
D block size, key and address sizes.
B and B+ Trees
Discuss it
Question 4 Explanation:
Asymptotic time complexity of both is of order logn.
Question 5
WRONG
A B-tree of order 4 is built from scratch by 10 successive insertions. What is the maximum number of
node splitting operations that may take place?
A 3
4
5
D 6
Question 5 Explanation:
Insertion of 3 keys
10 20 30
30
/ \
10*20 40
/ \
5*10*20 40
8*30
/ | \
5 10*20 40
8*30
/ | \
5 10*15*20 40
8*12*30
/ / \ \
5 10 15*20 40
8*12*30
/ / \ \
5 10 15*17*20 40
Insertion of 10th key (4th and 5th Splits)
12
/ \
8 15*30
/ \ / | \
5 10 13 17*20 40
Question 6
WRONG
The order of a leaf node in a tree B+ ? is the maximum number of (value, data record pointer) pairs it can
hold. Given that the block size is 1K bytes, data record pointer is 7 bytes long, the value field is 9 bytes
long and a block pointer is 6 bytes long, what is the order of the leaf node?
63
B 64
67
D 68
Question 6 Explanation:
Disk Block size = 1024 bytes
Let order of leaf be m. A leaf node in B+ tree contains at most m record pointers, at most m values, and
one disk block pointer. r*m + V*m + p <= 1024 16m <= 1018 m =< 63
Question 7
WRONG
The order of an internal node in a B+ tree index is the maximum number of children it can have. Suppose
that a child pointer takes 6 bytes, the search field value takes 14 bytes, and the block size is 512 bytes.
What is the order of the internal node?
A 24
25
26
D 27
Question 7 Explanation:
Please comment below if you find anything wrong in the above post.
Question 8
CORRECT
Consider the following 2-3-4 tree (i.e., B-tree with a minimum degree of two) in which each data item is a
letter. The usual alphabetical ordering of letters is used in constructing the
A)
B)
C)
A A
C C
D D
Question 8 Explanation:
Since the given B tree is 2-3-4 tree, there can be at-most 4 children or 3 keys. In B Tree insertion, we start
from root and traverse till the leaf node where key is to be inserted. While traversing, if we find a a node
which full, we split it. When we insert G, we find root itself is full, so we split it. When we come down to
leftmost leaf, we find that the leaf is also full, so we split the leaf also.
Question 9
WRONG
A B+ -tree index is to be built on the Name attribute of the relation STUDENT. Assume that all student
names are of length 8 bytes, disk block are size 512 bytes, and index pointers are of size 4 bytes. Given
this scenario, what would be the best choice of the degree (i.e. the number of pointers per node) of the B+
-tree?
A 16
B 42
43
44
B and B+ Trees GATE-CS-2002
Discuss it
Question 9 Explanation:
Size of 1 record = 8 + 4 = 12
(N - 1) 12 + 4 = 512
12N - 12 + 4 = 512
16N = 1009
N = 43.3333
Question 10
WRONG
With reference to the B+ tree index of order 1 shown below, the minimum number of nodes (including the
root node) that must be fetched in order to satisfy the following query: Get all records with a search key
greater than or equal to 7 and less than 15 is ________
A 4
5
6
D 7
Question 10 Explanation:
We can get all values in range from 7 to 59 by accessing 5 nodes.
1) First search 7 in a leaf node.
Question 11
WRONG
Consider B+ tree in which the search key is 12 bytes long, block size is 1024 bytes, record pointer is 10
bytes long and block pointer is 8 bytes long. The maximum number of keys that can be accommodated in
each non-leaf node of the tree is
A 49
50
51
D 52
Question 11 Explanation:
Let m be the order of B+ tree
m <= 51
Question 12
WRONG
A B-Tree used as an index for a large database table has four levels including the root node. If a new key
is inserted in this index, then the maximum number of nodes that could be newly created in the process
are:
5
B 4
C 3
2
B and B+ Trees Gate IT 2005
Discuss it
Question 12 Explanation:
Number of children of a node is equal to the number of keys in it plus 1. Given tree has 4 levels, the tree
will be increased with one more level if a new key is inserted.
Question 13
WRONG
B+ Trees are considered BALANCED because
the lengths of the paths from the root to all leaf nodes are all equal.
B the lengths of the paths from the root to all leaf nodes differ from each other by at most 1.
the number of children of any two non-leaf sibling nodes differ by at most 1.
Question 13 Explanation:
In both B Tree and B+ trees, depth (length of root to leaf paths) of all leaf nodes is same. This is made
sure by the insertion and deletion operations. In these trees, we do insertions in a way that if we have
increase height of tree after insertion, we increase height from root. This is different from BST where
height increases from leaf nodes. Similarly, if we have to decrease height after deletion, we move the root
one level down. This is also different from BST which shrinks from bottom. The above ways of insertion
and deletion make sure that depth of every leaf node is same. You can refer below links for more
details. IIT Delhi Video Lecture B Tree Introduction B Tree Insertion B Tree Deletion
Heap
Question 1
WRONG
What is the time complexity of Build Heap operation. Build Heap is used to build a max(or min) binary
heap from a given array. Build Heap is used in Heap Sort as a first step for sorting.
A O(nLogn)
O(n^2)
C O(Logn)
O(n)
Heap
Discuss it
Question 1 Explanation:
Following is algorithm for building a Heap of an input array A.
BUILD-HEAP(A)
heapsize := size(A);
do HEAPIFY(A, i);
end for
END
Although the worst case complexity looks like O(nLogn), upper bound of time complexity is O(n). See
following links for the proof of time
complexity.http://www.dgp.utoronto.ca/people/JamesStewart/378notes/08buildheap/
Question 2
CORRECT
Suppose we are sorting an array of eight integers using heapsort, and we have just finished some heapify
(either maxheapify or minheapify) operations. The array now looks like this: 16 14 15 10 12 27 28 How
many heapify operations have been performed on root of heap?
A 1
C 3 or 4
D 5 or 6
Question 2 Explanation:
In Heapsort, we first build a heap, then we do following operations till the heap size becomes 1. a) Swap
the root with last element b) Call heapify for root c) reduce the heap size by 1. In this question, it is given
that heapify has been called few times and we see that last two elements in given array are the 2
maximum elements in array. So situation is clear, it is maxheapify whic has been called 2 times.
Question 3
CORRECT
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 CS 2011)
A A
C C
D D
Heap
Discuss it
Question 3 Explanation:
See http://www.geeksforgeeks.org/data-structures-and-algorithms-set-26/ for explanation.
Question 4
WRONG
A 3-ary max heap is like a binary max heap, but instead of 2 children, nodes have 3 children. A 3-ary
heap can be represented by an array as follows: The root is stored in the first location, a[0], nodes in the
next level, from left to right, is stored from a[1] to a[3]. The nodes from the second level of the tree from
left to right are stored from a[4] location onward. An item x can be inserted into a 3-ary heap containing n
items by placing x in the location a[n] and pushing it up the tree to satisfy the heap property. Which one of
the following is a valid sequence of elements in an array representing 3-ary max heap?
1, 3, 5, 6, 8, 9
B 9, 6, 3, 1, 8, 5
C 9, 3, 6, 8, 5, 1
9, 5, 6, 8, 3, 1
Heap
Discuss it
Question 4 Explanation:
Following 3-ary Max Heap can be constructed from sequence given option (D)
9
/ | \
/ | \
5 6 8
/ |
/ |
3 1
Question 5
WRONG
Suppose the elements 7, 2, 10 and 4 are inserted, in that order, into the valid 3- ary max heap found in
the above question, Which one of the following is the sequence of items in the array representing the
resultant heap?
10, 7, 9, 8, 3, 1, 5, 2, 6, 4
B 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
C 10, 9, 4, 5, 7, 6, 8, 2, 1, 3
10, 8, 6, 9, 7, 2, 3, 4, 1, 5
Heap
Discuss it
Question 5 Explanation:
After insertion of 7
9
/ | \
/ | \
7 6 8
/|\
/ | \
3 1 5
After insertion of 2
9
/ | \
/ | \
7 6 8
/|\ /
/ | \ /
3 1 5 2
After insertion of 10
10
/ | \
/ | \
7 9 8
/|\ /|
/ | \ / |
3 1 5 2 6
After insertion of 4
10
/ | \
/ | \
7 9 8
/|\ /|\
/ | \ / | \
3 1 5 2 6 4
Question 6
CORRECT
Consider a binary max-heap implemented using an array. Which one of the following array represents a
binary max-heap? (GATE CS 2009)
A 25,12,16,13,10,8,14
B 25,12,16,13,10,8,14
25,14,16,13,10,8,12
D 25,14,12,13,10,8,16
Heap
Discuss it
Question 6 Explanation:
A tree is max-heap if data at every node in the tree is greater than or equal to its children s data. In array
representation of heap tree, a node at index i has its left child at index 2i + 1 and right child at index 2i + 2.
25
/ \
/ \
14 16
/ \ / \
/ \ / \
13 10 8 12
Question 7
CORRECT
What is the content of the array after two delete operations on the correct answer to the previous
question?
A 14,13,12,10,8
B 14,12,13,8,10
C 14,13,8,12,10
14,13,12,8,10
Heap
Discuss it
Question 7 Explanation:
For Heap trees, deletion of a node includes following two operations. 1) Replace the root with last element
on the last level. 2) Starting from root, heapify the complete tree from top to bottom.. Let us delete the two
nodes one by one: 1) Deletion of 25: Replace 25 with 12
12
/ \
/ \
14 16
/\ /
/ \ /
13 10 8
Since heap property is violated for root (16 is greater than 12), make 16 as root of the tree.
16
/ \
/ \
14 12
/\ /
/ \ /
13 10 8
/ \
/ \
14 12
/\
/ \
13 10
/ \
/ \
8 12
/\
/ \
13 10
14
/ \
/ \
13 12
/\
/ \
8 10
Question 8
CORRECT
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 (A) (logn) (B) (n) (C) (nlogn)
(D) (n^2)
A A
B
C C
D D
Heap
Discuss it
Question 8 Explanation:
We can reduce the problem to Build Heap for 2n elements. Time taken for build heap is O(n)
Question 9
WRONG
In a min-heap with n elements with the smallest element at the root, the 7th smallest element can be
found in time a) (n log n) b) (n) c) (log n) d) (1) The question was not clear in
original GATE exam. For clarity, assume that there are no duplicates in Min-Heap and accessing heap
elements below root is allowed.
A a
C c
d
Heap
Discuss it
Question 9 Explanation:
The 7th smallest element must be in first 7 levels. Total number of nodes in any Binary Heap in first 7
levels is at most 1 + 2 + 4 + 8 + 16 + 32 + 64 which is a constant. Therefore we can always find 7th
smallest element in [Tex]\theta(1)[/Tex] time. If Min-Heap is allowed to have duplicates, then time
complexity becomes (Log n). Also, if Min-Heap doesn't allow directly accessing elements below root and
supports only extract-min() operation, then also time complexity becomes (Log n).
Question 10
WRONG
In a binary max heap containing n numbers, the smallest element can be found in time (GATE CS 2006)
0(n)
B O(logn)
C 0(loglogn)
0(1)
Heap
Discuss it
Question 10 Explanation:
In a max heap, the smallest element is always present at a leaf node. So we need to check for all leaf
nodes for the minimum value. Worst case complexity will be O(n)
12
/ \
/ \
8 7
/\ /\
/ \ / \
2 3 4 5
Question 11
WRONG
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.
a
b
C c
D d
Heap
Discuss it
Question 11 Explanation:
32, 15, 20, 30, 12, 25, 16
32
/ \
15 20
After insertion of 30
32
/ \
15 20
30
32
/ \
30 20
/
15
After insertion of 12
32
/ \
30 20
/ \
15 12
After insertion of 25
32
/ \
30 20
/ \ /
15 12 25
32
/ \
30 25
/ \ /
15 12 20
After insertion of 16
32
/ \
30 25
/ \ / \
15 12 20 16
Question 12
WRONG
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)
O(n)
O(nLogn)
Heap
Discuss it
Question 12 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.
Question 13
CORRECT
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:
10, 8, 7, 3, 2, 1, 5
B 10, 8, 7, 2, 3, 1, 5
C 10, 8, 7, 1, 2, 3, 5
D 10, 8, 7, 5, 3, 2, 1
Heap GATE-CS-2014-(Set-2)
Discuss it
Question 13 Explanation:
Initially heap has 10, 8, 5, 3, 2
10
/ \
8 5
/\
3 2
After insertion of 1
10
/ \
8 5
/\ /
3 21
After insertion of 7
10
/ \
8 5
/\ /\
3 21 7
10
/ \
8 7
/\ /\
3 21 5
greater than 7
Question 14
WRONG
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
Merging with another heap under the assumption that the heap has capacity to accommodate
Heap
Discuss it
Question 14 Explanation:
The merge operation takes O(n) time, all other operations given in question take O(Logn) time. The
Binomial and Fibonacci Heaps do merge in better time complexity.
Question 15
WRONG
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
A i-1
floor(i/2)
C ceiling(i/2)
(i+1)/2
Heap GATE-CS-2001
Discuss it
Question 15 Explanation:
Binary heaps can be represented using arrays: storing elements in an array and using their relative
positions within the array to represent child-parent relationships. For the binary heap element stored at
index i of the array, Parent Node will be at index: floor(i/2) Left Child will be at index: 2i Right child will be
at index: 2*i + 1 This explanation is contributed by Saksham Seth.
Question 16
WRONG
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
Question 16 Explanation:
The array 40, 30, 20, 10, 15, 16, 17, 8, 4 represents following heap
40
/ \
30 20
/\ /\
10 15 16 17
/\
8 4
/ \
30 20
/\ /\
10 15 16 17
/\ /
8 4 35
/ \
35 20
/\ /\
10 30 16 17
/\ /
8 4 15
Question 17
WRONG
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
4
B 5
C 2
3
Heap GATE-CS-2015 (Set 3)
Discuss it
Question 17 Explanation:
89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100
89
/ \
19 50
/ \ / \
17 12 15 2
/ \ /\ / \
5 7 11 6 9 100
100
/ \
19 89
/ \ / \
17 12 50 5
/ \ /\ / \
7 11 6 9 2 15
Question 18
WRONG
An operator delete(i) for a binary heap data structure is to be designed to delete the item in the i-th node.
Assume that the heap is implemented in an array and i refers to the i-th index of the array. If the heap tree
has depth d (number of edges on the path from the root to the farthest leaf), then what is the time
complexity to re-fix the heap efficiently after the removal of the element?
A O(1)
Question 18 Explanation:
For this question, we have to slightly tweak the delete_min() operation of the heap data structure to
implement the delete(i) operation. The idea is to empty the spot in the array at the index i (the position at
which element is to be deleted) and replace it with the last leaf in the heap (remember heap is
implemented as complete binary tree so you know the location of the last leaf), decrement the heap size
and now starting from the current position i (position that held the item we deleted), shift it up in case
newly replaced item is greater than the parent of old item (considering max-heap). If its not greater than
the parent, then percolate it down by comparing with the childs value. The newly added item can
percolate up/down a maximum of d times which is the depth of the heap data structure. Thus we can say
that complexity of delete(i) would be O(d) but not O(1). http://geeksquiz.com/binary-heap/ This solution is
contributed by Pranjul Ahuja.
Question 19
WRONG
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 _____________ [This question was originally
asked as Fill-in-the-Blanks question]
A 6
7
8
D 9
Question 20
WRONG
Which of the following sequences of array elements forms a heap?
{23, 17, 14, 6, 13, 10, 1, 12, 7, 5}
Question 20 Explanation:
When they are asking for heap, by default it's max heap. Basic Requirement:Array representation of
binary tree Starting from basics lets first understand heap trees We have 2 types of heap Min heap and
Max heap In Min heap the parent is always smaller than its children and in Max heap parent is always
greater than its children.
Looking at the options we can tell that which tree is Max heap tree. Now consider each option one by one
and draw a tree
From options it is clear that only option C satisfies the Max heap tree property. This explanation has been
contributed by Parul Sharma.
Tree Traversals
Question 1
WRONG
Following function is supposed to calculate the maximum depth or height of a Binary tree -- the number of
nodes along the longest path from the root node down to the farthest leaf node.
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);
C X = lDepth - 1, Y = rDepth -1
Tree Traversals
Discuss it
Question 1 Explanation:
If a tree is not empty, height of tree is MAX(Height of Left Subtree, Height of Right Subtree) + 1
See program to Find the Maximum Depth or Height of a Tree for more details.
Question 2
CORRECT
What is common in three different types of traversals (Inorder, Preorder and Postorder)?
Tree Traversals
Discuss it
Question 2 Explanation:
The order of inorder traversal is LEFT ROOT RIGHT The order of preorder traversal is ROOT LEFT
RIGHT The order of postorder traversal is LEFT RIGHT ROOT In all three traversals, LEFT is traversed
before RIGHT
Question 3
WRONG
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
postorder traversal of the binary tree is:
debfgca
edbgfca
C edbfgca
D defgbca
Tree Traversals
Discuss it
Question 3 Explanation:
Below is the given tree.
a
/ \
/ \
b c
/ \ / \
/ \ / \
d e f g
Question 4
CORRECT
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);
}
Run on IDE
C Returns height where height is defined as number of edges on the path from root to deepest node
D Return diameter where diameter is number of edges on the longest path between any two nodes.
Tree Traversals
Discuss it
Question 4 Explanation:
The function counts internal nodes. 1) If root is NULL or a leaf node, it returns 0. 2) Otherwise returns, 1
plus count of internal nodes in left subtree, plus count of internal nodes in right subtree. See the following
complete program. 1
Question 5
CORRECT
Which of the following pairs of traversals is not sufficient to build a binary tree from the given traversals?
Tree Traversals
Discuss it
Question 5 Explanation:
See http://www.geeksforgeeks.org/if-you-are-given-two-traversal-sequences-can-you-construct-the-
binary-tree/ for details.
Question 6
WRONG
Consider two binary operators ' ' and ' ' with the precedence of operator being lower than
that of the operator. Operator is right associative while operator is left associative.
Which one of the following represents the parse tree for expression (7 3 4 3 2)?
(GATE CS 2011)
A A
B
C
D D
Tree Traversals
Discuss it
Question 6 Explanation:
Let us consider the given expression ([Tex]7 \downarrow 3 \uparrow 4 \uparrow 3 \downarrow 2[/Tex]).
Since the precedence of [Tex]\uparrow[/Tex] is higher, the sub-expression ([Tex]3 \uparrow 4 \uparrow
3[/Tex]) will be evaluated first. In this sub-expression, [Tex]4 \uparrow 3[/Tex] would be evaluated first
because [Tex]\uparrow[/Tex] is right to left associative. So the expression is evaluated as [Tex]((7
\downarrow (3 \uparrow (4 \uparrow 3))) \downarrow 2)[/Tex]. Also, note that among the two
[Tex]\downarrow [/Tex] operators, first one is evaluated before the second one because the associativity of
[Tex]\downarrow[/Tex] is left to right.
Question 7
WRONG
Which traversal of tree resembles the breadth first search of the graph?
A Preorder
Inorder
C Postorder
Level order
Tree Traversals
Discuss it
Question 7 Explanation:
Breadth first search visits all the neighbors first and then deepens into each neighbor one by one.
The level order traversal of the tree also visits nodes on the current level and then goes to the next level.
Question 8
WRONG
Which of the following tree traversal uses a queue data structure?
Preorder
B Inorder
C Postorder
Level order
Tree Traversals
Discuss it
Question 8 Explanation:
Level order traversal uses a queue data structure to visit the nodes level by level.
Question 9
CORRECT
Which of the following cannot generate the full binary tree?
Question 9 Explanation:
To generate a binary tree, two traversals are necessary and one of them must be inorder. But, a full binary
tree can be generated from preorder and postorder traversals. Read the algorithm here. Read Can tree
be constructed from given traversals?
Question 10
WRONG
Consider the following C program segment
struct CellNode
{
struct CelINode *leftchild;
int element;
struct CelINode *rightChild;
}
Question 10 Explanation:
Explanation: DoSomething() returns max(height of left child + 1, height of left child + 1). So given that
pointer to root of tree is passed to DoSomething(), it will return height of the tree. Note that this
implementation follows the convention where height of a single node is 0.
Question 11
WRONG
Let LASTPOST, LASTIN and LASTPRE denote the last vertex visited in a postorder, inorder and preorder
traversal. Respectively, of a complete binary tree. Which of the following is always true? (GATE CS 2000)
LASTIN = LASTPOST
B LASTIN = LASTPRE
C LASTPRE = LASTPOST
Question 11 Explanation:
It is given that the given tree is complete binary tree. For a complete binary tree, the last visited node will
always be same for inorder and preorder traversal. None of the above is true even for a complete binary
tree. The option (a) is incorrect because the last node visited in Inorder traversal is right child and last
node visited in Postorder traversal is root. The option (c) is incorrect because the last node visited in
Preorder traversal is right child and last node visited in Postorder traversal is root. For option (b), see the
following counter example. Thanks to Hunaif Muhammed for providing the correct explanation.
1
/ \
2 3
/\ /
4 5 6
Inorder traversal is 4 2 5 1 6 3
Preorder traversal is 1 2 4 5 3 6
Question 12
WRONG
The array representation of a complete binary tree contains the data in sorted order. Which traversal of
the tree will produce the data in sorted form?
A Preorder
Inorder
C Postorder
Level order
Tree Traversals
Discuss it
Question 12 Explanation:
The level order traversal of a binary tree prints the data in the same order as it is stored in the array
representation of a complete binary tree.
Question 13
WRONG
Consider the following rooted tree with the vertex P labeled as root
B SQPTURWV
C SQPTWUVR
SQPTRUWV
Tree Traversals GATE-CS-2014-(Set-3)
Discuss it
Question 13 Explanation:
Algorithm Inorder(tree) - Use of Recursion
Steps:
understanding of Recursion
NULL here.
inorder traversal.
Hence we go back to Q.
Hence we go back to P.
be SQPTRWUV.
Question 14
WRONG
Consider the pseudocode given below. The function DoSomething() takes as argument a pointer to the
root of an arbitrary tree represented by the leftMostChild-rightSibling representation. Each node of the
tree is of type treeNode.
typedef struct treeNode* treeptr;
struct treeNode
{
treeptr leftMostChild, rightSibling;
};
int DoSomething (treeptr tree)
{
int value=0;
if (tree != NULL)
{
if (tree->leftMostChild == NULL)
value = 1;
else
value = DoSomething(tree->leftMostChild);
value = value + DoSomething(tree->rightSibling);
}
return(value);
}
Run on IDE
When the pointer to the root of a tree is passed as the argument to DoSomething, the value returned by
the function corresponds to the
number of internal nodes in the tree.
Question 14 Explanation:
The function counts leaf nodes for a tree represented using leftMostChild-rightSibling representation.
Below is function with comments added to demonstrate how function works. 1
Question 15
WRONG
Level order traversal of a rooted tree can be done by starting from the root and performing
A preorder traversal
B inorder traversal
Question 15 Explanation:
See this post for details
Question 16
WRONG
Consider the label sequences obtained by the following pairs of traversals on a labeled binary tree. Which
of these pairs identify a tree uniquely ?
(i) preorder and postorder
(ii), (iii)
(iii) only
D (iv) only
Question 16 Explanation:
Here, we consider each and every option to check whether it is true or false. 1) Preorder and postorder
Question 17
WRONG
Let LASTPOST, LASTIN and LASTPRE denote the last vertex visited in a postorder, inorder and preorder
traversal, respectively, of a complete binary tree. Which of the following is always true?
A LASTIN = LASTPOST
LASTIN = LASTPRE
C LASTPRE = LASTPOST
Question 17 Explanation:
See question 1 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-1/
Question 18
WRONG
Which one of the following binary trees has its inorder and preorder traversals as BCAD and ABCD,
respectively?
A A
B B
C
D
Tree Traversals GATE-IT-2004
Discuss it
Question 18 Explanation:
Inorder Traversal: Left -Root -Right PreOrder Traversal: Root-Left-Right
InOrder PreOrder
A. BADC ABCD
B. BCAD ACBD
C. ACBD ABCD
Question 19
WRONG
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
p
B p+1
n-p
D n-p+1
Question 19 Explanation:
Binary Search Tree, is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys less than the nodes key.
The right subtree of a node contains only nodes with keys greater than the nodes key.
The left and right subtree each must also be a binary search tree. There must be no
duplicate nodes.
So let us say n=10, p=4. According to BST property the root must be 10-4=6 (considering all unique
elements in BST)
And according to BST insertion, root is the first element to be inserted in a BST.
Therefore, the answer is (n-p).
Question 20
WRONG
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
A 8, 7, 6, 5, 4, 3, 2, 1
B 1, 2, 3, 4, 8, 7, 6, 5
2, 1, 4, 3, 6, 7, 8, 5
2, 1, 4, 3, 7, 8, 6, 5
Tree Traversals Gate IT 2005
Discuss it
Question 20 Explanation:
Please see this link for more details http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-
preorder-traversal/
Question 21
WRONG
If all the edge weights of an undirected graph are positive, then any subset of edges that connects all the
vertices and has minimum total weight is a
A Hamiltonian cycle
B grid
hypercube
tree
Tree Traversals Graph Theory GATE IT 2006
Discuss it
Question 21 Explanation:
As here we want subset of edges that connects all the vertices and has minimum total
weight i.e. Minimum Spanning Tree Option A - includes cycle, so may or may not
connect all edges. Option B - has no relevance to this question. Option C - includes
cycle, so may or may not connect all edges. Related:http://www.geeksforgeeks.org/greedy-
algorithms-set-2-kruskals-minimum-spanning-tree-mst/ http://www.geeksforgeeks.org/greedy-algorithms-
set-5-prims-minimum-spanning-tree-mst-2/ This solution is contributed by Mohit Gupta.
Question 22
WRONG
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?
35
64
C 128
D 5040
Question 23
WRONG
The following three are known to be the preorder, inorder and postorder sequences of a binary tree. But it
is not known which is which.
MBCAFHPYK
KAMCBYPFH
MABCKYFPH
Pick the true statement from the following.
I and II are preorder and inorder sequences, respectively
C II is the inorder sequence, but nothing more can be said about the other two sequences
Question 23 Explanation:
The approach to solve this question is to first find 2 sequences whose first and last element is same. The
reason being first element in the Pre-order of any binary tree is the root and last element in the Post-order
of any binary tree is the root. Looking at the sequences given, Pre-order = KAMCBYPFH Post-order =
MBCAFHPYK Left-over sequence MABCKYFPH will be in order. Since we have all the traversals
identified, let's try to draw the binary tree if possible.
I. Post
order
II. Pre order
III. Inorder This solution is contributed by Pranjul Ahuja.
Question 24
CORRECT
Consider the following sequence of nodes for the undirected graph given below.
abefdgc
abefcgd
adgebcf
adbcgef
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)?
A 1 and 3 only
2 and 3 only
C 2, 3 and 4 only
D 1, 2, and 3
Question 24 Explanation:
1: abef->c or g should be covered
4: adbc->e or f should be covered
2: abefcgd correct
3: adgebcf correct