Gate - DS & Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 211

2 Compiler Design (199) 323

3 Programming and DS: DS (213)

Arrays, Stacks, Queues, Linked lists, Trees, Binary search trees, Binary heaps, Graphs.

Mark Distribution in Previous GATE


Year 2021-1 2021-2 2020 2019 2018 2017-1 2017-2 2016-1 2016-2 Minimum Average Maximum
1 Mark Count 4 2 2 0 2 3 1 1 1 0 1.7 4
2 Marks Count 1 0 1 2 0 0 1 3 3 0 1.2 3
Total Marks 6 2 4 4 2 3 3 7 7 2 4.2 7

3.1 Abstract Data Type (1) top☝

3.1.1 Abstract Data Type: GATE CSE 2005 | Question: 2 top☝ ☛ https://gateoverflow.in/1344

An Abstract Data Type (ADT) is:

A. same as an abstract class


B. a data type that cannot be instantiated
C. a data type for which only the operations defined on it can be used, but none else
D. all of the above

gate2005-cse data-structures normal abstract-data-type

Answer ☟

Answers: Abstract Data Type

3.1.1 Abstract Data Type: GATE CSE 2005 | Question: 2 top☝ ☛ https://gateoverflow.in/1344

 An abstract data type (ADT) supports only the operations which are defined.

Abstract class is one that may not have definitions of all the objects it have. Moreover it can not be instantiated. To
instantiate we have to create a subclass then instantiate the class.

Abstract Data Type is like data structure eg. STACK where we have P USH() P OP () operation defined .

Hence, they are not the same thing.


http://www.devx.com/tips/Tip/5681
Correct Answer: C
References

 49 votes -- Manali (2.1k points)

3.2 Arrays (13) top☝

3.2.1 Arrays: GATE CSE 1993 | Question: 12 top☝ ☛ https://gateoverflow.in/2309

The following Pascal program segments finds the largest number in a two-dimensional integer array
A[0 … n − 1, 0 … n − 1] using a single loop. Fill up the boxes to complete the program and write against
A , B , C and D in your answer book Assume that max is a variable to store the largest value and i, j are the indices to
the array.
begin
max:=|A|, i:=0, j:=0;
while |B| do
begin
if A[i, j]>max then max:=A[i, j];
if |C| then j:=j+1;
else begin
j:=0;
i:=|D|
end
end

© Copyright GATE Overflow. Some rights reserved.


324 3 Programming and DS: DS (213)

end

gate1993 data-structures arrays normal descriptive

Answer ☟

3.2.2 Arrays: GATE CSE 1994 | Question: 1.11 top☝ ☛ https://gateoverflow.in/2452

In a compact single dimensional array representation for lower triangular matrices (i.e all the elements above the
diagonal are zero) of size n × n, non-zero elements, (i.e elements of lower triangle) of each row are stored one after
another, starting from the first row, the index of the (i, j)th element of the lower triangular matrix in this new representation is:

A. i + j
B. i + j − 1
i(i−1)
C. (j − 1) + 2
j(j−1)
D. i + 2

gate1994 data-structures arrays normal

Answer ☟

3.2.3 Arrays: GATE CSE 1994 | Question: 25 top☝ ☛ https://gateoverflow.in/2521

An array A contains n integers in non-decreasing order, A[1] ≤ A[2] ≤ ⋯ ≤ A[n]. Describe, using Pascal like
pseudo code, a linear time algorithm to find i, j, such that A[i] + A[j] = a given integer M , if such i, j exist.

gate1994 data-structures arrays normal descriptive

Answer ☟

3.2.4 Arrays: GATE CSE 1997 | Question: 17 top☝ ☛ https://gateoverflow.in/2277

An array A contains n ≥ 1 positive integers in the locations A[1], A[2], … A[n]. The following program fragment
prints the length of a shortest sequence of consecutive elements of A, A[i], A[i + 1], … , A[j] such that the sum of
their values is ≥ M , a given positive number. It prints ‘ n + 1’ if no such sequence exists. Complete the program by filling in
the boxes. In each case use the simplest possible expression. Write only the line number and the contents of the box.
begin
i:=1;j:=1;
sum := ◻
min:=n; finish:=false;
while not finish do
if ◻ then
if j=n then finish:=true
else
begin
j:=j+1;
sum:= ◻
end
else
begin
if(j-i) < min then min:=j-i;
sum:=sum –A[i];
i:=i+1;
end
writeln (min +1);
end.

gate1997 data-structures arrays normal descriptive

Answer ☟

3.2.5 Arrays: GATE CSE 1998 | Question: 2.14 top☝ ☛ https://gateoverflow.in/1686

Let A be a two dimensional array declared as follows:


A: array [1 …. 10] [1 ….. 15] of integer;

Assuming that each integer takes one memory location, the array is stored in row-major order and the first element of the array
is stored at location 100, what is the address of the element A[i][j]?

A. 15i + j + 84

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 325

B. 15j + i + 84
C. 10i + j + 89
D. 10j + i + 89

gate1998 data-structures arrays easy

Answer ☟

3.2.6 Arrays: GATE CSE 2000 | Question: 1.2 top☝ ☛ https://gateoverflow.in/625

An n × n array v is defined as follows:


v [i, j] = i − j for all i, j, i ≤ n, 1 ≤ j ≤ n
The sum of the elements of the array v is

A. 0
B. n−1
C. n2 − 3n + 2
(n+1)
D. n2 2

gate2000-cse data-structures arrays easy

Answer ☟

3.2.7 Arrays: GATE CSE 2000 | Question: 15 top☝ ☛ https://gateoverflow.in/686

Suppose you are given arrays p[1......N] and q[1......N] both uninitialized, that is, each location may contain an
arbitrary value), and a variable count, initialized to 0. Consider the following procedures set and is_set:
set(i) {
count = count + 1;
q[count] = i;
p[i] = count;
}
is_set(i) {
if (p[i] ≤ 0 or p[i] > count)
return false;
if (q[p[i]] ≠ i)
return false;
return true;
}

A. Suppose we make the following sequence of calls:


set(7); set(3); set(9);
After these sequence of calls, what is the value of count, and what do q[1], q[2], q[3], p[7], p[3] and p[9] contain?
B. Complete the following statement "The first count elements of __________contain values i such that set
(_________________) has been called".
C. Show that if set(i) has not been called for some i, then regardless of what p[i] contains, is_set(i) will return false.

gate2000-cse data-structures arrays easy descriptive

Answer ☟

3.2.8 Arrays: GATE CSE 2005 | Question: 5 top☝ ☛ https://gateoverflow.in/1347

A program P reads in 500 integers in the range [0, 100] representing 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?

A. An array of 50 numbers
B. An array of 100 numbers
C. An array of 500 numbers
D. A dynamically allocated array of 550 numbers

gate2005-cse data-structures arrays easy

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


326 3 Programming and DS: DS (213)

3.2.9 Arrays: GATE CSE 2013 | Question: 50 top☝ ☛ https://gateoverflow.in/1557

The procedure given below is required to find and replace certain characters inside an input character string supplied in
array A. The characters to be replaced are supplied in array oldc, while their respective replacement characters are
supplied in array newc. Array A has a fixed length of five characters, while arrays oldc and newc contain three characters
each. However, the procedure is flawed.
void find_and_replace (char *A, char *oldc, char *newc) {
for (int i=0; i<5; i++)
for (int j=0; j<3; j++)
if (A[i] == oldc[j])
A[i] = newc[j];
}

The procedure is tested with the following four test cases.

1. oldc = “abc”, newc = “dab”


2. oldc = “cde”, newc = “bcd”
3. oldc = “bca”, newc = “cda”
4. oldc = “abc”, newc = “bac”

The tester now tests the program on all input strings of length five consisting of characters ‘ a’, ‘b’, ‘c’, ‘d’ and ‘ e’ with
duplicates allowed. If the tester carries out this testing with the four test cases given above, how many test cases will be able to
capture the flaw?

A. Only one
B. Only two
C. Only three
D. All four

gate2013-cse data-structures arrays normal

Answer ☟

3.2.10 Arrays: GATE CSE 2013 | Question: 51 top☝ ☛ https://gateoverflow.in/43291

The procedure given below is required to find and replace certain characters inside an input character string supplied in
array A. The characters to be replaced are supplied in array oldc, while their respective replacement characters are
supplied in array newc. Array A has a fixed length of five characters, while arrays oldc and newc contain three characters
each. However, the procedure is flawed.
void find_and_replace (char *A, char *oldc, char *newc) {
for (int i=0; i<5; i++)
for (int j=0; j<3; j++)
if (A[i] == oldc[j])
A[i] = newc[j];
}

The procedure is tested with the following four test cases.

1. oldc = “abc”, newc = “dab”


2. oldc = “cde”, newc = “bcd”
3. oldc = “bca”, newc = “cda”
4. oldc = “abc”, newc = “bac”

If array A is made to hold the string “ abcde”, which of the above four test cases will be successful in exposing the flaw in this
procedure?

A. None
B. 2 only
C. 3 and 4 only
D. 4 only

gate2013-cse data-structures arrays normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 327

3.2.11 Arrays: GATE CSE 2014 Set 3 | Question: 42 top☝ ☛ https://gateoverflow.in/2076

Consider the C function given below. Assume that the array listA contains n(> 0) elements, sorted in ascending
order.
int ProcessArray(int *listA, int x, int n)
{
int i, j, k;
i = 0; j = n-1;
do {
k = (i+j)/2;
if (x <= listA[k]) j = k-1;
if (listA[k] <= x) i = k+1;
}
while (i <= j);
if (listA[k] == x) return(k);
else return -1;
}

Which one of the following statements about the function P rocessArray is CORRECT?

A. It will run into an infinite loop when x is not in listA.


B. It is an implementation of binary search.
C. It will always find the maximum element in listA.
D. It will return − 1 even when x is present in listA.

gate2014-cse-set3 data-structures arrays easy

Answer ☟

3.2.12 Arrays: GATE CSE 2015 Set 2 | Question: 31 top☝ ☛ https://gateoverflow.in/8148

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 with a ∞). The minimum number of entries (other than 1) to be shifted, to
remove 1 from the given Young tableau is _____.

gate2015-cse-set2 databases arrays normal numerical-answers

Answer ☟

3.2.13 Arrays: GATE CSE 2021 Set 1 | Question: 2 top☝ ☛ https://gateoverflow.in/357450

Let P be an array containing n integers. Let t be the lowest upper bound on the number of comparisons of the array
elements, required to find the minimum and maximum values in an arbitrary array of n elements. Which one of
the following choices is correct?

A. t > 2n − 2
B. t > 3⌈ n2 ⌉ and t ≤ 2n − 2
C. t > n and t ≤ 3⌈ n2 ⌉
D. t > ⌈log2 (n)⌉ and t ≤ n

gate2021-cse-set1 data-structures arrays

Answer ☟

Answers: Arrays

© Copyright GATE Overflow. Some rights reserved.


328 3 Programming and DS: DS (213)

3.2.1 Arrays: GATE CSE 1993 | Question: 12 top☝ ☛ https://gateoverflow.in/2309

 We have to traverse all elements in array. The code is doing this row wise.

begin
max:=A[0,0], i:=0, j:=0;
while (i < n) do
begin
if A[i, j]>max then max:=A[i, j];
if (j < n-1) then j:=j+1;
else begin
j:=0;
i:=i++;
end
end
end

 36 votes -- Arjun Suresh (330k points)

3.2.2 Arrays: GATE CSE 1994 | Question: 1.11 top☝ ☛ https://gateoverflow.in/2452

 j − 1 + i(i − 1)/2 because if you form a lower triangular matrix it contains elements in rows 1, 2, 3, …

So, C is the correct answer.

PS: Though not mentioned in the question, from options it is clear that the array index starts from
1 and not
0.
Explanation :
In a lower triangular matrix, ith row contains (i + 1) number of non zero elements.
If we assume Array index starting from 1 then, ith row contains i number of non zero elements.

before ith row there are i − 1 rows (row 1 to i − 1) , and in total these rows has 1 + 2 + 3 + … + (i − 1) = i((i − 1)/2
elements (row 1 has 1 element, row 2 has 2 elements, row i − 1 has i − 1 elements etc.)

Now, at ith row, before jth element there are (j − 1) elements(starting from arr[i, 1] to arr[i, j − 1]) .

Hence, in total before arr[i, j] there are (i(i − 1)/2 + j − 1) elements and those elements will have indexes .
S,o the index of the (i, j)th element of the lower triangular matrix in this new representation is (j − 1) + i(i − 1)/2
which is option C .
 70 votes -- Bhagirathi Nayak (11.7k points)

3.2.3 Arrays: GATE CSE 1994 | Question: 25 top☝ ☛ https://gateoverflow.in/2521


i = 1;
j = n;
while(i != j) {
if(A[i] + A[j] == M) break;
else if(A[i] + A[j] < M) i++;
else j--;
}

 35 votes -- Ankit Rokde (6.9k points)

3.2.4 Arrays: GATE CSE 1997 | Question: 17 top☝ ☛ https://gateoverflow.in/2277

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 329

 begin
i:=1;j:=1;
sum := A[1]
min:=n; finish:=false;
while not finish do
if sum < M then
if j=n then finish:=true
else
begin
j:=j+1;
sum:= sum + A[j]
end
else
begin
if(j-i) < min then min:=j-i;
sum:=sum – A[i];
i:=i+1;
end
writeln (min +1);
end.

Algorithm
'i' indicates the starting marker and 'j' acts as ending marker for the sum sequence. 'sum' is initialised as the first element in
the array because the algorithm proceeds by taking the sum of remaining elements. 'finish' is a boolean variable that
indicates exit from the loop.
After entering the loop for the first time with ' finish' as false, the sum is checked if it's strictly less than " M ". If that's the
case j is incremented and the sum is modified to sum +A[j]. When 'sum' becomes greater than or equal to ' M ', 'min' is
modified to the latest number of elements that make the sum greater than or equal to 'M ' and then, the first element is
stripped off from the sum and 'i' is incremented by one to move the initial marker of the sum sequence. The loop runs till ' j'
reaches the end of the array.
The algorithm keeps track of ' min' i.e. the number of elements in the minimum sum sequence. This is very similar to the
way we find the minimum value in an array by modifying the min value whenever a lesser value is encountered.
 22 votes -- krish__ (4.6k points)

3.2.5 Arrays: GATE CSE 1998 | Question: 2.14 top☝ ☛ https://gateoverflow.in/1686

 A[LB1 … U B1 , LB2 … U B2 ]
BA = Base address.
C = size of each element.
Row major order.
Loc(a[i][j]) = BA + [(i − LB1 )(U B2 − LB2 + 1) + (j − LB2 )] ∗ C.
Column Major order
Loc(a[i][j]) = BA + [(j − LB2 )(U B1 − LB1 + 1) + (i − LB1 )] ∗ C.
Substituting the values.
Answer is A.
 31 votes -- Gate Keeda (15.9k points)

3.2.6 Arrays: GATE CSE 2000 | Question: 1.2 top☝ ☛ https://gateoverflow.in/625

 The sum of the ith row and ith column is 0 as shown below. Since, the numbers of rows equals the number of
columns, the total sum will be 0.

0 -1 -2 -3 -4
1 0 -1 -2 -3
2 1 0 -1 -2
3 2 1 0 -1
4 3 2 1 0

© Copyright GATE Overflow. Some rights reserved.


330 3 Programming and DS: DS (213)

Correct Answer: A
 46 votes -- Arjun Suresh (330k points)

3.2.7 Arrays: GATE CSE 2000 | Question: 15 top☝ ☛ https://gateoverflow.in/686


a.
Initially count = 0;

When we call set(7) − count = 1, q[1] = 7, p[7] = 1 ;


when we call set(3) − count = 2, q[2] = 3, p[3] = 2 ;
when we call set(9) − count = 3, q[3] = 9, p[9] = 3 ;

b. Ans- "The first count elements of array q contain values i such that set(i) has been called".

c. If set(i) has not been called for some i, then regardless of what p[i] contains, When we call is_set(i) then
if (q[p[i]] ≠ i)
return false;

will always execute, because if set(i) is not called then p[i] ≠ count(any) and for then same count q[count] ≠ i. So if statement
will be true and will return false.
 16 votes -- Dhananjay Kumar Sharma (18.8k points)

3.2.8 Arrays: GATE CSE 2005 | Question: 5 top☝ ☛ https://gateoverflow.in/1347

 As we our area of interest is only the 50 numbers so take An array of 50 numbers where A[0] corresponds to
51...A[49] corresponds to 100 then after reading an input just increment the counter in correct position as said above.

Correct Answer: A
 63 votes -- Bhagirathi Nayak (11.7k points)

3.2.9 Arrays: GATE CSE 2013 | Question: 50 top☝ ☛ https://gateoverflow.in/1557

 The test cases 3 and 4 are the only cases that capture the flaw. The code does not work properly when an old
character is replaced by a new character and the new character is again replaced by another new character. This
doesn't happen in test cases (1) and (2), it happens only in cases (3) and (4).

Correct Answer: B.
 42 votes -- Vikrant Singh (11.2k points)

3.2.10 Arrays: GATE CSE 2013 | Question: 51 top☝ ☛ https://gateoverflow.in/43291

 The test cases 3 and 4 are the only cases that capture the flaw. The code does not work properly when an old
character is replaced by a new character and the new character is again replaced by another new character. This does
not happen in test cases (1) and (2), it happens only in cases (3) and (4).

Correct Answer: C.
 8 votes -- Vikrant Singh (11.2k points)

3.2.11 Arrays: GATE CSE 2014 Set 3 | Question: 42 top☝ ☛ https://gateoverflow.in/2076

 This is an implementation of the Binary search algorithm.

Note that the loop will be terminated when we have found x. In that case both the if conditions will be true making condition
inside the while as false i.e., i > j.

Correct Answer: B
 28 votes -- Monanshi Jain (7k points)

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 331

3.2.12 Arrays: GATE CSE 2015 Set 2 | Question: 31 top☝ ☛ https://gateoverflow.in/8148

 The answer should be 5.

1. We first need to shift 2 in place of 1 keeping 5 AND 14 intact as it isn't mentioned in the question that the entire row
elements move.
2. 4 is shifted up,next to 2 (keeping 12 and infinity intact in column 2).
3. Now in second row 6 is shifted left.
4. 18 shifts up to the second row
5. And finally 25 is shifted left to the third column.

So, this takes 5 moves and still maintains the tableau property. Also infinity is placed to the right of 25 and below 23
(unfilled entries to be filled with ∞ ). The final table would look as follows.

2 4 5 14
3 6 18 23
10 12 25 ∞
31 ∞ ∞ ∞

 71 votes -- Aman verma (209 points)

3.2.13 Arrays: GATE CSE 2021 Set 1 | Question: 2 top☝ ☛ https://gateoverflow.in/357450

 Correct Option: C

The answer is a stub!


Tournament Method:

Imagine using merge sort and you’d divided the array elements in pairs of two, every element is compared with each
other.
The largest(or smallest if preferred) is selected out each pairs and the winners are copied to a new array and the
procedure it repeated till we have one element remaining.

For this,
n n n,
At first we need 2 comparisons(since 2 pairs), then 4 so on this sums to n , an AP problem.
n n n
Comparisons Req. for finding the Max Element = + + ...= n
2 4 8

For finding the smallest element we would use the losers left out in the first round n2 losers to be precise.
We again use this procedure with an intention for finding smaller amongst all, (worst losers will be the best winners in
these rounds, ironical indeed).

For this,
n n n.
We need, 4 at first since we are pitting losers against losers comparisons then, 8 so on which sums upto 2
n n n n
Comparisons Req. for finding the Min Element = + + ...=
4 8 16 2
n 3n
Total Number of Comparisons Number Required = n + =
2 2
3
The number of comparisons needed is at least n if we consider the elements to be distinct.
2
Hence C is the answer.
Another more intuitive way to understand this is the build heap operation. I’ll leave that to you...
 2 votes -- Cringe is my middle name... (817 points)

3.3 Avl Tree (3) top☝

3.3.1 Avl Tree: GATE CSE 2009 | Question: 37,ISRO-DEC2017-55 top☝ ☛ https://gateoverflow.in/1323

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.

© Copyright GATE Overflow. Some rights reserved.


332 3 Programming and DS: DS (213)

A. 2
B. 3
C. 4
D. 5

gate2009-cse data-structures binary-search-tree normal isrodec2017 avl-tree

Answer ☟

3.3.2 Avl Tree: GATE CSE 2020 | Question: 6 top☝ ☛ https://gateoverflow.in/333225

What is the worst case time complexity of inserting n2 elements into an AVL-tree with n elements initially?

A. Θ(n4 )
B. Θ(n2 )
C. Θ(n2 log n)
D. Θ(n3 )

gate2020-cse binary-tree avl-tree

Answer ☟

3.3.3 Avl Tree: GATE IT 2008 | Question: 12 top☝ ☛ https://gateoverflow.in/3272

Which of the following is TRUE?

A. The cost of searching an AVL tree is Θ(log n) but that of a binary search tree is O(n)
B. 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)

gate2008-it data-structures binary-search-tree easy avl-tree

Answer ☟

Answers: Avl Tree

3.3.1 Avl Tree: GATE CSE 2009 | Question: 37,ISRO-DEC2017-55 top☝ ☛ https://gateoverflow.in/1323

 Answer is B.
With 1 node height is 0.
Max height will come when each level contain min nodes.
Minimum Nodes in an AVL tree with height n is H(n) = H(n − 1) + H(n − 2) + 1 .
H(0) = 1 .
H(1) = 2
H(2) = H(1) + H(0) + 1 = 2 + 1 + 1 = 4
H(3) = H(2) + H(1) + 1 = 4 + 2 + 1 = 7 .

So, the max height with 7 nodes is 3.


 71 votes -- Gate Keeda (15.9k points)

3.3.2 Avl Tree: GATE CSE 2020 | Question: 6 top☝ ☛ https://gateoverflow.in/333225

 Answer : C
Steps: For worst case (in worst case insertion will cause Ω(log n) operations in an AVL tree where n is the number
of nodes present.

1st insertion time complexity = Θ(log n)


2nd insertion time complexity = Θ(log(n + 1))

th
n2 insertion time complexity = Θ(log n) + Θ(log(n + 1)) + … + Θ(log(n + n2 ))
= Θ (log(n. (n + 1). (n + 2) … (n + n2 )))

= Θ (log )
© Copyright GATE Overflow. Some rights reserved.
3 Programming and DS: DS (213) 333

= Θ (log nn ) (∵ the highest degree term in the log expression will be nn .


2 2

= Θ (n2 log n) .

 14 votes -- Prashant Singh (47.1k points)

3.3.3 Avl Tree: GATE IT 2008 | Question: 12 top☝ ☛ https://gateoverflow.in/3272

 A) is true as AVL tree is a balanced search tree that has time complexity of searching Θ(log n), but in binary
search tree, we can have a completely left/right skewed tree, in which search is O(n).
 37 votes -- Happy Mittal (8.2k points)

3.4 Binary Heap (3) top☝

3.4.1 Binary Heap: GATE CSE 2018 | Question: 46 top☝ ☛ https://gateoverflow.in/204121

The number of possible min-heaps containing each value from {1, 2, 3, 4, 5, 6, 7} exactly once is _______

gate2018-cse binary-heap numerical-answers combinatory

Answer ☟

3.4.2 Binary Heap: GATE CSE 2020 | Question: 47 top☝ ☛ https://gateoverflow.in/333184

Consider the array representation of a binary min-heap containing 1023 elements. The minimum number of
comparisons required to find the maximum in the heap is ___________.

gate2020-cse numerical-answers binary-heap

Answer ☟

3.4.3 Binary Heap: GATE CSE 2021 Set 2 | Question: 2 top☝ ☛ https://gateoverflow.in/357538

​Let H be a binary min-heap consisting of n elements implemented as an array. What is the worst case time complexity
of an optimal algorithm to find the maximum element in H ?

A. Θ(1)
B. Θ(log n)
C. Θ(n)
D. Θ(n log n)

gate2021-cse-set2 data-structures heap binary-heap time-complexity

Answer ☟

Answers: Binary Heap

3.4.1 Binary Heap: GATE CSE 2018 | Question: 46 top☝ ☛ https://gateoverflow.in/204121

 Lets answer this question in an easier way :

7!
Now do 7×3×3 = 80
Here 7! because 7 items to be filled, Now 7 because root has only 7 nodes as its decedent including itself and only one can
be the root. In same way we get 3 and 3 for the second level nodes and 1 and 1 for the third level.
 57 votes -- Prashant Singh (47.1k points)

Ans: 80

© Copyright GATE Overflow. Some rights reserved.


334 3 Programming and DS: DS (213)

Explanation:
Number of min-heaps possible with keys {1, 2, 3, 4, 5, 6, 7} .

' A min-heap is a binary tree such that. - the data contained in each node is less than (or equal to) the data in that
node's children. - the binary tree is complete.

Since a binary heap is always a complete binary tree, so with 7 nodes, we can have 2 levels (root at level 0). It's structure
will be like this:

Now because of min-heap property, every node's value must be smaller than all of it's children. So, this ensure that the
minimum will always be at the root. ∴ 1 will be at the root.

The second minimum element(i.e. 2) can be present at the first level only(root is at the zeroth level). So we have two options.
Let's, for now, fix 2 at the left side.

We are now left with 5 more elements {3, 4, 5, 6, 7} . For the left subtree's two leaves, we have 5 ∗ 4 ways. i.e. first
choosing one of the 5 nodes, then choosing one of the remaining 4 nodes.
Now 3 nodes left. Out of these 3, one will be the least among them, and that will definitely become the parent of the two
remaining leaves(in the right subtree). Now with 2 nodes left, we can arrange them in 2 ways.

This gives (5 ∗ 4) ∗ 2 = 40 ways.


We can have the same number of ways, if we fixed 2 at the right subtree instead of left. So total ways:
= 40 ∗ 2
= 80
 282 votes -- Rishabh Gupta (12.5k points)

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 335

3.4.2 Binary Heap: GATE CSE 2020 | Question: 47 top☝ ☛ https://gateoverflow.in/333184

 If a heap has 1023 elements, it'll contain 512 leaves and since it is a MIN-HEAP, the maximum will be present in
the leaves. (Why? Assume it is not, then there will be some elements present under it and this will violate the min-
heap property.)

We can visualise it this way. At each level starting with root level, number of elements are

1 − 2 − 4 − 8 − 16 − 32 − 64 − 128 − 256 − 512 (this is the last level, hence leaves)

So if we have n elements in an array, we know that to find the maximum it takes n − 1 comparisons.

In this case, n = 512 , so the answer should be 511.

Some other excellent questions on finding maximum-minimum:

https://gateoverflow.in/1917/gate2014-1-39
https://gateoverflow.in/27198/tifr2014-b-10
https://gateoverflow.in/27194/tifr2014-b-9

References

 19 votes -- goxul (5.2k points)

3.4.3 Binary Heap: GATE CSE 2021 Set 2 | Question: 2 top☝ ☛ https://gateoverflow.in/357538

 In a min heap, maximum element is present in one of the leaf nodes.

If index of heap starts with 1, indices of leaves are ⌊n/2⌋ + 1, ⌊n/2⌋ + 2, ⌊n/2⌋ + 3 … n .

So, we have to perform linear search on at most n/2 + 1 elements to find the maximum element. (we cannot perform binary
search since it is not guaranteed that leaves are in sorted order) and that multiplied by some constant c will be the time
complexity of the optimal algorithm. (Here, c includes the cost of all operations which includes comparison, index shift etc.
for a single maximum element compare)

In asymptotic terms, c ∗ (n/2 + 1) is Θ(n).


 8 votes -- chirudeepnamini (3.2k points)

3.5 Binary Search Tree (31) top☝

3.5.1 Binary Search Tree: GATE CSE 1996 | Question: 2.14 top☝ ☛ https://gateoverflow.in/2743

A binary search tree is generated by inserting in order the following integers:

50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24

The number of nodes in the left subtree and right subtree of the root respectively is

A. (4, 7)
B. (7, 4)
C. (8, 3)
D. (3, 8)

gate1996 data-structures binary-search-tree normal

Answer ☟

3.5.2 Binary Search Tree: GATE CSE 1996 | Question: 4 top☝ ☛ https://gateoverflow.in/2756

A binary search tree is used to locate the number 43. Which of the following probe sequences are possible and which
are not? Explain.

© Copyright GATE Overflow. Some rights reserved.


336 3 Programming and DS: DS (213)

(a) 61 52 14 17 40 43
(b) 2 3 50 40 60 43
(c) 10 65 31 48 37 43
(d) 81 61 52 14 41 43
(e) 17 77 27 66 18 43
gate1996 data-structures binary-search-tree normal descriptive

Answer ☟

3.5.3 Binary Search Tree: GATE CSE 1997 | Question: 4.5 top☝ ☛ https://gateoverflow.in/2246

A binary search tree contains the value 1, 2, 3, 4, 5, 6, 7, 8 . The tree is traversed in pre-order and the values are printed
out. Which of the following sequences is a valid output?

A. 53124786
B. 53126487
C. 53241678
D. 53124768

gate1997 data-structures binary-search-tree normal

Answer ☟

3.5.4 Binary Search Tree: GATE CSE 2001 | Question: 14 top☝ ☛ https://gateoverflow.in/755

A. Insert the following keys one by one into a binary search tree in the order specified.

15, 32, 20, 9, 3, 25, 12, 1

Show the final binary search tree after the insertions.


B. Draw the binary search tree after deleting 15 from it.
C. Complete the statements S1 , S2 and S3 in the following function so that the function computes the depth of a binary tree
rooted at t.
typedef struct tnode{
int key;
struct tnode *left, *right;
} *Tree;

int depth (Tree t)


{
int x, y;
if (t == NULL) return 0;
x = depth (t -> left);
S1: ___________;

S2: if (x > y) return __________;

S3: else return _______;

gate2001-cse data-structures binary-search-tree normal descriptive

Answer ☟

3.5.5 Binary Search Tree: GATE CSE 2003 | Question: 19, ISRO2009-24 top☝ ☛ https://gateoverflow.in/909

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. 7 5 1 0 3 2 4 6 8 9
B. 0 2 4 3 1 6 5 9 8 7
C. 0 1 2 3 4 5 6 7 8 9
D. 9 8 6 4 2 3 0 1 5 7

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 337

gate2003-cse binary-search-tree easy isro2009

Answer ☟

3.5.6 Binary Search Tree: GATE CSE 2003 | Question: 6 top☝ ☛ https://gateoverflow.in/897

Let T(n) be the number of different binary search trees on n distinct elements.
Then T(n) = ∑nk=1 T(k − 1)T(x) , where x is

A. n−k+1
B. n−k
C. n−k−1
D. n−k−2

gate2003-cse normal binary-search-tree

Answer ☟

3.5.7 Binary Search Tree: GATE CSE 2003 | Question: 63, ISRO2009-25 top☝ ☛ https://gateoverflow.in/950

A data structure is required for storing a set of integers such that each of the following operations can be done in
O(log n) time, where n is the number of elements in the set.

I. Deletion of the smallest element


II. Insertion of an element if it is not already present in the set

Which of the following data structures can be used for this purpose?

A. A heap can be used but not a balanced binary search tree


B. A balanced binary search tree can be used but not a heap
C. Both balanced binary search tree and heap can be used
D. Neither balanced search tree nor heap can be used

gate2003-cse data-structures easy isro2009 binary-search-tree

Answer ☟

3.5.8 Binary Search Tree: GATE CSE 2004 | Question: 4, ISRO2009-26 top☝ ☛ https://gateoverflow.in/1001

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)?

A. 2
B. 3
C. 4
D. 6

gate2004-cse data-structures binary-search-tree easy isro2009

Answer ☟

3.5.9 Binary Search Tree: GATE CSE 2004 | Question: 85 top☝ ☛ https://gateoverflow.in/1079

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 ( number of leaf-nodes , number of leaf-nodes )


in left-subtree of x in right-subtree of x

Then the worst-case time complexity of the program is?

A. Θ(n)
B. Θ(n log n)

2
Θ( )
© Copyright GATE Overflow. Some rights reserved.
338 3 Programming and DS: DS (213)

C. Θ(n2 )
D. Θ(n2 log n)

gate2004-cse binary-search-tree normal data-structures

Answer ☟

3.5.10 Binary Search Tree: GATE CSE 2005 | Question: 33 top☝ ☛ https://gateoverflow.in/1369

Postorder traversal of a given binary search tree, T produces the following sequence of keys
10, 9, 23, 22, 27, 25, 15, 50, 95, 60, 40, 29
Which one of the following sequences of keys can be the result of an in-order traversal of the tree T ?

A. 9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95
B. 9, 10, 15, 22, 40, 50, 60, 95, 23, 25, 27, 29
C. 29, 15, 9, 10, 25, 22, 23, 27, 40, 60, 50, 95
D. 95, 50, 60, 40, 27, 23, 22, 25, 10, 9, 15, 29

gate2005-cse data-structures binary-search-tree easy

Answer ☟

3.5.11 Binary Search Tree: GATE CSE 2008 | Question: 46 top☝ ☛ https://gateoverflow.in/458

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. Θ(log n)
B. Θ(n)
C. Θ(n log n)
D. None of the above, as the tree cannot be uniquely determined

gate2008-cse data-structures binary-search-tree normal

Answer ☟

3.5.12 Binary Search Tree: GATE CSE 2012 | Question: 5 top☝ ☛ https://gateoverflow.in/37

The worst case running time to search for an element in a balanced binary search tree with n2n elements is

A. Θ(n log n)
B. Θ(n2n )
C. Θ(n)
D. Θ(log n)

gate2012-cse data-structures normal binary-search-tree

Answer ☟

3.5.13 Binary Search Tree: GATE CSE 2013 | Question: 43 top☝ ☛ https://gateoverflow.in/1554

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?

A. 10, 20, 15, 23, 25, 35, 42, 39, 30


B. 15, 10, 25, 23, 20, 42, 35, 39, 30
C. 15, 20, 10, 23, 25, 42, 35, 39, 30
D. 15, 10, 23, 25, 20, 35, 42, 39, 30

gate2013-cse data-structures binary-search-tree normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 339

3.5.14 Binary Search Tree: GATE CSE 2013 | Question: 7 top☝ ☛ https://gateoverflow.in/1416

Which one of the following is the tightest upper bound that represents the time complexity of inserting an object into a
binary search tree of n nodes?

A. O(1)
B. O(log n)
C. O(n)
D. O(n log n)

gate2013-cse data-structures easy binary-search-tree

Answer ☟

3.5.15 Binary Search Tree: GATE CSE 2014 Set 3 | Question: 39 top☝ ☛ https://gateoverflow.in/2073

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(na logb n + mc logd n) , the value of a + 10b + 100c + 1000d is ______.

gate2014-cse-set3 data-structures binary-search-tree numerical-answers normal

Answer ☟

3.5.16 Binary Search Tree: GATE CSE 2015 Set 1 | Question: 10 top☝ ☛ https://gateoverflow.in/8129

Which of the following is/are correct in order traversal sequence(s) of binary search tree(s)?

I. 3, 5, 7, 8, 15, 19, 25
II. 5, 8, 9, 12, 10, 15, 25
III. 2, 7, 10, 8, 14, 16, 20
IV. 4, 6, 7, 9, 18, 20, 25
A. I and IV only
B. II and III only
C. II and IV only
D. II only

gate2015-cse-set1 data-structures binary-search-tree easy

Answer ☟

3.5.17 Binary Search Tree: GATE CSE 2015 Set 1 | Question: 23 top☝ ☛ https://gateoverflow.in/8221

What are the worst-case complexities of insertion and deletion of a key in a binary search tree?

A. Θ(log n) for both insertion and deletion


B. Θ(n) for both insertion and deletion
C. Θ(n) for insertion and Θ(log n) for deletion
D. Θ(log n) for insertion and Θ(n) for deletion

gate2015-cse-set1 data-structures binary-search-tree easy

Answer ☟

3.5.18 Binary Search Tree: GATE CSE 2015 Set 3 | Question: 13 top☝ ☛ https://gateoverflow.in/8409

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
B. 67
C. 69
D. 83

gate2015-cse-set3 data-structures binary-search-tree easy

© Copyright GATE Overflow. Some rights reserved.


340 3 Programming and DS: DS (213)

Answer ☟

3.5.19 Binary Search Tree: GATE CSE 2016 Set 2 | Question: 40 top☝ ☛ https://gateoverflow.in/39586

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.

gate2016-cse-set2 data-structures binary-search-tree normal numerical-answers

Answer ☟

3.5.20 Binary Search Tree: GATE CSE 2017 Set 1 | Question: 6 top☝ ☛ https://gateoverflow.in/118286

Let T be a binary search tree with 15 nodes. The minimum and maximum possible heights of T are:
Note: The height of a tree with a single node is 0.

A. 4 and 15 respectively.
B. 3 and 14 respectively.
C. 4 and 14 respectively.
D. 3 and 15 respectively.

gate2017-cse-set1 data-structures binary-search-tree easy

Answer ☟

3.5.21 Binary Search Tree: GATE CSE 2017 Set 2 | Question: 36 top☝ ☛ https://gateoverflow.in/118378

The pre-order traversal of a binary search tree is given by 12, 8, 6, 2, 7, 9, 10, 16, 15, 19, 17, 20 . Then the post-order
traversal of this tree is

A. 2, 6, 7, 8, 9, 10, 12, 15, 16, 17, 19, 20


B. 2, 7, 6, 10, 9, 8, 15, 17, 20, 19, 16, 12
C. 7, 2, 6, 8, 9, 10, 20, 17, 19, 15, 16, 12
D. 7, 6, 2, 10, 9, 8, 15, 16, 17, 20, 19, 12

gate2017-cse-set2 data-structures binary-search-tree

Answer ☟

3.5.22 Binary Search Tree: GATE CSE 2020 | Question: 41 top☝ ☛ https://gateoverflow.in/333190

In a balanced binary search tree with n elements, what is the worst case time complexity of reporting all elements in
range [a, b]? Assume that the number of reported elements is k.

A. Θ(log n)
B. Θ(log n + k)
C. Θ(k log n)
D. Θ(n log k)

gate2020-cse data-structures binary-search-tree

Answer ☟

3.5.23 Binary Search Tree: GATE CSE 2020 | Question: 5 top☝ ☛ https://gateoverflow.in/333226

The preorder traversal of a binary search tree is 15, 10, 12, 11, 20, 18, 16, 19 . Which one of the following is the
postorder traversal of the tree?

A. 10, 11, 12, 15, 16, 18, 19, 20


B. 11, 12, 10, 16, 19, 18, 20, 15
C. 20, 19, 18, 16, 15, 12, 11, 10
D. 19, 16, 18, 20, 11, 12, 10, 15

gate2020-cse binary-search-tree

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 341

Answer ☟

3.5.24 Binary Search Tree: GATE CSE 2021 Set 1 | Question: 10 top☝ ☛ https://gateoverflow.in/357442

A binary search tree T contains n distinct elements. What is the time complexity of picking an element in T that is
smaller than the maximum element in T ?

A. Θ(n log n)
B. Θ(n)
C. Θ(log n)
D. Θ(1)

gate2021-cse-set1 data-structures binary-search-tree time-complexity

Answer ☟

3.5.25 Binary Search Tree: GATE IT 2005 | Question: 12 top☝ ☛ https://gateoverflow.in/3757

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

A. p
B. p+1
C. n−p
D. n−p+1

gate2005-it data-structures normal binary-search-tree

Answer ☟

3.5.26 Binary Search Tree: GATE IT 2005 | Question: 55 top☝ ☛ https://gateoverflow.in/3816

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
C. 2, 1, 4, 3, 6, 7, 8, 5
D. 2, 1, 4, 3, 7, 8, 6, 5

gate2005-it data-structures binary-search-tree normal

Answer ☟

3.5.27 Binary Search Tree: GATE IT 2006 | Question: 45 top☝ ☛ https://gateoverflow.in/3588

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?

A. {10, 75, 64, 43, 60, 57, 55}


B. {90, 12, 68, 34, 62, 45, 55}
C. {9, 85, 47, 68, 43, 57, 55}
D. {79, 14, 72, 56, 16, 53, 55}

gate2006-it data-structures binary-search-tree normal

Answer ☟

3.5.28 Binary Search Tree: GATE IT 2007 | Question: 29 top☝ ☛ https://gateoverflow.in/3462

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?

A. 35
B. 64

© Copyright GATE Overflow. Some rights reserved.


342 3 Programming and DS: DS (213)

C. 128
D. 5040

gate2007-it data-structures binary-search-tree normal

Answer ☟

3.5.29 Binary Search Tree: GATE IT 2008 | Question: 71 top☝ ☛ https://gateoverflow.in/3385

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

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?

A. II and III only


B. I and III only
C. III and IV only
D. III only

gate2008-it data-structures binary-search-tree normal

Answer ☟

3.5.30 Binary Search Tree: GATE IT 2008 | Question: 72 top☝ ☛ https://gateoverflow.in/3386

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?

A. I, II and IV are inorder sequences of three different BSTs


B. I is a preorder sequence of some BST with 439 as the root
C. II is an inorder sequence of some BST where 121 is the root and 52 is a leaf
D. IV is a postorder sequence of some BST with 149 as the root

gate2008-it data-structures binary-search-tree easy

Answer ☟

3.5.31 Binary Search Tree: GATE IT 2008 | Question: 73 top☝ ☛ https://gateoverflow.in/3387

How many distinct BSTs can be constructed with 3 distinct keys?

A. 4
B. 5
C. 6
D. 9

gate2008-it data-structures binary-search-tree normal

Answer ☟

Answers: Binary Search Tree

3.5.1 Binary Search Tree: GATE CSE 1996 | Question: 2.14 top☝ ☛ https://gateoverflow.in/2743

 Correct Option: B

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 343

Root will be 50. now insert one by one, greater to 50 in the right sub tree, lesser in left sub tree.

Or you can simply count the number looking at the i/p. less than 50 are 7. more than 50 are 4.
 34 votes -- Gate Keeda (15.9k points)

3.5.2 Binary Search Tree: GATE CSE 1996 | Question: 4 top☝ ☛ https://gateoverflow.in/2756

 (b) and (e) are not possible.

rest all i/p's will have binary trees with only one child. but (b) and (e) will have two childs at a point. therefore the probe
sequence will not be possible.

For better clarification, make BST's for the given i/p's and probe for 43.
 38 votes -- Gate Keeda (15.9k points)

3.5.3 Binary Search Tree: GATE CSE 1997 | Question: 4.5 top☝ ☛ https://gateoverflow.in/2246

 Note: PreOrder means Root-Left-Right Traversal of tree.

By Option Elimination:-

B. False. Because 5 is root so in preorder sequence first 5 elements must contain 1 to 5 But 6 comes here. So false.

So, now common things in option A,C,D is 5, 3 means 5 root then LHS subtree root is 3 . now 3 s LHS is 1, 2 so they should
come first rather than 4. So option C is False.

Now Check for Option A,D.

Root 5's RHS is 6, 7, 8 now as per Option A,D 7 is Root so 6 should be Left and 8 should be Right so pre order for Right
sub tree is 7, 6, 8 (Root-L-R). This satisfies option D.
Correct Answer: D
 45 votes -- Rajesh Pradhan (18.9k points)

3.5.4 Binary Search Tree: GATE CSE 2001 | Question: 14 top☝ ☛ https://gateoverflow.in/755

 Binary search tree will be :

After delete of root: use inorder predecessor

© Copyright GATE Overflow. Some rights reserved.


344 3 Programming and DS: DS (213)

Or After delete of root: use inorder successor

typedef struct tnode{


int key;
struct tnode *left, *right;
} *Tree;

int depth (Tree t)


{
int x, y;
if (t == NULL) return 0;
x = depth (t -> left);
S1: y = depth (t -> right);

S2: if (x > y) return (1+x);one for root

S3: else return (1+y); one for root

 28 votes -- Anu007 (14.4k points)

3.5.5 Binary Search Tree: GATE CSE 2003 | Question: 19, ISRO2009-24 top☝ ☛ https://gateoverflow.in/909

 In-order traversal returns the elements in ascending (smallest to largest) order.

Therefore, correct option C


 27 votes -- Gate_15_isHere (459 points)

3.5.6 Binary Search Tree: GATE CSE 2003 | Question: 6 top☝ ☛ https://gateoverflow.in/897

 The summation is for each node, if that node happens to be the root. When a node is root, it will have (k − 1)
nodes on the left sub tree (k being any number) and correspondingly (n − k) elements on the right sub tree. So, we
can write recurrence T(k − 1) ∗ T(n − k) for the number of distinct binary search trees, as the numbers on left and right
sub trees form BSTs independent of each other and only a difference in one of the sub trees produces a difference in the tree.
Hence, answer is B.
Knowing the direct formula can also help in getting the answer but is not recommended.
https://gatecse.in/number-of-binary-trees-possible-with-n-nodes/
 58 votes -- Arjun Suresh (330k points)

3.5.7 Binary Search Tree: GATE CSE 2003 | Question: 63, ISRO2009-25 top☝ ☛ https://gateoverflow.in/950

 Balanced search tree have height log n

Deletion of smallest element will take O(log n) time

Finding a element is present/not and doing insertion: O(log n)

Heap(MIN) is also an almost complete binary tree have height log n

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 345

Deletion of smallest element will take O(log n) time (root element removal, replace with last element +balancing)

Finding a element is present/not and insertion: Finding only takes O(n), insertion then balancing take O(log n). So, total
O(n) + O(log n) = O(n).

Answer is B.

(even if its maxheap our ans does not change only time for deletion of min will increase O(n))
 73 votes -- Anurag Semwal (6.7k points)

3.5.8 Binary Search Tree: GATE CSE 2004 | Question: 4, ISRO2009-26 top☝ ☛ https://gateoverflow.in/1001

Height is 3
Correct Answer: B
 33 votes -- Prashant Singh (47.1k points)

3.5.9 Binary Search Tree: GATE CSE 2004 | Question: 85 top☝ ☛ https://gateoverflow.in/1079

 B. At the root node (first level) the cost would be Θ ( n ) as the tree is balanced.
2
At next level, we have 2 nodes and for each of them cost of computing g(x) will be Θ ( n4 ). So, total cost at second level
= Θ ( n2 ) . Similarly at each level (total cost per level and not the cost per node in a level) the cost would be Θ ( n2 ) and so
for log n levels it would be Θ(n log n).
PS: Even if we change min to max in the defintion of g(x) we get the same answer.
 85 votes -- Shaun Patel (6.1k points)

3.5.10 Binary Search Tree: GATE CSE 2005 | Question: 33 top☝ ☛ https://gateoverflow.in/1369

 In order traversal of b binary search tree returns the element in sorted order - ascending (inorder is left parent then
right. in a bst left is less than parent and right is greater than parent). In this option A is the only sorted list. hence it is
the only possibility.
 31 votes -- Sankaranarayanan P.N (8.5k points)

3.5.11 Binary Search Tree: GATE CSE 2008 | Question: 46 top☝ ☛ https://gateoverflow.in/458

 Correct Answer: B
Last element in post order is the root of tree- find this element in inorder- log n time.
Now as in quick sort consider this as pivot and split the post order array into 2- possible because all elements smaller than
pivot goes to left and all elements larger than pivot goes to right and suppose we have x elements smaller than pivot, these
elements will be same in both inorder as well as postorder (order may change). We already got the root, now left child is the
left split and right child is the right split.
So, doing this recursively gives time complexity of this approach as

T(n) = T(k) + T(n − k − 1) + log n

Solving would give T(n) = O(n log n) in worst case, by putting k = 0 and shown at bottom.
But searching for an element in the inorder traversal of given BST can be done in O(1) because we have n elements from
1..n so there is no need to search for an element- if last element in post order is say 5 we take it as root and since 4 elements
(1..4) are smaller we split the post order array in to two- (first 4 elements), ( 6th element onward) and solve recursively. Time
complexity for this would be

T(n) = T(k) + T(n − k − 1) + O(1)

© Copyright GATE Overflow. Some rights reserved.


346 3 Programming and DS: DS (213)

which gives T(n) = O(n).


Since we know that all elements must be traversed at least once, T(n) = Ω(n) also and so

T(n) = Θ(n).

The following code is doing this.


//Install graphviz (sudo apt-get install graphviz on Ubuntu) to view output tree
#include<stdio.h>
#include<stdlib.h>
struct tree
{
struct tree* left;
struct tree* right;
int x;
};
struct tree* makenode(int x)
{
struct tree * root = malloc(sizeof(struct tree));
root -> x = x;
root -> left = root -> right = NULL;
return root;
}

struct tree* makeBST(int *post, int start, int n, int inorder){


if(n <= 0)
return NULL;
int pivot = post[start + n -1];
struct tree * root = makenode(pivot);
root -> left = makeBST(post, start, pivot-1 - inorder, inorder );
root -> right = makeBST(post, pivot - inorder - 1, n - (pivot - inorder), pivot);
return root;
}
void preorder(struct tree* node)
{
if(node == NULL)
return;
printf("%d ", node->x);
preorder(node->left);
preorder(node->right);
}
void printdot(struct tree* node, FILE * f)
{
if(node == NULL)
return;
if(node-> left != NULL)
{
fprintf(f, "%d -- %d;\n", node->x, node->left->x);
}
if(node-> right != NULL)
{
fprintf(f, "%d -- %d;\n", node->x, node->right->x);
}
printdot(node->left, f);
printdot(node->right, f);
}

int main(){
int i, n, *a;
printf("Enter n: ");
scanf("%d", &n);
a = malloc(n * sizeof(int));
printf ("Enter post order traversal: ");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
struct tree * tree = makeBST(a, 0, n, 0);
printf("Pre order traversal is : ");
preorder(tree);
printf("\n");
FILE * f = fopen("tree.dot", "w");
fprintf(f, "graph tree { \n");
printdot(tree, f);
fprintf(f, "}\n");
fclose(f);

#if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__) || (defined (__gnu_linux__)) )


system("dot -Tpng tree.dot -o output.png; eog output.png");
#endif

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 347

T(n) = T(k) + T(n − k − 1) + log n

Solving would give T(n) = O(n log n), by putting k = 0 ,


T(n) = T(0) + T(n − 1) + log n, ⟹ T(n) = O(1) + log n + log(n − 1) + log(n − 2) + ⋯ + log 1 ⟹ T(n) = n
(Stirling's Approximation)
PS: Even for a general BST, given a post order traversal, we can construct the BST in O(n) more stricter than O(n log n)
derived above and this matches Ω(n) and hence we do have an Θ(n) algorithm. This algorithm can be seen at below link
https://www.geeksforgeeks.org/construct-a-binary-search-tree-from-given-postorder/
References

 96 votes -- Arjun Suresh (330k points)

3.5.12 Binary Search Tree: GATE CSE 2012 | Question: 5 top☝ ☛ https://gateoverflow.in/37

 Binary search takes Θ(log n) for n elements in the worst case. So, with (n2n ) elements, the worst case time will
be

Θ(log(n2n ))

= Θ(log n + log 2n )

= Θ(log n + n)

= Θ(n)

Correct Answer: C
 79 votes -- Arjun Suresh (330k points)

3.5.13 Binary Search Tree: GATE CSE 2013 | Question: 43 top☝ ☛ https://gateoverflow.in/1554

 Since it is a binary search tree, its inorder traversal produces a sorted sequence i.e.
10, 15, 20, 23, 25, 30, 35, 39, 42.
Now given inorder and preorder traversals, we get following tree :

From this, we can give postorder traversal sequence as 15, 10, 23, 25, 20, 35, 42, 39, 30 i.e., option (D).
 35 votes -- Happy Mittal (8.2k points)

3.5.14 Binary Search Tree: GATE CSE 2013 | Question: 7 top☝ ☛ https://gateoverflow.in/1416

 Option (C) is True .


Suppose that we need to insert a node z such that k = key[z]. Using binary search we find a nil such that replacing it
by z does not break the BST-property

BST-Insert(x, z, k)

1. : if x = nil then return “Error”


2. :y←x
3. : while true do {
4. : if key[y] < k
5. : then z ← left[y]
6. : else z ← right[y]

© Copyright GATE Overflow. Some rights reserved.


348 3 Programming and DS: DS (213)

7. : if z = nil break
8. :}
9. : if key[y] > k then left[y] ← z
10. : else right[p[y]] ← z

Time Complexity Analysis :

1. Best Case = O(1) , When it is smallest/greatest element and BST contains only all greater/smaller element than
inserting element respectively.
2. Avg Case = O(log n) , When it belongs between some elements .
3. Worst Case = O(n) , When it is smallest/greatest element and BST contains only all smaller/greater element than
inserting element respectively.

 42 votes -- Bhagirathi Nayak (11.7k points)

3.5.15 Binary Search Tree: GATE CSE 2014 Set 3 | Question: 39 top☝ ☛ https://gateoverflow.in/2073

 In worst case for finding L and H it will take O(log n) time as the given tree is balanced binary search tree.
Now there are m elements between L and H . So to traverse m element it will take O(m) time (traversal algorithm
given below). So, total
O(m + log n) ⟹ a = 0, b = 1, c = 1, d = 0
∴ 0 + (10 × 1) + (100 × 1) + (1000 × 0) = 110.

To find all the numbers from L to H we can do an inorder traversal from root and discard all elements before L and after H .
But this has O(n) time complexity. So, we can do a modification to inorder traversal and combine with binary search as
follows:

1. Find L using binary search and keep all nodes encountered in the search in a stack.
2. After finding L add it to stack as well and initialize sum = 0.
3. Now, for all nodes in stack, do an inorder traversal starting from their right node and adding the node value to sum. If H
is found, stop the algorithm.

 125 votes -- Kalpish Singhal (1.6k points)

Here is an example 

L = 25, H = 35
Inorder: 10, 15, 20, 25 , 26, 27, 28, 30, 31, 32, 33, 34, 35 , 36, 39, 42
L H

1. Find L and H → O(log n) time.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 349

2. Traverse ' m' elements between ' L' and ' H ' → O(m) [Traversal algorithm]

Total → O(m + log n)


a = 0, b = 1, c = 1, d = 0
10 + 100 = 110 Answer
Traversal Algorithm:

1. Find L using Binary search and keep H > node > L encountered in the search in a stack.

2. After finding L, add it to stack as well & initialize sum = 0


3. Now, for all nodes in the stack, do an inorder traversal starting from their right node and adding the node value to sum. If
it is found than stop the algorithm.

Node (1)
No Right child; Sum = Sum + Node value = 0 + 25 = 25.
Node (2)
Inorder Traversal from Right Child → 24, 28
Sum = sum + inorder Traversal + Node Value = (25 + 27 + 28) + 26
Node (3)
H
Inorder Traversal From Right Child → 31, 32, 33, 34, 35→ Stop Inorder Traversal
Sum = Sum + Inorder Traversal + Node value
= 25 + 26 + 24 + 28 + (31 + 32 + 33 + 34 + 35) + 30
= 25 + 26 + 24 + 28 + 30 + 31 + 32 + 33 + 34 + 35 Answer

EDIT :

1. In Step 1, we need to find only L and not H.


2. In Traversal Algo: Find L using Binary Search and Keep, L< Nodes< H, encountered in the search in the stack.

 79 votes -- Vidhi Sethi (8.3k points)

3.5.16 Binary Search Tree: GATE CSE 2015 Set 1 | Question: 10 top☝ ☛ https://gateoverflow.in/8129

 In order traversal of key are always in ascending order.


So, here I & IV th sequence are in ascending order so Option A is Answer.
 23 votes -- Rajesh Pradhan (18.9k points)

3.5.17 Binary Search Tree: GATE CSE 2015 Set 1 | Question: 23 top☝ ☛ https://gateoverflow.in/8221

 Option B, both happens when the BST is skewed.


What is a Skewed Tree?
A binary tree which is dominated solely by left child nodes or right child nodes is called a skewed binary tree or more
specifically left skewed binary tree or right skewed binary tree respectively.

 39 votes -- GATERush (917 points)

© Copyright GATE Overflow. Some rights reserved.


350 3 Programming and DS: DS (213)

3.5.18 Binary Search Tree: GATE CSE 2015 Set 3 | Question: 13 top☝ ☛ https://gateoverflow.in/8409

 On last level 67, hence option B is True.


 33 votes -- Bran Stark (339 points)

3.5.19 Binary Search Tree: GATE CSE 2016 Set 2 | Question: 40 top☝ ☛ https://gateoverflow.in/39586

 We need to fill 7 levels with 7 elements. So, at each level we have exactly 2 possible options like 1 and 7 for
root- one corresponding to making it left skewed and other right skewed. And this is the same for all levels up to 6
giving 26 = 64 possible ways.
 141 votes -- Arjun Suresh (330k points)

3.5.20 Binary Search Tree: GATE CSE 2017 Set 1 | Question: 6 top☝ ☛ https://gateoverflow.in/118286

 The maximum height of a binary search tree will be when the tree is fully skewed

Maximum height = n − 1 = 15– 1 = 14


The minimum height of a binary search tree will be when the tree is full.

Minimum height = log2 (n + 1)– 1 = log2 (15 + 1)– 1 = log2 (16)– 1 = 4 − 1 = 3


Correct Answer: B
 17 votes -- Pankaj Kumar (7.8k points)

3.5.21 Binary Search Tree: GATE CSE 2017 Set 2 | Question: 36 top☝ ☛ https://gateoverflow.in/118378

 Preoder: 12 8 6 2 7 9 10 16 15 19 17 20
Inorder of BST must be sorted in increasing order!
 root 
left right
root

 
Inorder: 2 6 7 8 9 10 12 15 16 17 19 20
left right

So, Postorder: 2 7 6 10 9 8 15 17 20 19 16 12.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 351

Answer is B.
 23 votes -- 2018 (5.5k points)

3.5.22 Binary Search Tree: GATE CSE 2020 | Question: 41 top☝ ☛ https://gateoverflow.in/333190

 First, you'll have to check if the elements a and b are present in the BST or not. Since the BST is balanced, it will
take Θ(log2 (n)) time for that. Traversing the k elements would take additional Θ(k) time.

Hence Θ(log2 (n) + k)


 17 votes -- Debasish Das (1.5k points)

3.5.23 Binary Search Tree: GATE CSE 2020 | Question: 5 top☝ ☛ https://gateoverflow.in/333226

 Preorder traversal of BST : 15, 10, 12, 11, 20, 18, 16, 19
In Pre-order, the first node is ROOT. So root is 15.
In Post-order, the last node is ROOT. So in the Post-order sequence, 15 must be at last.
In Pre-order, the second node is the left child of ROOT, if it is less than the root.
Sequence: 10, 12, 11 belongs to the left sub-tree of ROOT.
10, 12, 11 is a Preorder of BST -- repetitively apply the steps.
In the Pre-order, the nodes which are greater than ROOT are on the right side of ROOT.
Sequence: 20, 18, 16, 19 belongs to the right sub-tree of ROOT.
20, 18, 16, 19 is a Preorder of BST -- repetitively apply the steps.

Finally we will get 11, 12, 10, 16, 19, 18, 20, 15 as Postorder.
 9 votes -- Shaik Masthan (50.4k points)

3.5.24 Binary Search Tree: GATE CSE 2021 Set 1 | Question: 10 top☝ ☛ https://gateoverflow.in/357442

 If our data structure contains n distinct elements then :

In all the standard data structures that we know/study about, If we want to pick/find an element which is Not maximum
(smaller than maximum) then time complexity will be Θ(1) because we only need to compare any two elements. Take any
two elements that you can access in constant time, compare them and return smaller of those two elements.

PS :

By “standard data structures that we know/study about” I mean the following :

Binary tree, Binary search tree, AVL tree, sorted or unsorted array, linked lists, arrays, stacks, queues, hash tables, heaps etc.
 7 votes -- Deepak Poonia (23.3k points)

3.5.25 Binary Search Tree: GATE IT 2005 | Question: 12 top☝ ☛ https://gateoverflow.in/3757

 Option is C.

© Copyright GATE Overflow. Some rights reserved.


352 3 Programming and DS: DS (213)

P: # elements in RST
⇒ Depending on X, some number will go LST ∉ RST

Remaining elements for LST: n − (p + 1)

  


1, 2, … , n − (p + 1) n−p (n − p) + 1, … , n
LSTn−(p+1)elements Root1element RSTpelements

 58 votes -- Akhil Nadh PC (16.5k points)

3.5.26 Binary Search Tree: GATE IT 2005 | Question: 55 top☝ ☛ https://gateoverflow.in/3816

The answer is D.
 30 votes -- Gate Keeda (15.9k points)

3.5.27 Binary Search Tree: GATE IT 2006 | Question: 45 top☝ ☛ https://gateoverflow.in/3588

 In option C search sequence progress in . . .47, 68, 43, . .

At 47 we see that search key 55 is greater and it will be on right side of 47. so in further comparison a value less than 47
will not come

Hence, option C is wrong.


 38 votes -- Sankaranarayanan P.N (8.5k points)

3.5.28 Binary Search Tree: GATE IT 2007 | Question: 29 top☝ ☛ https://gateoverflow.in/3462

 10, 20, 40, 50, 70, 80, 90

In BST search we if we go from say 10 to 40 while searching for 60, we will never encounter 20. So, 10, 20, 40 and 50
visited, means they are visited in order. Similarly, 90, 80 and 70 are visited in order. So, our required answer will be
No. of possible permutations of 7 numbers
No. of possible permutations of numbers smaller than 60×No. of possible permutations of numbers larger than 60

(Since only one permutation is valid for both the smaller set of numbers as well as larger set of numbers)

7!
=
© Copyright GATE Overflow. Some rights reserved.
3 Programming and DS: DS (213) 353

7!
= 4!3!

= 35

Correct Answer: A
 169 votes -- Arjun Suresh (330k points)

Question is similar to this question : https://gateoverflow.in/1275/gate2007_84-85


We will convert Moves to Text.
It is given that During Search we have Traversed these nodes

{10, 20, 40, 50, 70, 80, 90}


as it can be seen that Red ones are bigger than 60 and blue ones are smaller than 60.
Path to node 60 has involved those nodes. So, one of the possible solution to the problem is

{L, L, L, L, S, S, S}.

Any other solution will contains these moves only because at a time on a node we can get directions as S(meaning 60 is
smaller) or L(meaning 60 is larger) on comparison and since it is given that those nodes were encountered it means
directions were picked from that set.
7!
Hence, total number of possible solutions = all Permutations of that set, which is given by 4!×3!
= 35
answer = option A
References

 42 votes -- Amar Vashishth (25.2k points)

3.5.29 Binary Search Tree: GATE IT 2008 | Question: 71 top☝ ☛ https://gateoverflow.in/3385

 The option is D.

' Which all of the above sequences list nodes in the order in which we could have encountered them in the search?

The question goes like this. IF there had been 273 in the actual sequence then which of the following search sequences
would have been successful.

In sequence 1 no need to go from 285 to 376 as 273 is less than 285.


In sequence 2 no need to go from 381 to 472 as 273 is less than 381.
In sequence 4 no need to go from 395 to 463 as 273 is less than 395.
In sequence 3 number 273 might have been to the left of 307 and search would have been successful.
Hence, Option D
 54 votes -- Akhil Nadh PC (16.5k points)

Answer: D

© Copyright GATE Overflow. Some rights reserved.


354 3 Programming and DS: DS (213)

I. no need to go from 285 to 376 as 273 is less than 285.

II. no need to go from 381 to 472 as 273 is less than 381.

IV. no need to go from 395 to 463 as 273 is less than 395.


 28 votes -- Rajarshi Sarkar (27.8k points)

3.5.30 Binary Search Tree: GATE IT 2008 | Question: 72 top☝ ☛ https://gateoverflow.in/3386


A. Incorrect because I & IV are not in ascending order.(Inoder sequence of BST is in increasing order)

B. I is a preorder sequence of some BST with 439 as the root . False because if 439 is root, it should be first element in
preorder.

C. This is correct.

D. IV is a postorder sequence of some BST with 149 as the root, False because if 149 is root, it should be last element in
postorder

 32 votes -- Akash Kanase (36k points)

3.5.31 Binary Search Tree: GATE IT 2008 | Question: 73 top☝ ☛ https://gateoverflow.in/3387

 For number of distinct BSTs with n nodes we apply the formula

C(2n, n)
n+1

n = 3 here, so C(6, 3) = 20
C(2n,n)
So, n+1 = 20/4 = 5
Answer is 5
REF :- https://gatecse.in/number-of-binary-trees-possible-with-n-nodes/
Correct Answer: B
References

 41 votes -- Abhimanyu Kumar (161 points)

3.6 Binary Tree (50) top☝

3.6.1 Binary Tree: GATE CSE 1987 | Question: 2c top☝ ☛ https://gateoverflow.in/80579

State whether the following statements are TRUE or FALSE:

It is possible to construct a binary tree uniquely whose pre-order and post-order traversals are given?

gate1987 binary-tree data-structures normal true-false

Answer ☟

3.6.2 Binary Tree: GATE CSE 1987 | Question: 2g top☝ ☛ https://gateoverflow.in/80588

State whether the following statements are TRUE or FALSE:

If the number of leaves in a tree is not a power of 2, then the tree is not a binary tree.

gate1987 data-structures binary-tree true-false

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 355

3.6.3 Binary Tree: GATE CSE 1987 | Question: 7b top☝ ☛ https://gateoverflow.in/82427

Construct a binary tree whose preorder traversal is

KLNM P RQST

and inorder traversal is

NLKP RM SQT

gate1987 data-structures binary-tree descriptive

Answer ☟

3.6.4 Binary Tree: GATE CSE 1988 | Question: 7i top☝ ☛ https://gateoverflow.in/94366

Define the height of a binary tree or subtree and also define a height-balanced (AVL) tree.

gate1988 normal descriptive data-structures binary-tree

Answer ☟

3.6.5 Binary Tree: GATE CSE 1988 | Question: 7ii top☝ ☛ https://gateoverflow.in/94367

Mark the balance factor of each on the tree given on the below figure and state whether it is height-balanced.

gate1988 data-structures normal descriptive binary-tree

Answer ☟

3.6.6 Binary Tree: GATE CSE 1988 | Question: 7iii top☝ ☛ https://gateoverflow.in/94368

Consider the tree given in the below figure, insert 13 and show the new balance factors that would arise if the tree is not
rebalanced. Finally, carry out the required rebalancing of the tree and show the new tree with the balance factors on
each mode.

gate1988 normal descriptive data-structures binary-tree

Answer ☟

3.6.7 Binary Tree: GATE CSE 1990 | Question: 3-iv top☝ ☛ https://gateoverflow.in/84828

The total external path length, EPL, of a binary tree with n external nodes is, EPL = ∑ Iw , where Iw is the path
w
length of external node w),

A. ≤ n2 always.
B. ≥ n log2 n always.
2

© Copyright GATE Overflow. Some rights reserved.


356 3 Programming and DS: DS (213)

C. Equal to n2 always.
D. O(n) for some special trees.

gate1990 normal data-structures binary-tree multiple-selects

Answer ☟

3.6.8 Binary Tree: GATE CSE 1991 | Question: 01,viii top☝ ☛ https://gateoverflow.in/506

The weighted external path length of the binary tree in figure is ______

gate1991 binary-tree data-structures normal numerical-answers

Answer ☟

3.6.9 Binary Tree: GATE CSE 1991 | Question: 1,ix top☝ ☛ https://gateoverflow.in/502

If the binary tree in figure is traversed in inorder, then the order in which the nodes will be visited is ______

gate1991 binary-tree easy data-structures descriptive

Answer ☟

3.6.10 Binary Tree: GATE CSE 1991 | Question: 14,a top☝ ☛ https://gateoverflow.in/541

Consider the binary tree in the figure below:

What structure is represented by the binary tree?

gate1991 data-structures binary-tree time-complexity normal descriptive

Answer ☟

3.6.11 Binary Tree: GATE CSE 1991 | Question: 14,b top☝ ☛ https://gateoverflow.in/43026

Consider the binary tree in the figure below:

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 357

Give different steps for deleting the node with key 5 so that the structure is preserved.

gate1991 data-structures binary-tree normal descriptive

Answer ☟

3.6.12 Binary Tree: GATE CSE 1991 | Question: 14,c top☝ ☛ https://gateoverflow.in/43027

Consider the binary tree in the figure below:

Outline a procedure in Pseudo-code to delete an arbitrary node from such a binary tree with n nodes that preserves the
structures. What is the worst-case time complexity of your procedure?

gate1991 normal data-structures binary-tree time-complexity descriptive

Answer ☟

3.6.13 Binary Tree: GATE CSE 1993 | Question: 16 top☝ ☛ https://gateoverflow.in/2313

Prove by the principal of mathematical induction that for any binary tree, in which every non-leaf node has 2-
descendants, the number of leaves in the tree is one more than the number of non-leaf nodes.

gate1993 data-structures binary-tree normal descriptive

Answer ☟

3.6.14 Binary Tree: GATE CSE 1994 | Question: 8 top☝ ☛ https://gateoverflow.in/2504

A rooted tree with 12 nodes has its nodes numbered 1 to 12 in pre-order. When the tree is traversed in post-order, the
nodes are visited in the order 3, 5, 4, 2, 7, 8, 6, 10, 11, 12, 9, 1 .

Reconstruct the original tree from this information, that is, find the parent of each node, and show the tree diagrammatically.

gate1994 data-structures binary-tree normal descriptive

Answer ☟

3.6.15 Binary Tree: GATE CSE 1995 | Question: 1.17 top☝ ☛ https://gateoverflow.in/2604

A binary tree T has n leaf nodes. The number of nodes of degree 2 in T is

A. log2 n
B. n−1
C. n
D. 2n

gate1995 data-structures binary-tree normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


358 3 Programming and DS: DS (213)

3.6.16 Binary Tree: GATE CSE 1995 | Question: 6 top☝ ☛ https://gateoverflow.in/2667

What is the number of binary trees with 3 nodes which when traversed in post-order give the sequence A, B, C? Draw
all these binary trees.

gate1995 data-structures binary-tree normal descriptive

Answer ☟

3.6.17 Binary Tree: GATE CSE 1996 | Question: 1.14 top☝ ☛ https://gateoverflow.in/2718

In the balanced binary tree in the below figure, how many nodes will become unbalanced when a node is inserted as a
child of the node “g”?

A. 1
B. 3
C. 7
D. 8

gate1996 data-structures binary-tree normal

Answer ☟

3.6.18 Binary Tree: GATE CSE 1996 | Question: 1.15 top☝ ☛ https://gateoverflow.in/2719

Which of the following sequences denotes the post order traversal sequence of the below tree?

A. fegcdba
B. gcbdafe
C. gcdbfea
D. fedgcba

gate1996 data-structures binary-tree easy

Answer ☟

3.6.19 Binary Tree: GATE CSE 1997 | Question: 16 top☝ ☛ https://gateoverflow.in/2276

A size-balanced binary tree is a binary tree in which for every node the difference between the number of nodes in the
left and right subtree is at most 1. The distance of a node from the root is the length of the path from the root to the
node. The height of a binary tree is the maximum distance of a leaf node from the root.

A. Prove, by using induction on h, that a size-balance binary tree of height h contains at least 2h nodes.
B. In a size-balanced binary tree of height h ⩾ 1 , how many nodes are at distance h − 1 from the root? Write only the answer
without any explanations.

gate1997 data-structures binary-tree normal descriptive proof

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 359

Answer ☟

3.6.20 Binary Tree: GATE CSE 1998 | Question: 20 top☝ ☛ https://gateoverflow.in/1734

Draw the binary tree with node labels a, b, c, d, e, f and g for which the inorder and postorder traversals result in the
following sequences:

Inorder: a f b c d g e

Postorder: a f c g e d b

gate1998 data-structures binary-tree descriptive

Answer ☟

3.6.21 Binary Tree: GATE CSE 2000 | Question: 1.14 top☝ ☛ https://gateoverflow.in/637

Consider the following nested representation of binary trees: (X Y Z) indicates Y and Z are the left and
right subtrees, respectively, of node X . Note that Y and Z may be NULL , or further nested. Which of the following
represents a valid binary tree?

A. (1 2 (4 5 6 7))
B. (1 (2 3 4) 5 6) 7)
C. (1 (2 3 4) (5 6 7))
D. (1 (2 3 NULL) (4 5))

gate2000-cse data-structures binary-tree easy

Answer ☟

3.6.22 Binary Tree: GATE CSE 2000 | Question: 2.16 top☝ ☛ https://gateoverflow.in/663

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
B. LASTIN = LASTPRE
C. LASTPRE = LASTPOST
D. None of the above

gate2000-cse data-structures binary-tree normal

Answer ☟

3.6.23 Binary Tree: GATE CSE 2002 | Question: 2.12 top☝ ☛ https://gateoverflow.in/842

A weight-balanced tree is a binary tree in which for each node, the number of nodes in the left sub tree is at least half
and at most twice the number of nodes in the right sub tree. The maximum possible height (number of nodes on the
path from the root to the furthest leaf) of such a tree on n nodes is best described by which of the following?

A. log2 n
B. log 4 n
3
C. log3 n
D. log 3 n
2

gate2002-cse data-structures binary-tree normal

Answer ☟

3.6.24 Binary Tree: GATE CSE 2002 | Question: 6 top☝ ☛ https://gateoverflow.in/859

Draw all binary trees having exactly three nodes labeled A, B and C on which preorder traversal gives the sequence
C, B, A.
gate2002-cse data-structures binary-tree easy descriptive

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


360 3 Programming and DS: DS (213)

3.6.25 Binary Tree: GATE CSE 2004 | Question: 35 top☝ ☛ https://gateoverflow.in/1032

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. inorder and postorder
III. preorder and inorder
IV. level order and postorder

A. I only
B. II, III
C. III only
D. IV only

gate2004-cse data-structures binary-tree normal

Answer ☟

3.6.26 Binary Tree: GATE CSE 2004 | Question: 43 top☝ ☛ https://gateoverflow.in/1040

Consider the following C program segment


struct CellNode{
struct CellNode *leftChild
int element;
struct CellNode *rightChild;
};

int Dosomething (struct CellNode *ptr)


{
int value = 0;
if(ptr != NULL)
{
if (ptr -> leftChild != NULL)
value = 1 + DoSomething (ptr -> leftChild);
if (ptr -> rightChild != NULL)
value = max(value, 1 + Dosomething (ptr -> rightChild));
}
return(value);
}

The value returned by the function DoSomething when a pointer to the root of a non-empty tree is passed as argument is

A. The number of leaf nodes in the tree


B. The number of nodes in the tree
C. The number of internal nodes in the tree
D. The height of the tree

gate2004-cse data-structures binary-tree normal

Answer ☟

3.6.27 Binary Tree: GATE CSE 2006 | Question: 13 top☝ ☛ https://gateoverflow.in/974

A scheme for storing binary trees in an array X is as follows. Indexing of X starts at 1 instead of 0. the root is stored at
X[1]. For a node stored at X[i], the left child, if any, is stored in X[2i] and the right child, if any, in X[2i + 1]. To be
able to store any binary tree on n vertices the minimum size of X should be

A. log2 n
B. n
C. 2n + 1
D. 2n − 1

gate2006-cse data-structures binary-tree normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 361

3.6.28 Binary Tree: GATE CSE 2007 | Question: 12 top☝ ☛ https://gateoverflow.in/1210

The height of a binary tree is the maximum number of edges in any root to leaf path. The maximum number of nodes in
a binary tree of height h is:

A. 2h − 1
B. 2h−1 − 1
C. 2h+1 − 1
D. 2h+1

gate2007-cse data-structures binary-tree easy

Answer ☟

3.6.29 Binary Tree: GATE CSE 2007 | Question: 13 top☝ ☛ https://gateoverflow.in/1211

The maximum number of binary trees that can be formed with three unlabeled nodes is:

A. 1
B. 5
C. 4
D. 3

gate2007-cse data-structures binary-tree normal

Answer ☟

3.6.30 Binary Tree: GATE CSE 2007 | Question: 39, UGCNET-June2015-II: 22 top☝ ☛ https://gateoverflow.in/1237

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:

A. d e b f g c a
B. e d b g f c a
C. e d b f g c a
D. d e f g b c a

gate2007-cse data-structures binary-tree normal ugcnetjune2015ii

Answer ☟

3.6.31 Binary Tree: GATE CSE 2007 | Question: 46 top☝ ☛ https://gateoverflow.in/1244

Consider the following C program segment where CellNode represents a node in a binary tree:
struct CellNode {
struct CellNode *leftChild;
int element;
struct CellNode *rightChild;
};

int Getvalue (struct CellNode *ptr) {


int value = 0;
if (ptr != NULL) {
if ((ptr->leftChild == NULL) &&
(ptr->rightChild == NULL))
value = 1;
else
value = value + GetValue(ptr->leftChild)
+ GetValue(ptr->rightChild);
}
return(value);
}

The value returned by GetV alue when a pointer to the root of a binary tree is passed as its argument is:

A. the number of nodes in the tree

© Copyright GATE Overflow. Some rights reserved.


362 3 Programming and DS: DS (213)

B. the number of internal nodes in the tree


C. the number of leaf nodes in the tree
D. the height of the tree

gate2007-cse data-structures binary-tree normal

Answer ☟

3.6.32 Binary Tree: GATE CSE 2010 | Question: 10 top☝ ☛ https://gateoverflow.in/2183

In a binary tree with n nodes, every node has an odd number of descendants. Every node is considered to be its own
descendant. What is the number of nodes in the tree that have exactly one child?

A. 0
B. 1
(n−1)
C. 2
D. n − 1

gate2010-cse data-structures binary-tree normal

Answer ☟

3.6.33 Binary Tree: GATE CSE 2011 | Question: 29 top☝ ☛ https://gateoverflow.in/2131

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?

A. 0
B. 1
C. n!
1 2n
D. n+1 . Cn

gate2011-cse binary-tree normal

Answer ☟

3.6.34 Binary Tree: GATE CSE 2012 | Question: 47 top☝ ☛ https://gateoverflow.in/2163

The height of a tree is defined as the number of edges on the longest path in the tree. The function shown in the pseudo-
code below is invoked as height (root) to compute the height of a binary tree rooted at the tree pointer root.
int height(treeptr n)
{ if(n == NULL) return -1;
if(n -> left == NULL)
if(n -> right == NULL) return 0;
else return B1; // Box 1

else{h1 = height(n -> left);


if(n -> right == NULL) return (1+h1);
else{h2 = height(n -> right);
return B2; // Box 2
}
}
}

The appropriate expressions for the two boxes B1 and B2 are:

A. B1: (1 + height(n → right)); B2: (1 + max(h1, h2))


B. B1: (height(n → right)) ; B2: (1 + max(h1, h2))
C. B1: height(n → right) ; B2: max(h1, h2)
D. B1: (1 + height(n → right)) ; B2: max(h1, h2)

gate2012-cse data-structures binary-tree normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 363

3.6.35 Binary Tree: GATE CSE 2014 Set 1 | Question: 12 top☝ ☛ https://gateoverflow.in/1776

Consider a rooted n node binary tree represented using pointers. The best upper bound on the time required to
determine the number of subtrees having exactly 4 nodes is O(na logb n). Then the value of a + 10b is __________.

gate2014-cse-set1 data-structures binary-tree numerical-answers normal

Answer ☟

3.6.36 Binary Tree: GATE CSE 2015 Set 1 | Question: 25 top☝ ☛ https://gateoverflow.in/8223

The height of a tree is the length of the longest root-to-leaf path in it. The maximum and minimum number of nodes in
a binary tree of height 5 are

A. 63 and 6, respectively
B. 64 and 5, respectively
C. 32 and 6, respectively
D. 31 and 5, respectively

gate2015-cse-set1 data-structures binary-tree easy

Answer ☟

3.6.37 Binary Tree: GATE CSE 2015 Set 2 | Question: 10 top☝ ☛ https://gateoverflow.in/8059

A binary tree T has 20 leaves. The number of nodes in T having two children is ______.

gate2015-cse-set2 data-structures binary-tree normal numerical-answers

Answer ☟

3.6.38 Binary Tree: GATE CSE 2015 Set 3 | Question: 25 top☝ ☛ https://gateoverflow.in/8428

Consider a binary tree T that has 200 leaf nodes. Then the number of nodes in T that have exactly two children are
______.

gate2015-cse-set3 data-structures binary-tree normal numerical-answers

Answer ☟

3.6.39 Binary Tree: GATE CSE 2016 Set 2 | Question: 36 top☝ ☛ https://gateoverflow.in/39597

Consider the following New-order strategy for traversing a binary tree:

Visit the root;


Visit the right subtree using New-order;
Visit the left subtree using New-order;

The New-order traversal of the expression tree corresponding to the reverse polish expression
3 4 * 5 - 2 ^ 6 7 * 1 + -

is given by:

A. +−167∗2∧5 − 34∗
B. −+1∗67∧2−5∗34
C. −+1∗76∧2 − 5 ∗ 43
D. 1 7 6 ∗ + 2 5 4 3 ∗ − ∧−

gate2016-cse-set2 data-structures binary-tree normal

Answer ☟

3.6.40 Binary Tree: GATE CSE 2018 | Question: 20 top☝ ☛ https://gateoverflow.in/204094

The postorder traversal of a binary tree is 8, 9, 6, 7, 4, 5, 2, 3, 1. The inorder traversal of the same tree is
8, 6, 9, 4, 7, 2, 5, 1, 3 . The height of a tree is the length of the longest path from the root to any leaf. The height of the
binary tree above is _____

© Copyright GATE Overflow. Some rights reserved.


364 3 Programming and DS: DS (213)

gate2018-cse data-structures binary-tree numerical-answers

Answer ☟

3.6.41 Binary Tree: GATE CSE 2019 | Question: 46 top☝ ☛ https://gateoverflow.in/302802

Let T be a full binary tree with 8 leaves. (A full binary tree has every level full.) Suppose two leaves a and b of T are
chosen uniformly and independently at random. The expected value of the distance between a and b in T (ie., the
number of edges in the unique path between a and b) is (rounded off to 2 decimal places) _________.

gate2019-cse numerical-answers data-structures binary-tree

Answer ☟

3.6.42 Binary Tree: GATE CSE 2021 Set 2 | Question: 16 top☝ ☛ https://gateoverflow.in/357524

Consider a complete binary tree with 7 nodes. Let A denote the set of first 3 elements obtained by performing Breadth-
First Search (BFS) starting from the root. Let B denote the set of first 3 elements obtained by performing Depth-First
Search (DFS) starting from the root.

The value of ∣A − B∣ is _____________

gate2021-cse-set2 numerical-answers data-structures binary-tree

Answer ☟

3.6.43 Binary Tree: GATE IT 2004 | Question: 54 top☝ ☛ https://gateoverflow.in/3697

Which one of the following binary trees has its inorder and preorder traversals as BCAD and ABCD, respectively?

A.

B.

C.

D.

gate2004-it binary-tree easy data-structures

Answer ☟

3.6.44 Binary Tree: GATE IT 2005 | Question: 50 top☝ ☛ https://gateoverflow.in/3811

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

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 365

the height of the tree is h > 0 , then the minimum number of nodes in the tree is

A. 2h−1
B. 2h−1 + 1
C. 2h − 1
D. 2h

gate2005-it data-structures binary-tree normal

Answer ☟

3.6.45 Binary Tree: GATE IT 2006 | Question: 71 top☝ ☛ https://gateoverflow.in/3615

An array X of n distinct integers is interpreted as a complete binary tree. The index of the first element of the array is
0. The index of the parent of element X[i], i ≠ 0 , is?

A. ⌊ ⌋
i
2

i−1
B. ⌈ ⌉
2

C. ⌈ ⌉
i
2

D. ⌈ ⌉ − 1
i
2

gate2006-it data-structures binary-tree normal

Answer ☟

3.6.46 Binary Tree: GATE IT 2006 | Question: 73 top☝ ☛ https://gateoverflow.in/3617

An array X of n distinct integers is interpreted as a complete binary tree. The index of the first element of the array is
0. If the root node is at level 0, the level of element X[i], i ≠ 0 , is
A. ⌊log2 i⌋
B. ⌈log2 (i + 1)⌉
C. ⌊log2 (i + 1)⌋
D. ⌈log2 i⌉

gate2006-it data-structures binary-tree normal

Answer ☟

3.6.47 Binary Tree: GATE IT 2006 | Question: 9 top☝ ☛ https://gateoverflow.in/3548

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
B. 11
C. 12
D. 15

gate2006-it data-structures binary-tree normal

Answer ☟

3.6.48 Binary Tree: GATE IT 2008 | Question: 46 top☝ ☛ https://gateoverflow.in/3356

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.

I. MBCAFHP Y K

© Copyright GATE Overflow. Some rights reserved.


366 3 Programming and DS: DS (213)

II. KAMCBY P FH
III. MABCKY FP H

Pick the true statement from the following.

A. 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
D. II and III are the preorder and inorder sequences, respectively

gate2008-it data-structures normal binary-tree

Answer ☟

3.6.49 Binary Tree: GATE IT 2008 | Question: 76 top☝ ☛ https://gateoverflow.in/3390

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 neighbours.
n3 can be expressed as
A. n1 + n2 − 1
B. n1 − 2
C. [((n1 + n2 )/2)]
D. n2 − 1

gate2008-it data-structures binary-tree normal

Answer ☟

3.6.50 Binary Tree: GATE IT 2008 | Question: 77 top☝ ☛ https://gateoverflow.in/3391

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 neighbours.
Starting with the above tree, while there remains a node v of degree two in the tree, add an edge between the two neighbours of
v and then remove v from the tree. How many edges will remain at the end of the process?
A. 2 ∗ n1 − 3
B. n2 + 2 ∗ n1 − 2
C. n3 − n2
D. n2 + n1 − 2

gate2008-it data-structures binary-tree normal

Answer ☟

Answers: Binary Tree

3.6.1 Binary Tree: GATE CSE 1987 | Question: 2c top☝ ☛ https://gateoverflow.in/80579

 Yes it is possible since we can create Binary search tree , we know every Binary search tree is binary tree also but
there are many binary tree possible , so we know that there is many binary tree possible without inorder.

So, answer is NO for this question


Refer: http://www.geeksforgeeks.org/if-you-are-given-two-traversal-sequences-can-you-construct-the-binary-tree/
References

 21 votes -- Prashant Singh (47.1k points)

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 367

3.6.2 Binary Tree: GATE CSE 1987 | Question: 2g top☝ ☛ https://gateoverflow.in/80588

 Condition for binary tree is atmost two immediate child for every internal node

No, it is not the condition for binary tree.


 21 votes -- Prashant Singh (47.1k points)

3.6.3 Binary Tree: GATE CSE 1987 | Question: 7b top☝ ☛ https://gateoverflow.in/82427

 We can do as follows:


Root

Pre : K L N M P R Q S T

Post : N L K P R M S Q T
Left Root Right

 21 votes -- kirti singh (2.6k points)

3.6.4 Binary Tree: GATE CSE 1988 | Question: 7i top☝ ☛ https://gateoverflow.in/94366

Height of a binary tree is the longest path from it’s root to any of its leaves.

With number of nodes as n,

Max height possible: n-1 (skewed binary trees)

Min height possible: floor(log2 n) (perfect binary trees)

An AVL tree is a height-balanced binary tree where the difference between the heights of the left subtree and the right
subtree cannot exceed 1 for all nodes.
 3 votes -- Ramyanee (131 points)

3.6.5 Binary Tree: GATE CSE 1988 | Question: 7ii top☝ ☛ https://gateoverflow.in/94367

Balancing factor = the height of left subtree − the height of right subtree
Balancing factors of all the nodes are marked in the figure.
Since there is no node that has a balancing factor greater than 1, we can say that the tree is balanced.
 4 votes -- Akash (1.1k points)

Balance Factor = height (left Sub Tree )− height (right Sub Tree )

© Copyright GATE Overflow. Some rights reserved.


368 3 Programming and DS: DS (213)

for height balance tree, balance factor of every node should be from −1 to 1 i. e. (−1, 0, 1)

So, given tree is height balanced tree.


 3 votes -- Gurdeep (6.7k points)

3.6.6 Binary Tree: GATE CSE 1988 | Question: 7iii top☝ ☛ https://gateoverflow.in/94368

 13 is less than 14, so it is placed on the left side of 14

Now need to be rebalanced. Here 17 is unbalanced, So, in the 2nd tree we need 1 right rotation to 17.

Now, 12 is unbalanced.To balance it we need 1 right rotation and 1 left rotation

 9 votes -- srestha (85.2k points)

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 369

3.6.7 Binary Tree: GATE CSE 1990 | Question: 3-iv top☝ ☛ https://gateoverflow.in/84828

 Here, n denotes the number of external (leaf) nodes and not the total number of nodes.

A. By adding an edge to the root of a skewed binary tree of say 10 nodes, we get a binary tree of 11 nodes having 2 external
nodes of path lengths 9 and 1 respectively giving EPL = 9 + 1 = 10 > 22 . So, option A is false.
B. This is always TRUE. The minimum EPL for a given number of external nodes n happens for a full binary tree. In this
case when we have n external nodes each will have a path length of log2 n giving EPL = n log2 n. Now, if we try to
add any amount of skeweness to this full binary tree we can see that EPL > n log2 n.
C. False as shown for option A.
D. False as shown for option B.

Correct option: B.
 2 votes -- Arjun Suresh (330k points)

3.6.8 Binary Tree: GATE CSE 1991 | Question: 01,viii top☝ ☛ https://gateoverflow.in/506

 This is straightforward. The nodes of the given tree are given in square boxes. The weights associated with the
nodes are the numbers example 15, 9, 10 etc.

Weighted path length = ∑ (for(each node in the tree) (path length) ∗(weight of the node) ).
n
= ∑ Path Lengthi ∗ Weight of Nodei
i=1

So answer (written in path_length * weight form) = 4 ∗ 2 + 4 ∗ 4 + 4 ∗ 5 + 4 ∗ 7 + 3 ∗ 9 + 3 ∗ 10 + 1 ∗ 15 = 144.


 52 votes -- arvchamp (131 points)

3.6.9 Binary Tree: GATE CSE 1991 | Question: 1,ix top☝ ☛ https://gateoverflow.in/502

 During the in-order traversal algorithm, the left subtree is explored first, followed by root, and finally nodes on
the right subtree.
In order traversal is : 4 1 6 7 3 2 5 8.
 22 votes -- Keith Kr (4.5k points)

3.6.10 Binary Tree: GATE CSE 1991 | Question: 14,a top☝ ☛ https://gateoverflow.in/541

 This is min-heap. It is obvious looking at the tree.


We cant use binary search as it is a heap.
 29 votes -- Akash Kanase (36k points)

3.6.11 Binary Tree: GATE CSE 1991 | Question: 14,b top☝ ☛ https://gateoverflow.in/43026

 Since the given binary tree is a min-heap tree.

First swap 27 and 5


Then delete 5
Apply min-heapify

And structure will be:

© Copyright GATE Overflow. Some rights reserved.


370 3 Programming and DS: DS (213)

 18 votes -- Manoj Kumar (26.7k points)

3.6.12 Binary Tree: GATE CSE 1991 | Question: 14,c top☝ ☛ https://gateoverflow.in/43027

 By looking at the values it is clear that It is a Min-Heap Data structures. We know that Heap Data structures are
stored in the array.
⟹ Delete procedure for Min-Heap Data Structure (If you already know the value and position of the node):

1. Replace that node with the last element of that tree.


2. Apply Heapify property on that node.

For Example, Let If I want to delete 1, then I will replace that with 27. and apply heapify on that node. Or if i want to delete
5 then also I will replace that with 27, and apply heapify on that node.
Time Complexity: In this case, time complexity will not be more than O(log n).
⟹ Delete procedure for Min-Heap Data Structure (If you know the value but not position) :

1. Find the position of the number by sequential search. (In the worst case it will take O(n) time).
2. Replace that node with the last element of that tree.
3. Apply heapify property at that node.

Time Complexity: Wort time complexity of this algorithm will be O(n + log n) i.e. O(n).
Note: This is a standard problem of Minimum element deletion from the Min-heap tree. The minimum element always
resides at top (Root node). We just replace that value with the last element of the tree and apply heapify at the root node. The
time complexity of that algorithm is O(log n).
Here I have written the second method only to show that if we have to delete any of the nodes, and we just know the value
but not the position. Since in question it is mentioned that Arbitrary node.
 44 votes -- Muktinath Vishwakarma (23.9k points)

3.6.13 Binary Tree: GATE CSE 1993 | Question: 16 top☝ ☛ https://gateoverflow.in/2313

 Base Case :- When we have just root then, there are no non leaf nodes. So No of leaves = 1, No of non leaf
nodes is = 0. Base case holds.
Induction Hypothesis :- Assume that now for k internal nodes we will have k + 1 leaves.
Inducting on no of leaves, Now we add 2 more leaves to this tree. One of k + 1 leaf will become internal node. So now we
will have k + 1 internal node. No of leafs will be K + 1 − 1 ( 1 leaf just became internal node) +2(New leafs) . So we
proved that for any binary tree, in which every non-leaf node has 2-descendants, the number of leaves in the tree is one more
than the number of non-leaf nodes.
 16 votes -- Akash Kanase (36k points)

3.6.14 Binary Tree: GATE CSE 1994 | Question: 8 top☝ ☛ https://gateoverflow.in/2504


PRE ORDER: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
POST ORDER : 3, 5, 4, 2, 7, 8, 6, 10, 11, 12, 9, 1

We can draw the tree, but in the question it is not specified if it is binary or ternary or something else.
Lets assume it is a binary tree.
Pre oder: Data, Left, Right (First node should be root)
(First node should be root, next to the root node should be left node of root, if in the post-order it is not in the second last
position)
Post order: Left, Right, Data
(Last node should be root, before the last node it should be right node of root, if in pre-order it is not in the second position)
Now we can conclude that 9 is right of 1 and 2 is left of 1.

PRE ORDER : 1, 2, 3, 4, 5, 6, 7, 8 , 9, 10, 11, 12


POST ORDER : 3, 5, 4, 2, 7, 8, 6 , 10, 11, 12, 9 ,1.

We can clearly observe that, the right of root contains 9, 10, 11, 12 ⟹ we can leave 9 as its position is fixed as immediate
right of root.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 371

So remaining elements are 10, 11, 12.


What is pre-order of those elements ?

10, 11, 12

What is the post order of those elements?

10, 11, 12

Is it possible in Binary Tree? (check all 5 trees which can formed by 3 nodes)
NO

Now lets consider a Ternary Tree

  


root non-root elements

PRE ORDER : 1 , 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12


POST ORDER : 3, 5, 4, 2, 7, 8, 6, 10, 11, 12, 9 , 1
non-root elements

2 is left most and 9 is right most, the children of 9 are 10, 11, 12 from left to right.


subtree of 9, but order unknown

PRE ORDER : 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12



Right most child of root

POST ORDER : 3, 5, 4, 2, 7, 8, 6, 10, 11, 12, 9

Check all the elements in the preorder after 9− those should be children of 9.
After checking the preorder and postorder we can conclude that all those elements are at the same level in the order
10 − 11 − 12.


Should be the leftmost child of rootElements before 2 in the postordermust be children of 2

PRE ORDER : 2 , 3, 4, 5, 6, 7, 8
POST ORDER : 3, 5, 4 , 2, 7, 8, 6

Should be a subtree of 2but order in unknown

How we separated 3, 4 and 5 as two parts?


Check the preorder: 3 ⟹ elements before 3 in the postorder are in the same subtree as 3 but there are no elements before
3.

© Copyright GATE Overflow. Some rights reserved.


372 3 Programming and DS: DS (213)

Therefore 3 is separated from 4 and 5.


How we fixed 4 and 5 in that order?
Check the preorder: 4 ⟹ elements before 4 in the postorder are in the same subtree of 4. Therefore 5 is in the same
subtree of 4.

PRE ORDER : 6, 7, 8
POST ORDER : 7, 8 ,6

Should be a sub-tree of 6but order is unknown

We can easily understand that 6 is the child of root. Elements before 6 in the postorder forms subtree of 6.

How we fixed 7 and 8 in that order?


Check the preorder: 7 ⟹ elements before 7 in the postorder are in the same subtree of 7 but there are no elements before
7.
Therefore 7 and 8 are separated.
 33 votes -- Shaik Masthan (50.4k points)

3.6.15 Binary Tree: GATE CSE 1995 | Question: 1.17 top☝ ☛ https://gateoverflow.in/2604

 In Binary Tree a node can have at most 2 children.


Total number of node N = node with 0 child + node with 1 child + node with 2 child.

⟹ N = n0 + n1 + n2 ( here, in question it is given that no. of leaf nodes i.e no. of nodes with 0 children is n so
n0 = n)
⟹ N = n + n1 + n2
Total number of edges e = N − 1, and also e = n ∗ 0 + n1 ∗ 1 + n2 ∗ 2

∴ N − 1 = n ∗ 0 + n1 ∗ 1 + n2 ∗ 2
⟹ n + n1 + n2 − 1 = n1 ∗ 1 + n2 ∗ 2

⟹ n2 = n − 1
Option B is answer.
NOTE - For the tree, the d egree of a node is defined as the number of sub-trees of the node or no of children of a node.
 71 votes -- Umang Raman (12.2k points)

3.6.16 Binary Tree: GATE CSE 1995 | Question: 6 top☝ ☛ https://gateoverflow.in/2667

 There are only five such binary trees. This is given by 3rd Catalan number as here we are finding the number of
structurally similar binary trees with 3 nodes.

1. One with C as root and left child as A and right child B.


2. Second with C as root, B as left child and A as again left child of B.
3. Third with C as root, B as left child and A as right child of B.
4. Fourth with C as root, B as right child and A as right child of B.
5. Fifth with C as root, B as right child and A as left child of B.

References

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 373

 29 votes -- Gate Keeda (15.9k points)

3.6.17 Binary Tree: GATE CSE 1996 | Question: 1.14 top☝ ☛ https://gateoverflow.in/2718

 (B).

a, b, c will become unbalanced with Balance factor as +2, +2, +2 respectively. Balance factor should be −1, 0, +1.

Balance factor = Height(LST) - Height(RST)

Or Balance factor = | Height(LST) - Height(RST) |


 27 votes -- Gate Keeda (15.9k points)

3.6.18 Binary Tree: GATE CSE 1996 | Question: 1.15 top☝ ☛ https://gateoverflow.in/2719

 Correct Option: C

Left → Right → Root.

Ref: https://gateoverflow.in/2718/gate1996_1-14
References

 18 votes -- Gate Keeda (15.9k points)

3.6.19 Binary Tree: GATE CSE 1997 | Question: 16 top☝ ☛ https://gateoverflow.in/2276


a. Prove, by using induction on h, that a size-balanced binary tree of height h contains at least 2h nodes.
When
h = 0 ……… least no. of nodes = 20 = 1
h = 1 ……… least no. of nodes = 21 = 2
h = 2 ……… least no. of nodes = 22 = 4
Assume that the rule is true for h = k
Then the min no. of nodes = 2k nodes
If we increase the height by 1 by adding a node, we must also add nodes to fill the (max level −1) level.
This would mean doubling the nodes
Thus 2k+1
Hence, proved

b. In a size-balanced binary tree of height h ≥ 1 , how many nodes are at distance h − 1 from the root? Write only the
answer
without any explanation
2h−1

 16 votes -- Sachin Mittal (15.8k points)

3.6.20 Binary Tree: GATE CSE 1998 | Question: 20 top☝ ☛ https://gateoverflow.in/1734

 The binary tree will be

© Copyright GATE Overflow. Some rights reserved.


374 3 Programming and DS: DS (213)

 23 votes -- Anu (4.7k points)

3.6.21 Binary Tree: GATE CSE 2000 | Question: 1.14 top☝ ☛ https://gateoverflow.in/637


A. → (4 5 6 7) this part of answer is not correct. We have (X Y Z) not (W X Y Z) . So, this is wrong
B. → 3 closing paranthesis, 2 opening paranthesis. This is wrong.
C. CORRECT
D. → Here in (1 (2 3 NULL) (4 5)), (4 5) this is not allowed. So this is wrong. (It should be (4, 5, NULL) )

 35 votes -- Akash Kanase (36k points)

3.6.22 Binary Tree: GATE CSE 2000 | Question: 2.16 top☝ ☛ https://gateoverflow.in/663

 Inorder : Left → Root → Right

Preorder : Root → Left → Right

Postorder: Left → Right → Root

If the binary tree is full (last level is fully filled), the last visited node in Inorder and Preorder must be the rightmost one in
the last level. But for a complete binary tree this need not be the case (in a complete binary tree last level need not be fully
filled) and LASTPRE will be from the second last level in case the complete binary tree is not full. So, choice (D).
 53 votes -- Arjun Suresh (330k points)

3.6.23 Binary Tree: GATE CSE 2002 | Question: 2.12 top☝ ☛ https://gateoverflow.in/842

 Let nl and nr nodes be present in the left and right sub-trees respectively.

nr
We have, ≤ nl ≤ 2nr . Without loss of generality, let the left sub-tree have greater number of nodes (2nr nodes). Then,
2
2(n−1)
nr + 2nr + 1 = n . Thus we get, nl = 3 and nr = n−1 3 .

Total number of nodes can be described by the recurrence:

2(n−1)
3 )+T(
T(n) = T ( n−1 3 ) + 1 and T(1) = 1

As this makes maximum nodes go to one subtree and that is what we want to get the maximum height with a given number
of nodes.

Now, the height of the tree will be: H(n) = H( 23 (n − 1)) + 1 and H(1) = 1

We can draw a recurrence tree and the cost at each level is 1, and the height will be log 3 (n).
2
So, D option is the answer.
 84 votes -- Arjun Suresh (330k points)

3.6.24 Binary Tree: GATE CSE 2002 | Question: 6 top☝ ☛ https://gateoverflow.in/859

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 375

5 Binary trees.
 22 votes -- Anu (4.7k points)

3.6.25 Binary Tree: GATE CSE 2004 | Question: 35 top☝ ☛ https://gateoverflow.in/1032

 Following combination can uniquely identify a tree.

Inorder and Preorder.


Inorder and Postorder.
Inorder and Level-order.

And following do not.

Postorder and Preorder.


Preorder and Level-order.
Postorder and Level-order.

Answer: B
 26 votes -- Shikhar Vashishth (3.1k points)

3.6.26 Binary Tree: GATE CSE 2004 | Question: 43 top☝ ☛ https://gateoverflow.in/1040

 Correct Option: D

It calculates Height of tree.

Easy way to get this answer .

Draw a tree where all 4 parameters are different.

Get a Tree for which Height, No of Internal Nodes & No of Leafs are different & Trace out this algorithm.
 31 votes -- Akash Kanase (36k points)

3.6.27 Binary Tree: GATE CSE 2006 | Question: 13 top☝ ☛ https://gateoverflow.in/974

 Answer is D.

' To be able to store " any " binary tree on n vertices the minimum size of X should be

" Any Binary Tree and Size should be minimum " .


So We must consider worst case binary tree for this situation and find the minimum space required .
Minimum size for any binary tree
−−−
⟹ Minimum size of worst case binary tree
X[i] = nodeX[2i] = Left childX[2i + 1] = Rightchild
Let n = 3

© Copyright GATE Overflow. Some rights reserved.


376 3 Programming and DS: DS (213)

X[1] X[1]
=A X[1] = A =A
X[2] X[3]
X[2] = B
=B X[4] = C =B
X[3] X[7]
=C =C
n 2n−1 2n − 1
Minimum size Best Case binary tree Minimum size Worst Case binary tree
 73 votes -- Akhil Nadh PC (16.5k points)

Answer should be (D).


Since binary tree can be of any form, the worst case happens for right skewed binary tree. Now, root goes to index 1, its child
goes to index 3, its child goes to index 7 and so on the nth vertex goes to 2n − 1 th index of array.
 34 votes -- Shaun Patel (6.1k points)

3.6.28 Binary Tree: GATE CSE 2007 | Question: 12 top☝ ☛ https://gateoverflow.in/1210

 2h+1 − 1 just try this taking a small complete binary

never try to remember these formulae as remembering formulae is an overhead try to take examples in such cases.

Correct Answer: C
 36 votes -- Bhagirathi Nayak (11.7k points)

3.6.29 Binary Tree: GATE CSE 2007 | Question: 13 top☝ ☛ https://gateoverflow.in/1211

 Can be found with formula... (2nCn/n + 1)... n being the number of nodes. for the given question... where
n = 3 ... answer is 5. Let me also specify here.. that number of Binary Search Trees with n nodes is equal to number
of unlabeled Binary trees.
http://gatecse.in/wiki/Number_of_Binary_trees_possible_with_n_nodes
Correct Answer: B
References

 26 votes -- Gate Keeda (15.9k points)

3.6.30 Binary Tree: GATE CSE 2007 | Question: 39, UGCNET-June2015-II: 22 top☝ ☛ https://gateoverflow.in/1237

 The answer is A.
Take the first node in preorder traversal - a will be the root of the tree
All nodes to the left of 'a' in inorder traversal will be in the left subtree of ' a' and all elements on the right will be in the right
subtree of 'a'.
Take the second element from preorder traversal - 'b' - goes to left subtree of ' a' as it is in the left of ' a' in inorder list.
Proceeding likewise we can construct the binary tree as:

 20 votes -- Gate Keeda (15.9k points)

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 377

3.6.31 Binary Tree: GATE CSE 2007 | Question: 46 top☝ ☛ https://gateoverflow.in/1244

 Answer: C
As the function returns 1 if and only if any node has both left & right children as NULL (that node is a leaf node). Hence,
value gets incremented at each leaf node.
 24 votes -- Rajarshi Sarkar (27.8k points)

3.6.32 Binary Tree: GATE CSE 2010 | Question: 10 top☝ ☛ https://gateoverflow.in/2183

 0 because every node has an odd number of descendants so least odd number 1 and every node is considered to
be its own descendant so all nodes have even number of descendants (0, 2, 4, 6...) so every node has either 0
children or 2 children...
 45 votes -- Murali (419 points)

3.6.33 Binary Tree: GATE CSE 2011 | Question: 29 top☝ ☛ https://gateoverflow.in/2131

 With n nodes, there are 2n Cn


distinct tree structures possible.
(n+1)

Corresponding to each structure, only one binary search tree (BST) can be formed because inorder is fixed.

Here, we are already given one such structure therefore only one tree possible.

If binary trees would have been asked, n! trees would have been possible corresponding to each distinct tree structure. Here,
tree structure is fixed and hence, we can have only one possibility for BST as elements are distinct. For general cases:
http://gatecse.in/wiki/Number_of_Binary_trees_possible_with_n_nodes

Correct Answer: B
References

 67 votes -- Anurag Semwal (6.7k points)

Given binary tree is unlabeled . So as it is given we are not allowed to change the formation of tree. Then To make it BST we
can use atmost 1 way . As for particular structure we can not use n! arrangement of nodes (Becasue they are labeled and it is
BST not BT)
 29 votes -- Palash (1.2k points)

3.6.34 Binary Tree: GATE CSE 2012 | Question: 47 top☝ ☛ https://gateoverflow.in/2163

 Answer is option A.
From the diagram below we are able to see how this works :

© Copyright GATE Overflow. Some rights reserved.


378 3 Programming and DS: DS (213)

 45 votes -- Amar Vashishth (25.2k points)

3.6.35 Binary Tree: GATE CSE 2014 Set 1 | Question: 12 top☝ ☛ https://gateoverflow.in/1776

 Answer: 1..

Explanation:

1. Come to the 4th level up from the leaf node of the given binary tree, which can be done using tree traversal in O(n).
2. For each node present in the level check whether it's subtree having exactly 4 nodes.. which can be done in constant time
for each node, since it's subtree having constant number of nodes..
3. nodes in the level is less than n.. so its complexity is O(n)

Therefore, a = 1 and b = 0

a + 10b = 1... <- Answer


 60 votes -- Vicky Bajoria (4.1k points)

We need to traverse all nodes at least once, and we need only one traversal. If num(child1) + num(child2) + 1 = 4,
then output yes.

So, a must be 1 and b = 0 ⟹ a + 10b = 1.


 75 votes -- Arjun Suresh (330k points)

3.6.36 Binary Tree: GATE CSE 2015 Set 1 | Question: 25 top☝ ☛ https://gateoverflow.in/8223

 Option A is correct because height 5 means level 6 so maximum node = 2l − 1 = 26 − 1 = 63


and for minimum, at each level only single node so total 6.

 36 votes -- Anoop Sonkar (4.1k points)

3.6.37 Binary Tree: GATE CSE 2015 Set 2 | Question: 10 top☝ ☛ https://gateoverflow.in/8059

' In A binary tree if there are


N leaf nodes then the number of nodes having 2 children will be N-1

Proof :

' Key idea is find number of edges using Degree and find number of edges using nodes and equate them

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 379

Let l be the number of leaf nodes, D1 be the number of nodes with one child and D2 be the number of nodes with two
children.
Sum of Degrees, D = 1 × l + 3 × D2 + 2 × D1 − 1(for root)
(Root is having one degree less because it is not having a parent)
D = l + 3D2 + 2D1 − 1 → (1)
Number of edges, e = D
2
Number of nodes, n = D2 + D1 + l
A tree with n nodes has n − 1 edges so,
D =D +D +l−1
2 2 1 → (2)
From (1) and (2)
l+3D2 +2D1 −1
2 = D2 + D1 + l − 1
⟹ D2 = l − 1
So, the number of nodes in T having two children = 20 − 1 = 19
 11 votes -- Rishi yadav (9k points)

3.6.38 Binary Tree: GATE CSE 2015 Set 3 | Question: 25 top☝ ☛ https://gateoverflow.in/8428

 Let number of nodes with exactly two children be x, and with exactly one children be y.

Total degree = 200 + 3x + 2y − 1 (As all nodes with 2 children have degree 3 except the root)

No. of nodes= x + y + 200

No. of edges =Total degree/2 = (200 + 3x + 2y − 1)/2 [Handshaking Theorem]

No. of edges in a tree = No. of nodes −1

So, (200 + 3x + 2y − 1) = 2x + 2y + 400 − 2

x = 199
 67 votes -- Arjun Suresh (330k points)

3.6.39 Binary Tree: GATE CSE 2016 Set 2 | Question: 36 top☝ ☛ https://gateoverflow.in/39597

 Expression given in reverse polish notation (i,e in Post-order)

convert first it into In-order

34 ∗ 5 − 2 ∧ 67 ∗ 1 + −

(3 ∗ 4) 5 − 2 ∧ 6 7 ∗ 1 + −

((3 ∗ 4) − 5) 2 ∧ 6 7 ∗ 1 + −

(((3 ∗ 4) − 5) ∧ 2) 6 7 ∗ 1 + −

(((3 ∗ 4) − 5) ∧ 2) (6 ∗ 7) 1 + −

(((3 ∗ 4) − 5) ∧ 2) ((6 ∗ 7) + 1) −

((((3 ∗ 4) − 5) ∧ 2) − ((6 ∗ 7) + 1))

so Inorder expression in ((((3 ∗ 4) − 5) ∧ 2) − ((6 ∗ 7) + 1))

New-Order traversal is as by ROOT RIGHT LEFT

((((3 ∗ 4) − 5) ∧ 2) − ((6 ∗ 7) + 1))

© Copyright GATE Overflow. Some rights reserved.


380 3 Programming and DS: DS (213)

−((6 ∗ 7) + 1)(((3 ∗ 4) − 5) ∧ 2)

− + 1(6 ∗ 7)(((3 ∗ 4) − 5) ∧ 2)

− + 1 ∗ 7 6(((3 ∗ 4) − 5) ∧ 2)

− + 1 ∗ 7 6 ∧ 2((3 ∗ 4) − 5)

− + 1 ∗ 7 6 ∧ 2 − 5(3 ∗ 4)

−+1∗76∧2−5∗43

option C is correct
 70 votes -- Praveen Saini (41.9k points)

It is quite simple actually.

Postorder: left, right, root

Neworder: Root, right, left

(left, right, root) and (Root, right, left) are reverse of each other, right ?

So, these two traversals will be exact reverse of each other! Option (c)!
 159 votes -- Ashish Deshmukh (1.3k points)

3.6.40 Binary Tree: GATE CSE 2018 | Question: 20 top☝ ☛ https://gateoverflow.in/204094

Nodes in longest path from Root to Leaf = (1 − 2, 2 − 4, 4 − 6, 6 − 8) or (1 − 2, 2 − 4, 4 − 6, 6 − 9)


|Longest Path| = |(1 − 2, 2 − 4, 4 − 6, 6 − 8)| = 4
 26 votes -- Digvijay (44.9k points)

3.6.41 Binary Tree: GATE CSE 2019 | Question: 46 top☝ ☛ https://gateoverflow.in/302802

' Two leaves a and b of T are chosen uniformly and independently at random.

See the word "independently" here. It means that choice of a must not affect choice of b and vice versa. This implies that
both a and b can even be the same node.
Now, we are given that the binary tree has 8 leaves. (23 = 8) ⟹ we have 3 levels in the tree starting from 0. The
distance in terms of number of edges between any two leaf nodes will always be even . If we consider any two leaves (not
necessarily distinct)

No. of pairs with path length 0 = 8. (When a = b)


No. of pairs with path length 2 = 8. (For each of the 8 leaf nodes, we have a pair and since the selection is independent
order of the pair is also significant)
No. of pairs with path length 4 = 16. (For each leaf node we have to go two levels up and while coming down we have 2

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 381

choices. So, we get 8 × 2 = 16 pairs)


No. of pairs with path length 6 = 32. (For each leaf node we have to go till the root, and from there while coming down
it has 2 × 2 = 4 choices. Thus we get 8 × 4 = 32 pairs.

Total number of possible pairs = 8 × 8 = 64

So, expected path length


8 8 16 32 272
=0× 64 +2× 64 +4× 64 +6× 64 = 64 = 4.25
 80 votes -- Arjun Suresh (330k points)

3.6.42 Binary Tree: GATE CSE 2021 Set 2 | Question: 16 top☝ ☛ https://gateoverflow.in/357524

 Complete binary tree property has this property that every level until last is fully filled and last level is filled from
left to right.

So, when we have a complete binary tree with 7 nodes,

level1 has 1 node ( root )


level2 has 2 nodes.
level3 has 4 nodes.

BFS goes level by level. So first three elements (say Set A) = level1 nodes (1) + level2 (2) nodes.

DFS is go by connected manner. So first three elements (say Set B ) = level1 nodes (1) + one node from level2 nodes +
one node from level3 nodes which is connected to the previously chosen level2 node.
A– B = the remaining node from the set of level2 nodes.

⟹ |A– B| = 1.
 2 votes -- Shaik Masthan (50.4k points)

3.6.43 Binary Tree: GATE IT 2004 | Question: 54 top☝ ☛ https://gateoverflow.in/3697

 Answer is D.
Inorder traversal is left node right.

Preorder is node left right.


 24 votes -- Sankaranarayanan P.N (8.5k points)

3.6.44 Binary Tree: GATE IT 2005 | Question: 50 top☝ ☛ https://gateoverflow.in/3811

Correct Option: B

Since the difference between the nodes in left and right subtree must hold for every node, until the last to last to last level, all
levels must be fully filled. So, we get 2h−1 − 1 nodes (No. of nodes in a complete binary tree of height h − 2). Now, our
aim is to increase two more levels by adding minimum no. of nodes- just add two in nodes one below other to any of the
nodes. So, we get 2h−1 + 1 nodes.
 46 votes -- Sneha Goel (819 points)

3.6.45 Binary Tree: GATE IT 2006 | Question: 71 top☝ ☛ https://gateoverflow.in/3615

 Option is (D).

Left child of ith element will be at 2 ∗ i + 1 and right child at 2(i + 1)


 39 votes -- Sankaranarayanan P.N (8.5k points)

3.6.46 Binary Tree: GATE IT 2006 | Question: 73 top☝ ☛ https://gateoverflow.in/3617

© Copyright GATE Overflow. Some rights reserved.


382 3 Programming and DS: DS (213)

PS : the value inside the node is array index

A. FALSE , ⌊log2 i⌋ = ⌊log2 1⌋ = 0 but X[1] is at level 1


B. FALSE , ⌈log2 (i + 1)⌉ = ⌈log2 (4 + 1)⌉ = ⌈log2 (5)⌉ = 3 but X[4] is at level 2
C. Correct
D. FALSE , ⌈log2 i⌉ = ⌈log2 1⌉ = 0 but X[1] is at level 1

 21 votes -- Gate Ranker18 (2.4k points)

3.6.47 Binary Tree: GATE IT 2006 | Question: 9 top☝ ☛ https://gateoverflow.in/3548

 A node in a binary tree has degree 0, 1 or 2.


Ref: http://faculty.cs.niu.edu/~mcmahon/CS241/Notes/bintree.html
We are given no. of 1 degree node = 5, no. of 2 degree nodes = 10.
Total no. of edges = 1 ∗ 5 + 2 ∗ 10 = 25 (In tree degree is for outgoing edges only, and hence each degree corresponds to
an edge)
So, total no. of nodes = 25 + 1 = 26 (No. of nodes in a tree is 1 more than no. of edges).
Now, no. of leaf nodes (nodes with 0 degree) = 26 − 5 − 10 = 11 .
Correct Answer: B
References

 84 votes -- Arjun Suresh (330k points)

3.6.48 Binary Tree: GATE IT 2008 | Question: 46 top☝ ☛ https://gateoverflow.in/3356

 In preorder, root comes at the beginning of the traversal sequence and in postorder, root comes at the last of the
traversal sequence. So, out of the given sequences only 1 and 2 are having such kind of order i.e K at the beginning
and at the last.

Therefore, 2 is the preorder and 1 is postorder and the left sequence i.e 3 will definitely be inorder.

So, option D is correct.


 36 votes -- Vivek sharma (2.1k points)

3.6.49 Binary Tree: GATE IT 2008 | Question: 76 top☝ ☛ https://gateoverflow.in/3390

 Given definition of degree: no of neighbours of a node.


total nodes = n = n1 + n2 + n3
Apply handshaking lemma:
Sum of degrees = 2∗no of edges
1 ∗ n1 + 2 ∗ n2 + 3 ∗ n3 = 2(n − 1)
Total number of edges in graph will always be (n1 + n2 + n3 − 1) .
1 ∗ n1 + 2 ∗ n2 + 3 ∗ n3 = 2(n1 + n2 + n3 − 1)
n1 + 2n2 + 3n3 = 2n1 + 2n2 + 2n3 − 2
n3 = n1 − 2 Option B
 66 votes -- swagnikd (561 points)

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 383

3.6.50 Binary Tree: GATE IT 2008 | Question: 77 top☝ ☛ https://gateoverflow.in/3391

 Initially, n1 ∗ 1 + n2 ∗ 2 + n3 ∗ 3 = 2(n1 + n2 + n3 − 1) ⟹ n3 = n1 − 2

Now we have removed all 2 degree nodes, so number of edges in final graph is n1 + n3 − 1.

Put n3 = n1 − 2, we get

Number of edges = 2 ∗ n1 − 3
 74 votes -- Sumit1311 (1.4k points)

From the above tree, we will get the tree below

Now, check with the options we will get (A) as the answer.
 40 votes -- Shreyans Dhankhar (2.1k points)

3.7 Graph Search (1) top☝

3.7.1 Graph Search: GATE CSE 1989 | Question: 3-ixa top☝ ☛ https://gateoverflow.in/87143

Which one of the following statements (s) is/are FALSE?

A. Overlaying is used to run a program, which is longer than the address space of the computer.
B. Optimal binary search tree construction can be performed efficiently by using dynamic programming.
C. Depth first search cannot be used to find connected components of a graph.
D. Given the prefix and postfix walls over a binary tree, the binary tree can be uniquely constructed.

normal gate1989 binary-tree graph-search multiple-selects

Answer ☟

Answers: Graph Search

3.7.1 Graph Search: GATE CSE 1989 | Question: 3-ixa top☝ ☛ https://gateoverflow.in/87143

A. FALSE according to definition of address space given in the link. whatever memory used by the overlay comes
under the address space of computer "https://en.wikipedia.org/wiki/Address_space".
B. TRUE Optimal binary search tree construction can be performed efficiently by using dynamic programming.
ref: http://www.geeksforgeeks.org/dynamic-programming-set-24-optimal-binary-search-tree/
C. FALSE Depth first search can be used to find connected components of a graph.
D. FALSE Infix + (postfix or prefix) is req. to construct the binary tree uniquely.

References

© Copyright GATE Overflow. Some rights reserved.


384 3 Programming and DS: DS (213)

 12 votes -- Lokesh Dafale (8.2k points)

3.8 Graphs (5) top☝

3.8.1 Graphs: GATE CSE 1997 | Question: 6.2 top☝ ☛ https://gateoverflow.in/2258

Let G be the graph with 100 vertices numbered 1 to 100. Two vertices i and j are adjacent if |i − j| = 8 or
|i − j| = 12. The number of connected components in G is
A. 8
B. 4
C. 12
D. 25

gate1997 data-structures normal graphs

Answer ☟

3.8.2 Graphs: GATE CSE 2008 | Question: 42 top☝ ☛ https://gateoverflow.in/1872

G is a graph on n vertices and 2n − 2 edges. The edges of G can be partitioned into two edge-disjoint spanning trees.
Which of the following is NOT true for G?

A. For every subset of k vertices, the induced subgraph has at most 2k − 2 edges.
B. The minimum cut in G has at least 2 edges.
C. There are at least 2 edge-disjoint paths between every pair of vertices.
D. There are at least 2 vertex-disjoint paths between every pair of vertices.

gate2008-cse data-structures graphs normal

Answer ☟

3.8.3 Graphs: GATE CSE 2014 Set 1 | Question: 3 top☝ ☛ https://gateoverflow.in/1754

Let G = (V , E) be a directed graph where V is the set of vertices and E the set of edges. Then which one of the
following graphs has the same strongly connected components as G ?

A. G1 = (V , E1 ) where E1 = {(u, v) ∣ (u, v) ∉ E}


B. G2 = (V , E2 ) where E2 = {(u, v) ∣ (v, u) ∈ E}
C. G3 = (V , E3 ) where E3 = {(u, v)∣ there is a path of length ≤ 2 from u to v in E}
D. G4 = (V4 , E) where V4 is the set of vertices in G which are not isolated

gate2014-cse-set1 data-structures graphs ambiguous

Answer ☟

3.8.4 Graphs: GATE CSE 2016 Set 1 | Question: 38 top☝ ☛ https://gateoverflow.in/39731

Consider the weighted undirected graph with 4 vertices, where the weight of edge {i, j} is given by the entry Wij in
the matrix W .

⎡0 2 8 5⎤

W=⎢
5 8⎥
⎢ ⎥
2 0
⎢8 5 0 x⎥
⎣5 8 x 0⎦

The largest possible integer value of x, for which at least one shortest path between some pair of vertices will contain the edge
with weight x is ___________.

gate2016-cse-set1 data-structures graphs normal numerical-answers

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 385

3.8.5 Graphs: GATE IT 2008 | Question: 4 top☝ ☛ https://gateoverflow.in/3264

What is the size of the smallest MIS (Maximal Independent Set) of a chain of nine nodes?

A. 5
B. 4
C. 3
D. 2

gate2008-it data-structures normal graphs

Answer ☟

Answers: Graphs

3.8.1 Graphs: GATE CSE 1997 | Question: 6.2 top☝ ☛ https://gateoverflow.in/2258

 From the description it is clear that vertices are connected as follows:

1 − 9 − 17−. . . −97
2 − 10 − 18−. . . −98
3 − 11 − 19−. . . −99
4 − 12 − 20−. . . −100
5 − 13 − 21−. . . −93
6 − 14 − 22−. . . −94
7 − 15 − 23−. . . −95
8 − 16 − 24−. . . −96

We have covered all vertices using 8 vertex sets considering only ∣i − j ∣= 8. Using ∣i − j ∣= 12 we can see the vertex 1 is
connected to 13, 2 − 14, 3 − 15 and 4 − 16, so the top 4 vertex sets are in fact connected to the bottom 4 sets, thus
reducing the connected components to 4.

Correct Answer: B
 62 votes -- Arjun Suresh (330k points)

3.8.2 Graphs: GATE CSE 2008 | Question: 42 top☝ ☛ https://gateoverflow.in/1872

 There are 2 spanning trees (a spanning tree connects all n vertices) for G which are edge disjoint. A spanning tree
for n nodes require n − 1 edges and so 2 edge-disjoint spanning trees requires 2n − 2 edges. As G has only 2n − 2
edges, it is clear that it doesn't have any edge outside that of the two spanning trees. Now lets see the cases:

Lets take any subgraph of G with k vertices. The remaining subgraph will have n − k vertices. Between these two
subgraphs (provided both has at least one vertex) there should be at least 2 edges, as we have 2 spanning trees in G. So, (B)
is TRUE. Also, in the subgraph with k vertices, we cannot have more than 2k − 2 edges as this would mean that in the other
subgraph with n − k vertices, we would have less than 2n − 2k edges, making 2 spanning trees impossible in it. So, (A) is
also TRUE.

A spanning tree covers all the vertices. So, 2 edge-disjoint spanning trees in G means, between every pair of vertices in G we
have two edge-disjoint paths (length of paths may vary). So, (C) is also TRUE.

So, that leaves option (D) as answer. It is not quite hard to give a counter example for (D).
 49 votes -- Arjun Suresh (330k points)

3.8.3 Graphs: GATE CSE 2014 Set 1 | Question: 3 top☝ ☛ https://gateoverflow.in/1754

 (A) is false. Consider just two vertices connected to each other. So, we have one SCC. The new graph won't have
any edges and so 2 SCC.

(B) is true. In a directed graph an SCC will have a path from each vertex to every other vertex. So, changing the direction of
all the edges, won't change the SCC.

(D) is false. Consider any graph with isolated vertices- we loose those components.

(C) is a bit tricky. Any edge is a path of length 1. So, the new graph will have all the edges from old one. Also, we are adding

© Copyright GATE Overflow. Some rights reserved.


386 3 Programming and DS: DS (213)

new edges (u, v). So, does this modify any SCC? No, because we add an edge (u, v), only if there is already a path of length
<= 2 from u to v- so we do not create a new path. So, both (B) and (C) must answer, though GATE key says only B.
 63 votes -- Arjun Suresh (330k points)

3.8.4 Graphs: GATE CSE 2016 Set 1 | Question: 38 top☝ ☛ https://gateoverflow.in/39731

Let us list down the shortest edge between each pair of vertices x, y in the graph

x y shortest path from x to y


1 2 2
1 3 there is a direct path from 1 to 3 of weight 8.We can also choose to go
via node 4 with total path weight 5 + x. if 5 + x < 8(x < 3) then shortest
path is 5 + x otherwise shortest path is the weight of the direct path
which is 8
1 4 5
2 3 5
2 4 there is a direct path from 2 to 4 of weight 8. We can also choose to go
via node 3 with total path weight 5 + x. If 5 + x < 8(x < 3) the shortest
path is 5+x. otherwise shortest path is the weight of the direct path
which is 8
3 4 We can chose to go through the direct path of weight x or via nodes 2, 1
to node 4 with weight 5 + 2 + 5 = 12. If x < 12 then we will chose x to be the shortest
path otherwise 12 is the shortest path

Case 1: Let us say x < 3 . Say x = 2 .

When we put x = 2 the above table is modified as

x y shortest path from x to y


1 2 2
1 3 7
1 4 5
2 3 5
2 4 7
3 4 2 // Note that the shortest path between nodes 3 and 4 is x = 2

Case 2: 3 ≤ x < 13 . Let's say x = 12 . The table is now modified as

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 387

x y shortest path from x to y


1 2 2
1 3 8
1 4 5
2 3 5
2 4 8
3 4 12 // Note that the shortest path between nodes 3 and 4 is x = 12
and one of the shortest path is the direct edge x

Now the question asks you to find the largest possible integer value of x such that shortest path between at least one pair of
nodes in the graph is equal to x. For values x = 2, 3, 4, … , 12 the shortest path between node 3 and 4 is equal to x.
The largest among this is x = 12 . So the answer is 12
PS: If the question is modified as "The largest possible integer value of x, for which the shortest path between some pair of
vertices is guaranteed to contain the edge with weight x is"
then the answer will be 11.
Correct Answer: 12.
 78 votes -- janakyMurthy (733 points)

3.8.5 Graphs: GATE IT 2008 | Question: 4 top☝ ☛ https://gateoverflow.in/3264

 Answer: C

1−2−3−4−5−6−7−8−9

(2, 5, 8) is the maximal independent set for a chain of 9 nodes. If we add any other node to the set then it will not be MIS.
 39 votes -- Rajarshi Sarkar (27.8k points)

3.9 Hashing (16) top☝

3.9.1 Hashing: GATE CSE 1989 | Question: 1-vii, ISRO2015-14 top☝ ☛ https://gateoverflow.in/10905

A hash table with ten buckets with one slot per bucket is shown in the following figure. The symbols S1 to S7 initially
entered using a hashing function with linear probing. The maximum number of comparisons needed in searching an
item that is not present is

A. 4
B. 5
C. 6
D. 3

hashing isro2015 gate1989 algorithms normal

Answer ☟

3.9.2 Hashing: GATE CSE 1996 | Question: 1.13 top☝ ☛ https://gateoverflow.in/2717

An advantage of chained hash table (external hashing) over the open addressing scheme is

A. Worst case complexity of search operations is less

© Copyright GATE Overflow. Some rights reserved.


388 3 Programming and DS: DS (213)

B. Space used is less


C. Deletion is easier
D. None of the above

gate1996 data-structures hashing normal

Answer ☟

3.9.3 Hashing: GATE CSE 1996 | Question: 15 top☝ ☛ https://gateoverflow.in/2767

Insert the characters of the string K R P C S N Y T J M into a hash table of size 10.
Use the hash function

h(x) = (ord(x)– ord(“a”) + 1) mod 10

and linear probing to resolve collisions.

A. Which insertions cause collisions?


B. Display the final hash table.

gate1996 data-structures hashing normal descriptive

Answer ☟

3.9.4 Hashing: GATE CSE 1997 | Question: 12 top☝ ☛ https://gateoverflow.in/2272

Consider a hash table with n buckets, where external (overflow) chaining is used to resolve collisions. The hash
function is such that the probability that a key value is hashed to a particular bucket is n1 . The hash table is initially
empty and K distinct values are inserted in the table.

A. What is the probability that bucket number 1 is empty after the K th insertion?
B. What is the probability that no collision has occurred in any of the K insertions?
C. What is the probability that the first collision occurs at the K th insertion?

gate1997 data-structures hashing probability normal descriptive

Answer ☟

3.9.5 Hashing: GATE CSE 2004 | Question: 7 top☝ ☛ https://gateoverflow.in/1004

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 hash to the same value
III. All elements hash to the same value
IV. Each element hashes to a different value

A. I only
B. II only
C. I and II only
D. III or IV

gate2004-cse data-structures hashing easy

Answer ☟

3.9.6 Hashing: GATE CSE 2007 | Question: 40 top☝ ☛ https://gateoverflow.in/1238

Consider a hash table of size seven, with starting index zero, and a hash function (3x + 4) mod 7 . 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

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 389

B. 1, 8, 10 , −, −, −, 3
C. 1, −, −, −, −, −, 3
D. 1, 10, 8 , −, −, −, 3

gate2007-cse data-structures hashing easy

Answer ☟

3.9.7 Hashing: GATE CSE 2009 | Question: 36 top☝ ☛ https://gateoverflow.in/1322

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?

0
1
2 2
3 23
4
A.
5 15
6
7
8 18
9
0
1
2 12
3 13
4
B.
5 5
6
7
8 18
9
0
1
2 12
3 13
4 2
C.
5 3
6 23
7 5
8 18
9 15
0
1
2 2, 12
3 13, 3, 23
4
D.
5 5, 15
6
7
8 18
9

gate2009-cse data-structures hashing normal

© Copyright GATE Overflow. Some rights reserved.


390 3 Programming and DS: DS (213)

Answer ☟

3.9.8 Hashing: GATE CSE 2010 | Question: 52 top☝ ☛ https://gateoverflow.in/2360

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 shown as below

0
1
2 42
3 23
4 34
5 52
6 46
7 33
8
9

Which one of the following choices gives a possible order in which the key values could have been inserted in the table?

A. 46, 42, 34, 52, 23, 33


B. 34, 42, 23, 52, 33, 46
C. 46, 34, 42, 23, 52, 33
D. 42, 46, 33, 23, 34, 52

gate2010-cse data-structures hashing normal

Answer ☟

3.9.9 Hashing: GATE CSE 2010 | Question: 53 top☝ ☛ https://gateoverflow.in/43327

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 shown as below

0
1
2 42
3 23
4 34
5 52
6 46
7 33
8
9

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
B. 20
C. 30
D. 40

data-structures hashing normal gate2010-cse

Answer ☟

3.9.10 Hashing: GATE CSE 2014 Set 1 | Question: 40 top☝ ☛ https://gateoverflow.in/1918

Consider a hash table with 9 slots. The hash function is h(k) = k mod 9 . The collisions are resolved by chaining.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 391

The following 9 keys are inserted in the order: 5, 28, 19, 15, 20, 33, 12, 17, 10 . The maximum, minimum, and average chain
lengths in the hash table, respectively, are

A. 3, 0, and 1
B. 3, 3, and 3
C. 4, 0, and 1
D. 3, 0, and 2

gate2014-cse-set1 data-structures hashing normal

Answer ☟

3.9.11 Hashing: GATE CSE 2014 Set 3 | Question: 40 top☝ ☛ https://gateoverflow.in/2074

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?

A. (97 × 97 × 97)/1003
B. (99 × 98 × 97)/1003
C. (97 × 96 × 95)/1003
D. (97 × 96 × 95/(3! × 1003 )

gate2014-cse-set3 data-structures hashing probability normal

Answer ☟

3.9.12 Hashing: GATE CSE 2015 Set 2 | Question: 33 top☝ ☛ https://gateoverflow.in/8152

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?
A. h(i) = i2 mod 10
B. h(i) = i3 mod 10
C. h(i) = (11 ∗ i2 )mod 10
D. h(i) = (12 ∗ i2 )mod 10

gate2015-cse-set2 data-structures hashing normal

Answer ☟

3.9.13 Hashing: GATE CSE 2015 Set 3 | Question: 17 top☝ ☛ https://gateoverflow.in/8414

Given that hash table T with 25 slots that stores 2000 elements, the load factor a for T is _________.

gate2015-cse-set3 data-structures hashing normal numerical-answers

Answer ☟

3.9.14 Hashing: GATE IT 2006 | Question: 20 top☝ ☛ https://gateoverflow.in/3559

Which of the following statement(s) is TRUE?

I. A hash function takes a message of arbitrary length and generates a fixed length code.
II. A hash function takes a message of fixed length and generates a code of variable length.
III. A hash function may give the same hash value for distinct messages.
A. I only
B. II and III only
C. I and III only
D. II only

gate2006-it data-structures hashing normal

Answer ☟

3.9.15 Hashing: GATE IT 2007 | Question: 28 top☝ ☛ https://gateoverflow.in/3461

Consider a hash function that distributes keys uniformly. The hash table size is 20. After hashing of how many keys

© Copyright GATE Overflow. Some rights reserved.


392 3 Programming and DS: DS (213)

will the probability that any new key hashed collides with an existing one exceed 0.5.

A. 5
B. 6
C. 7
D. 10

gate2007-it data-structures hashing probability normal

Answer ☟

3.9.16 Hashing: GATE IT 2008 | Question: 48 top☝ ☛ https://gateoverflow.in/3358

Consider a hash table of size 11 that uses open addressing with linear probing. Let h(k) = k mod 11 be the hash
function used. A sequence of records with keys
43 36 92 87 11 4 71 13 14
is inserted into an initially empty hash table, the bins of which are indexed from zero to ten. What is the index of the bin into
which the last record is inserted?

A. 3
B. 4
C. 6
D. 7

gate2008-it data-structures hashing normal

Answer ☟

Answers: Hashing

3.9.1 Hashing: GATE CSE 1989 | Question: 1-vii, ISRO2015-14 top☝ ☛ https://gateoverflow.in/10905

 No of comparison in worst case for an element not in hash table is size of largest cluster +1. This is because the
probe stops as soon as an empty slot is found (we r using linear probing here).

Size of largest cluster is 4 (S6, S3, S7, S1)

No of comparison is 4 + 1 = 5

Correct Answer: B
 76 votes -- Digvijay (44.9k points)

3.9.2 Hashing: GATE CSE 1996 | Question: 1.13 top☝ ☛ https://gateoverflow.in/2717


A. False :- search operation can go worst in chaining if all elements are stored under a single bucket.
B. False . Pointer space is overhead in chaining.
C. is true BCZ in Open Adressing sometimes though element is present we cant delete it if Empty Bucket comes in between
while searching for that element ;Such Limitation is not there in Chaining.

 26 votes -- Rajesh Pradhan (18.9k points)

3.9.3 Hashing: GATE CSE 1996 | Question: 15 top☝ ☛ https://gateoverflow.in/2767

 Here Order(x) − Order ('a') means count the number of characters between character ′ x′ and ′ a′ .
Assuming a = 0, b = 1 & so on.

a. J & M cause collusion.


b. Final Hash Table

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 393

Index key
0 T
1 K
2 J
3 C
4 N
5 Y
6 P
7 M
8 R
9 S

 20 votes -- Akash Kanase (36k points)

3.9.4 Hashing: GATE CSE 1997 | Question: 12 top☝ ☛ https://gateoverflow.in/2272


n−1
A. Probability that buckets other than 1 are selected =
n
(n − 1)k
This should happen k times and each of the k events are independent so
nk
n
B. When k = 1, probability of no collision = (for only one insert, there can be no collission)
n
n n−1
For k = 2 probability of no collision = ×
n n
n n−1 n−2 n−k+1
For k = n probability of no collision = × × ×…× for k ≤ n
n n n n
For k > n probability of no collision = 0 (even though we are using chaining without a collision a chain cannot start)

k−1
C. Probability of first collision at (k = 1) =
n
n k−1
Probability of first collision at (k = 2) = ×
n n
n n−1 k−1
Probability of first collision at (k = 3) = × ×
n n n
n n−1 n−2 n−k+2 k−1
Probability of first collision at (k ≤ n) = × × ×…× ×
n n n n n
n n−1 n−2 1 n
Probability of first collision at (k = n + 1) = × × ×…× ×
n n n n n
For k > n + 1 probability of first collision = 0 (as it should have definitely happened in one of the previous (n + 1)
insertions.

 38 votes -- Danish (3.4k points)

3.9.5 Hashing: GATE CSE 2004 | Question: 7 top☝ ☛ https://gateoverflow.in/1004

 Option C is correct answer because the last digit of every digit given is equal in I and II.

 16 votes -- Bhagirathi Nayak (11.7k points)

3.9.6 Hashing: GATE CSE 2007 | Question: 40 top☝ ☛ https://gateoverflow.in/1238

 The answer is (B).


1 will occupy location 0, 3 will occupy location 6, 8 hashed to location 0 which is already occupied so, it will be hashed to
one location next to it. i.e. to location 1.

© Copyright GATE Overflow. Some rights reserved.


394 3 Programming and DS: DS (213)

Since 10 also clashes, so it will be hashed to location 2.


 22 votes -- Gate Keeda (15.9k points)

3.9.7 Hashing: GATE CSE 2009 | Question: 36 top☝ ☛ https://gateoverflow.in/1322

 (C) is the correct option ..directly from the definition of linear probing. In linear probing, when a hashed location
is already filled, locations are linearly probed until a free one is found.
http://courses.cs.washington.edu/courses/cse326/00wi/handouts/lecture16/sld015.htm
References

 29 votes -- Bhagirathi Nayak (11.7k points)

3.9.8 Hashing: GATE CSE 2010 | Question: 52 top☝ ☛ https://gateoverflow.in/2360

 Option (C)

46, 34, 42, 23, 52, 33

46− position 6
34 position 4
42 position 2
23 position 3
52 position 2− collision next empty is 5
33 position 3− collision next empty is 7

 19 votes -- Sankaranarayanan P.N (8.5k points)

3.9.9 Hashing: GATE CSE 2010 | Question: 53 top☝ ☛ https://gateoverflow.in/43327

 53 - option (C).

Slots 3, 4, 5 and 6 must be filled before 33 comes. Similarly slots 2, 3 and 4 must be filled before 52 comes. And 52 must
come before 33, as it is not occupying slot 2. So, 33 must be at the end and 52 can come at position 4 or 5.

Let 52 come at position 4. Slots 2, 3 and 4 must be filled before 52 leaving only slot 6 left for the element coming at
position 5 which should be 46. So, the first 3 elements can come in any order giving 3! = 6 ways.

Let 52 come at position 5. Now, the first four elements can come in any order. So, 4! = 24 ways.

So, total number of different insertion sequences possible = 24 + 6 = 30


 67 votes -- Arjun Suresh (330k points)

answer = option C
the element 33 has managed to hold position at slot #7 it means elements should occupy slot #3 to slot #6 before it in the
sequence. Currently, it seems like all element except 42 should come before 33 in the sequence.
But, element 52 requires that 42 comes before it. and 33 requires that 52 comes before it. This means that 42 has to come
before 33. this makes element 33 to occupy last position in the sequence.
now for element 52 to occupy its place these can be two cases :

Case 1 : {42, 23, 34} , 52


Case 2: {42, 23, 34, 46} , 52

Case 1 means that those three elements comes before 52 = 3! = 6ways


Case 2 means that those four elements comes before 52 = 4! = 24ways
Combining all info we get,
Total number of sequences possible that will form the same hash table as above = (6 + 24) × 1 = 30

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 395

 61 votes -- Amar Vashishth (25.2k points)

3.9.10 Hashing: GATE CSE 2014 Set 1 | Question: 40 top☝ ☛ https://gateoverflow.in/1918

So, Maximum & minimum chain lengths are 3 & 0 respectively.


Average chain length = (0 + 3 + 1 + 1 + 0 + 1 + 2 + 0 + 1)/9 = 1 .
So, Answer is A.
 40 votes -- Jay (831 points)

3.9.11 Hashing: GATE CSE 2014 Set 3 | Question: 40 top☝ ☛ https://gateoverflow.in/2074

 We have 100 slots each of which are picked with equal probability by the hash function (since hashing is uniform).
So, to avoid first 3 slots, the hash function has to pick from the remaining 97 slots. And repetition is allowed, since
chaining is used- meaning a list of elements are stored in a slot and not a single element.
97 97 97
So, required probability = 100 × 100 × 100

= (97 × 97 × 97)/1003

Correct Answer: A
 88 votes -- Arjun Suresh (330k points)

3.9.12 Hashing: GATE CSE 2015 Set 2 | Question: 33 top☝ ☛ https://gateoverflow.in/8152

 Since mod 10 is used, the last digit matters.


If we CUBE all numbers from 0 to 9, we get the 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 to 10 buckets. If we make a table for square, we won't get equal
distribution as shown in the following table. 1, 4, 6 and 9 are repeated, so these buckets would have more entries and there
are no buckets corresponding to 2, 3, 7 and 8.

© Copyright GATE Overflow. Some rights reserved.


396 3 Programming and DS: DS (213)

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
http://geeksquiz.com/gate-gate-cs-2015-set-2-question-43/
Correct Answer: B
References

 87 votes -- Anu (4.7k points)

3.9.13 Hashing: GATE CSE 2015 Set 3 | Question: 17 top☝ ☛ https://gateoverflow.in/8414

 A critical statistic for a hash table is the load factor, that is the number of entries divided by the number of
buckets:
Load factor = n/k
where:
n = number of entries
k = number of buckets
As the load factor grows larger, the hash table becomes slower, and it may even fail to work (depending on the method used).
Here, load factor = 2000/25 = 80
 33 votes -- Akash Kanase (36k points)

3.9.14 Hashing: GATE IT 2006 | Question: 20 top☝ ☛ https://gateoverflow.in/3559

 Answer is (C).

I. A hash function takes a message of arbitrary length and generates a fixed length code.. This is correct, this is directly
from definition of hash function. Ref: https://en.wikipedia.org/wiki/Hash_function

II. As I is correct II is wrong !

III. This is true. example: Hash function N%10 , this will generate same values for 1 as well as 11!

(Even in cryptographic hash functions collision happens, just that it is not easy to find colliding instances!)
References

 30 votes -- Akash Kanase (36k points)

3.9.15 Hashing: GATE IT 2007 | Question: 28 top☝ ☛ https://gateoverflow.in/3461

 The question is a bit ambiguous.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 397

'
0.5.
After hashing of how many keys, will the probability that any new key hashed collides with an existing one exceed

Here, 'new key hashed' is the ambiguity. It can mean the probability of a collision in the next 'hash', or the probability of a
collision in any of the hashes of the 'new keys' starting from the first insertion. For the first case answer must be 10 to get
probability equal to 0.5, and so 11 must be the answer for probability > 0.5. Thus we can conclude from given choices, it is
the second case.
So, we need to find n such that after n hashes, probability of collision (in any of the n hashes) > 0.5.
Probability that there will be a collision after n hashes (a collision happened in at least one of those n hashes)
= 1−Probability that there was no collision in the first n hashes
20−n+1
= 1 − 1. 19
20 .
18
20 … 20 .
So, we need,
18 … 20−n+1 .
0.5 < 1 − 1. 19
20 . 20 20
19 . 18 20−n+1
⟹ 20 20 … 20 < 0.5 .
For n = 5 , we get, 0.5814 and for n = 6 , we get 0.43605. So, answer should be n = 6 .
Correct Answer: B
 69 votes -- Arjun Suresh (330k points)

3.9.16 Hashing: GATE IT 2008 | Question: 48 top☝ ☛ https://gateoverflow.in/3358


Index key
0 87
1 11
2 13
3 36
4 92
5 4
6 71
7 14
8
9
10 43

(D) is answer
 17 votes -- Prashant Singh (47.1k points)

3.10 Heap (24) top☝

3.10.1 Heap: GATE CSE 1990 | Question: 2-viii top☝ ☛ https://gateoverflow.in/83993

Match the pairs in the following questions:

(a) A heap construction (p) Ω(n log10 n)


(b) Constructing Hashtable with linear probing (q) O(n)
(c) AVL tree construction (r) O(n2 )
(d) Digital trie construction (s) O(n log10 n)

gate1990 match-the-following data-structures heap

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


398 3 Programming and DS: DS (213)

3.10.2 Heap: GATE CSE 1996 | Question: 2.11 top☝ ☛ https://gateoverflow.in/2740

The minimum number of interchanges needed to convert the array into a max-heap is

89, 19, 40, 17, 12, 10, 2, 5, 7, 11, 6, 9, 70


A. 0
B. 1
C. 2
D. 3

gate1996 data-structures heap easy

Answer ☟

3.10.3 Heap: GATE CSE 1999 | Question: 12 top☝ ☛ https://gateoverflow.in/1511

A. In binary tree, a full node is defined to be a node with 2 children. Use induction on the height of the binary tree to prove
that the number of full nodes plus one is equal to the number of leaves.
B. Draw the min-heap that results from insertion of the following elements in order into an initially empty min-heap:
7, 6, 5, 4, 3, 2, 1 . Show the result after the deletion of the root of this heap.

gate1999 data-structures heap normal descriptive

Answer ☟

3.10.4 Heap: GATE CSE 2001 | Question: 1.15 top☝ ☛ https://gateoverflow.in/708

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
B. ⌊ 2i ⌋
C. ⌈ 2i ⌉
(i+1)
D. 2

gate2001-cse data-structures heap easy

Answer ☟

3.10.5 Heap: GATE CSE 2003 | Question: 23 top☝ ☛ https://gateoverflow.in/1110

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)

gate2003-cse data-structures heap

Answer ☟

3.10.6 Heap: GATE CSE 2004 | Question: 37 top☝ ☛ https://gateoverflow.in/1034

The elements 32, 15, 20, 30, 12, 25, 16, are inserted one by one in the given order into a maxHeap. The resultant
maxHeap is

A.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 399

B.

C.

D.

gate2004-cse data-structures heap normal

Answer ☟

3.10.7 Heap: GATE CSE 2005 | Question: 34 top☝ ☛ https://gateoverflow.in/1370

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:

A. 10, 8, 7, 5, 3, 2, 1
B. 10, 8, 7, 2, 3, 1, 5
C. 10, 8, 7, 1, 2, 3, 5
D. 10, 8, 7, 3, 2, 1, 5

gate2005-cse data-structures heap normal

Answer ☟

3.10.8 Heap: GATE CSE 2006 | Question: 10 top☝ ☛ https://gateoverflow.in/889

In a binary max heap containing n numbers, the smallest element can be found in time

A. O(n)
B. O(log n)
C. O(log log n)
D. O(1)

gate2006-cse data-structures heap easy

Answer ☟

3.10.9 Heap: GATE CSE 2006 | Question: 76 top☝ ☛ https://gateoverflow.in/1852

Statement for Linked Answer Questions 76 & 77:

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.

76. Which one of the following is a valid sequence of elements in an array representing 3-ary max heap?

A. 1, 3, 5, 6, 8, 9

© Copyright GATE Overflow. Some rights reserved.


400 3 Programming and DS: DS (213)

B. 9, 6, 3, 1, 8, 5
C. 9, 3, 6, 8, 5, 1
D. 9, 5, 6, 8, 3, 1

gate2006-cse data-structures heap normal

Answer ☟

3.10.10 Heap: GATE CSE 2006 | Question: 77 top☝ ☛ https://gateoverflow.in/87191

Statement for Linked Answer Questions 76 & 77:

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.
76. Which one of the following is a valid sequence of elements in an array representing 3−ary max heap?

A. 1, 3, 5, 6, 8, 9
B. 9, 6, 3, 1, 8, 5
C. 9, 3, 6, 8, 5, 1
D. 9, 5, 6, 8, 3, 1

77. Suppose the elements 7, 2, 10 and 4 are inserted, in that order, into the valid 3-ary max heap found in the previous
question, Q.76. Which one of the following is the sequence of items in the array representing the resultant heap?

A. 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
D. 10, 8, 6, 9, 7, 2, 3, 4, 1, 5

gate2006-cse data-structures heap normal

Answer ☟

3.10.11 Heap: GATE CSE 2007 | Question: 47 top☝ ☛ https://gateoverflow.in/1245

Consider the process of inserting an element into a Max Heap, where the Max Heap is represented by an array.
Suppose we perform a binary search on the path from the new leaf to the root to find the position for the newly inserted
element, the number of comparisons performed is:

A. Θ(log2 n)
B. Θ(log2 log2 n)
C. Θ(n)
D. Θ(n log2 n)

gate2007-cse data-structures heap normal

Answer ☟

3.10.12 Heap: GATE CSE 2009 | Question: 59 top☝ ☛ https://gateoverflow.in/1341

Consider a binary max-heap implemented using an array.


Which one of the following array represents a binary max-heap?

A. {25, 12, 16, 13, 10, 8, 14}


B. {25, 14, 13, 16, 10, 8, 12}
C. {25, 14, 16, 13, 10, 8, 12}
D. {25, 14, 12, 13, 10, 8, 16}

gate2009-cse data-structures heap normal

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 401

Answer ☟

3.10.13 Heap: GATE CSE 2009 | Question: 60 top☝ ☛ https://gateoverflow.in/43466

Consider a binary max-heap implemented using an array.


What is the content of the array after two delete operations on {25, 14, 16, 13, 10, 8, 12}

A. {14, 13, 12, 10, 8}


B. {14, 12, 13, 8, 10}
C. {14, 13, 8, 12, 10}
D. {14, 13, 12, 8, 10}

gate2009-cse data-structures heap normal

Answer ☟

3.10.14 Heap: GATE CSE 2011 | Question: 23 top☝ ☛ https://gateoverflow.in/2125

A max-heap is a heap where the value of each parent is greater than or equal to the value of its children. Which of the
following is a max-heap?

A.

B.

C.

D.

gate2011-cse data-structures heap easy

Answer ☟

3.10.15 Heap: GATE CSE 2014 Set 2 | Question: 12 top☝ ☛ https://gateoverflow.in/1967

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:

A. 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

gate2014-cse-set2 data-structures heap normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


402 3 Programming and DS: DS (213)

3.10.16 Heap: GATE CSE 2015 Set 1 | Question: 32 top☝ ☛ https://gateoverflow.in/8273

Consider a max heap, represented by the array: 40, 30, 20, 10, 15, 16, 17, 8, 4 .

Array index 1 2 3 4 5 6 7 8 9
Value 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

A. 40, 30, 20, 10, 15, 16, 17, 8, 4, 35


B. 40, 35, 20, 10, 30, 16, 17, 8, 4, 15
C. 40, 30, 20, 10, 35, 16, 17, 8, 4, 15
D. 40, 35, 20, 10, 15, 16, 17, 8, 4, 30

gate2015-cse-set1 data-structures heap easy

Answer ☟

3.10.17 Heap: GATE CSE 2015 Set 2 | Question: 17 top☝ ☛ https://gateoverflow.in/8091

Consider a complete binary tree where the left and right subtrees of the root are max-heaps. The lower bound for the
number of operations to convert the tree to a heap is

A. Ω(log n)
B. Ω(n)
C. Ω(n log n)
D. Ω(n2 )

gate2015-cse-set2 data-structures heap normal

Answer ☟

3.10.18 Heap: GATE CSE 2015 Set 3 | Question: 19 top☝ ☛ https://gateoverflow.in/8418

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

A. 4
B. 5
C. 2
D. 3

gate2015-cse-set3 data-structures heap normal

Answer ☟

3.10.19 Heap: GATE CSE 2016 Set 1 | Question: 37 top☝ ☛ https://gateoverflow.in/39706

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)
B. O(d) but not O(1)
C. O(2d ) but not O(d)
D. O(d 2d ) but not O(2d )

gate2016-cse-set1 data-structures heap normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 403

3.10.20 Heap: GATE CSE 2016 Set 2 | Question: 34 top☝ ☛ https://gateoverflow.in/39585

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 _________.

gate2016-cse-set2 data-structures heap normal numerical-answers

Answer ☟

3.10.21 Heap: GATE CSE 2019 | Question: 40 top☝ ☛ https://gateoverflow.in/302808

Consider the following statements:

I. The smallest element in a max-heap is always at a leaf node


II. The second largest element in a max-heap is always a child of a root node
III. A max-heap can be constructed from a binary search tree in Θ(n) time
IV. A binary search tree can be constructed from a max-heap in Θ(n) time

Which of te above statements are TRUE?

A. I, II and III
B. I, II and IV
C. I, III and IV
D. II, III and IV

gate2019-cse data-structures heap

Answer ☟

3.10.22 Heap: GATE IT 2004 | Question: 53 top☝ ☛ https://gateoverflow.in/3696

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)
B. O(n)
C. O(n log log n)
D. O(n log n)

gate2004-it data-structures heap normal

Answer ☟

3.10.23 Heap: GATE IT 2006 | Question: 44 top☝ ☛ https://gateoverflow.in/3587

Which of the following sequences of array elements forms a heap?

A. {23, 17, 14, 6, 13, 10, 1, 12, 7, 5}


B. {23, 17, 14, 6, 13, 10, 1, 5, 7, 12}
C. {23, 17, 14, 7, 13, 10, 1, 5, 6, 12}
D. {23, 17, 14, 7, 13, 10, 1, 12, 5, 7}

gate2006-it data-structures heap easy

Answer ☟

3.10.24 Heap: GATE IT 2006 | Question: 72 top☝ ☛ https://gateoverflow.in/3616

An array X of n distinct integers is interpreted as a complete binary tree. The index of the first element of the array is
0. If only the root node does not satisfy the heap property, the algorithm to convert the complete binary tree into a heap
has the best asymptotic time complexity of

A. O(n)
B. O(log n)
C. O(n log n)
D. O(n log log n)

© Copyright GATE Overflow. Some rights reserved.


404 3 Programming and DS: DS (213)

gate2006-it data-structures heap easy

Answer ☟

Answers: Heap

3.10.1 Heap: GATE CSE 1990 | Question: 2-viii top☝ ☛ https://gateoverflow.in/83993

 (A) A heap Construction(Build heap) : -


Build-Heap (A)

1. heap-size[A] ← length[A]
2. for i ← ⌊length[A]/2⌋ downto 1
3. do Heapify (A, i)

Note that A[(⌊n/2⌋ + 1) … n] are all leaves so they are length 1 heaps.
Trivial Analysis: Each call to Heapify requires log(n) time, we make n such calls ⟹ O(n log n).
Tighter Bound: Each call to Max-Heapify requires time O(h) where h is the height of node i. Therefore running time is
log n log n
× O(h) = O (n ∑ h )
h h

h=0 2 +1
h
h=0 2

where 2h + 1 = Number of nodes at height h and O(h) = Running time for each node.

= O (n ∑ ) = O(n)
h
h=0 2h

h
Note: ∑∞
h=0 =2
2h
Reference:

https://courses.csail.mit.edu/6.006/fall10/handouts/recitation10-8.pdf
http://www.cs.fsu.edu/~burmeste/slideshow/chapter7/7-3.html

(B) Constructing Hash table with linear probing for n elements has time complexity ⟹ O(n2 ) in the worst case. This
happens when all the n elements are hashed to the same location and this means the number of probes will go like
n.(n−1)
0, 1, 2, 3, … n − 1 for the n elements giving the total number of probes 2 which is O(n2 ).
(C) AVL Tree construction : -

AVL trees are height-balanced binary search trees.


Balance factor of a node : height(left subtree) − height(right subtree).
An AVL tree has balance factor calculated at every node, for every node, heights of left and right subtree can differ by no
more than 1.
Constructing an AVL tree, to create a tree we have to insert n elements in it. To insert the element in a balanced tree
we need log(n). Therefore we can do this with O(n log(n)) time complexity.
We can traverse an AVL tree in O(n) time and the inorder traversal gives the sorted list of n elements. Since, sorting of
n elements takes minimum Ω(n log n) time this also implies that creation of AVL tree is Ω(n log n).
From above two points we get the time complexity of AVL tree creation as Θ(n log n)

Reference:

https://stackoverflow.com/questions/17629668/difference-between-the-time-complexity-required-to-build-binary-search-
tree-and
https://courses.cs.washington.edu/courses/cse373/06sp/handouts/lecture12.pdf
https://www.cs.auckland.ac.nz/software/AlgAnim/AVL.html

(D) Digital trie construction of n keys with maximum length m requires O(n × m) time. Among the options m is not
specified and assuming m is constant (small length keys), the time complexity will be O(n) which is also O(n log n). So,
(s) gets mapped to (D) and (p) to (C) though both (p) and (s) are possible for (C).

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 405

Correct Answer:
A − q, B − r, C − p, D − s
References

 11 votes -- Lakshman Patel (64.9k points)

3.10.2 Heap: GATE CSE 1996 | Question: 2.11 top☝ ☛ https://gateoverflow.in/2740

 "The minimum number of interchanges needed to convert the array


89, 19, 40, 17, 12, 10, 2, 5, 7, 11, 6, 9, 70
into a heap with the maximum element at the root node is:"

This is the correction.

Answer: C.

Only element 70 violates the rule. Hence, it must be shifted to its proper position.
Step1: swap(10, 70)
Step2: swap(40, 70)
Hence, only 2 interchanges are required.
 24 votes -- Gate Keeda (15.9k points)

3.10.3 Heap: GATE CSE 1999 | Question: 12 top☝ ☛ https://gateoverflow.in/1511


a. Note My Convention:-
Number of full nodes = F
Number of leaf node = L
----------------------------------------------------------------
Base Case: H = 0 .
A binary tree of height 0 is just a single node with no children, and therefore has 1 leaf.
F+1=L
0+1=1
so the base case satisfies the induction hypothesis (see below).
Induction Hypothesis (I.H.): Suppose that for some k ≥ 0 , all binary trees of height ≤ k have (F + 1) = L leaves .
Induction Step: Let T be a binary tree of height k + 1. Then T ′ s left and right subtrees are each binary trees of height
≤ k, and thus by the I.H. both subtree have (F + 1) leaves. The number of leaves in T is equal to the sum of the number
of leaves in T 's subtrees,
(F + 1) (left sub tree) +(F + 1) (right sub tree) = L (left sub tree) +L (right sub tree)
2F + 2 = 2L
2(F + 1) = 2(L)
∴ F + 1 = L (proved)
Hence, the hypothesis holds for k + 1, and so the theorem is proved.

b. Here in question they mentioned to insert element in given order into an empty Heap.
So here we have to use Insertion Method to create the heap instead of using Heapify Method to build the heap.
Please refer the below image where the LHS shows the resultant heap after doing insertion of the keys into initial empty
heap.
RHS heap is the result of deletion of root.

© Copyright GATE Overflow. Some rights reserved.


406 3 Programming and DS: DS (213)

 24 votes -- Rajesh Pradhan (18.9k points)

3.10.4 Heap: GATE CSE 2001 | Question: 1.15 top☝ ☛ https://gateoverflow.in/708

 for node at index i

left child(L) at 2i

right child(R) at 2i + 1

for node at index i

parent will be at floor i/2

Correct Answer: B
 27 votes -- Pooja Palod (24.1k points)

3.10.5 Heap: GATE CSE 2003 | Question: 23 top☝ ☛ https://gateoverflow.in/1110

 Time to find the smallest element on a min-heap- one retrieve operation - Θ(1)
Time to find the second smallest element on a min-heap- requires 22 − 1 = 3 check operations to find the second
smallest element out of 3 elements - Θ(1)

Time to find the 7th smallest element - requires O(27 − 1) = O(127) check operations to find the seventh smallest element
out of 127 possible ones - Θ(1)

In short if the number of required operations is independent of the input size n, then it is always Θ(1).

(Here, we are doing a level order traversal of the heap and checking the elements)

If we are not allowed to traverse the heap and allowed only default heap-operations, we will be restricted with doing Extract-
min 7 times which would be O(log n).

Correct Answer: D
 98 votes -- gatecse (62.6k points)

3.10.6 Heap: GATE CSE 2004 | Question: 37 top☝ ☛ https://gateoverflow.in/1034

 The answer is option A.

Just keep inserting elements making sure resulting Tree is nearly Complete. (Heap Property) .
While inserting any node, if you find that Value of New Node > Value of its parent, bubble it up to keep Max heap property

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 407

 22 votes -- Akash Kanase (36k points)

3.10.7 Heap: GATE CSE 2005 | Question: 34 top☝ ☛ https://gateoverflow.in/1370

 Answer is (D)
Whenever we insert an element in heap, it will be in last level from left to right. So, here we insert element 1 and 7 as
children of node 5. Then we perform heapify algorithm until we get the min/max heap. So, finally we get the heap whose
level order traversal is 10, 8, 7, 3, 2, 1, 5
Initial heap:

After insert of 1

After insert of 7

 19 votes -- neha pawar (3.3k points)

3.10.8 Heap: GATE CSE 2006 | Question: 10 top☝ ☛ https://gateoverflow.in/889


A. O(n)

In a max heap, the smallest element is always present at a leaf node. Heap being a complete binary tree, there can be up
to n2 leaf nodes and to examine all of them we would need O(n) time.

 40 votes -- Keith Kr (4.5k points)

3.10.9 Heap: GATE CSE 2006 | Question: 76 top☝ ☛ https://gateoverflow.in/1852

 D.
The method to solve is clearly given in the question itself. Just one thing to mention is the heap property. Max Heap =
The parent is always greater or equal to the child. if not then swap the respective child with the parent to satisfy the property
of the heap.
 11 votes -- Gate Keeda (15.9k points)

3.10.10 Heap: GATE CSE 2006 | Question: 77 top☝ ☛ https://gateoverflow.in/87191

© Copyright GATE Overflow. Some rights reserved.


408 3 Programming and DS: DS (213)

Heap will be constructed like this, based on the correct answer of Q.76 (which is 9 5 6 8 3 1)
Correct Answer: A
 15 votes -- Anurag Pandey (10.5k points)

3.10.11 Heap: GATE CSE 2007 | Question: 47 top☝ ☛ https://gateoverflow.in/1245

 Number of elements in the path from new leaf to root = log n, and all elements are sorted from leaf to root so we
can do a binary search which will result in O(log log n) number of comparisons.

Since a heap is a complete binary tree (hence height balanced also), in an array implementation, from every node index, we
can know its depth and this will be the number of elements − n for binary search.

Correct Answer: B
 94 votes -- Vikrant Singh (11.2k points)

3.10.12 Heap: GATE CSE 2009 | Question: 59 top☝ ☛ https://gateoverflow.in/1341

 Answer : (C)
The binary max-Heap looks like this :

Max-heap

 13 votes -- Dipak Majhi (757 points)

Taking the given array as level order traversal, we can build binary tree.

(A) 13 comes as child of 12, which is not allowed in a binary max-heap

(B) 16 comes as child of 14 violating max-heap property

(C) is a valid binary max-heap as all children are smaller than their parent

(D) 16 comes as child of 12, violating max-heap property


 18 votes -- Arjun Suresh (330k points)

3.10.13 Heap: GATE CSE 2009 | Question: 60 top☝ ☛ https://gateoverflow.in/43466

 During delete, the root element is removed, replaced with the last element and heap property is corrected by
pushing the root downwards. So, for first delete,

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 409

25 14 16 13 10 8 12 → 12 14 16 13 10 8 → 16 14 12 13 10 8 (the element not satisfying max-heap property is


exchanged with the largest of its children) (heap property satisfied)

Second delete:

16 14 12 13 10 8 → 8 14 12 13 10 → 14 8 12 13 10 → 14 13 12 8 10 (heap property satisfied)

Correct Answer: D
 29 votes -- Arjun Suresh (330k points)

3.10.14 Heap: GATE CSE 2011 | Question: 23 top☝ ☛ https://gateoverflow.in/2125

 In option (A) - it is not a max heap because it is not a Complete Binary Tree (a heap must have all levels till last
but one completely filled and in the last level all nodes must be filled from the left end without a gap till the last node)

In option (C) - it is complete binary tree but is not following the max heap property i.e. the value of parent node is not always
greater than the child nodes as the node of value 5 is less then one of its child node value of 8.

In option (D) - similar to (C) option explanation here node of value 2 is less than the child node value 4.

Correct option is (B) and it satisfies all the properties of a max heap.
 22 votes -- ASHU2015 (261 points)

3.10.15 Heap: GATE CSE 2014 Set 2 | Question: 12 top☝ ☛ https://gateoverflow.in/1967

 Answer is (A)....whenever insertion will be done in heap ,it will always inserted in last level from left to right.so
we insert 1 and 7 as a child of node 5 now we perform heapify algorithm until heap property will satisfied..and then
we get the heap whose level order traversal is 10, 8, 7, 3, 2, 1, 5 .
Initial heap

After insert of 1

After insert of 7

© Copyright GATE Overflow. Some rights reserved.


410 3 Programming and DS: DS (213)

 23 votes -- neha pawar (3.3k points)

3.10.16 Heap: GATE CSE 2015 Set 1 | Question: 32 top☝ ☛ https://gateoverflow.in/8273

 Heap is complete binary tree. To insert a new element, we put it at the end of the tree and move up towards root till
heap property is satisfied. Here, 35 comes as child of 15, with the path 40 − 30 − 15 − 35. So, we swap 15, 35 and
then 30, 35 to get the new path 40 − 35 − 30 − 15. So, new heap will be 40 35 20 10 30 16 17 8 4 15.

Correct Answer: B
 39 votes -- Arjun Suresh (330k points)

3.10.17 Heap: GATE CSE 2015 Set 2 | Question: 17 top☝ ☛ https://gateoverflow.in/8091

 Answer is (A).

Here, lower bound imply best algorithm which works for all cases and hence we should consider worst-case.

Max-Heapify(root).
 52 votes -- Vikrant Singh (11.2k points)

3.10.18 Heap: GATE CSE 2015 Set 3 | Question: 19 top☝ ☛ https://gateoverflow.in/8418

 First interchange 15-100


2nd 50-100
3rd 89-100
So, total interchange 3 so option (D) is correct.
 30 votes -- Anoop Sonkar (4.1k points)

3.10.19 Heap: GATE CSE 2016 Set 1 | Question: 37 top☝ ☛ https://gateoverflow.in/39706

 Answer would be (B) O(d) but not O(1).. as we need to apply heapify.. and suppose if we are deleting root, in
worst case would take O(d) time..
 52 votes -- Abhilash Panicker (7.6k points)

3.10.20 Heap: GATE CSE 2016 Set 2 | Question: 34 top☝ ☛ https://gateoverflow.in/39585

 Here answer is 8. With 1023 nodes, we can easily build a min heap as shown in the below diagram.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 411

Here, 9 is pushed to the deepest possible level which is 8 here. (kth smallest element in a min-heap cannot go deeper than
level k because the path from root to that level goes through k − 1 smaller elements). Now, do we have enough elements to
fill the right subtree to satisfy the complete binary tree property required by a heap? Yes. As shown in the diagram, up
to depth 9 (assume it is fully filled) we’ll need 29 − 1 = 511 elements. We have 1023 elements and so the remaining 512
elements should go to depth 9 which is guaranteed to have the maximum element – here 1023.
Correct answer is 8.
 81 votes -- Akash Kanase (36k points)

3.10.21 Heap: GATE CSE 2019 | Question: 40 top☝ ☛ https://gateoverflow.in/302808


I. The smallest element in a max-heap is always at a leaf node – TRUE because by definition of a max-heap every
parent node must be larger than its child node.
II. The second largest element in a max-heap is always a child of a root node – TRUE. The kth largest element cannot have
more than k − 1 parents (larger value nodes) and so cannot be lower than level k.
III. A max-heap can be constructed from a binary search tree in Θ(n) time. Build heap for any array of size n (even
unsorted) can be done in O(n) time.

Now lets see the 4th statement.

4. A binary search tree can be constructed from a max-heap in Θ(n) time. This can be proved FALSE using the simple
argument that we can do max-heap construction in O(n) and if we can convert this to BST in O(n) time we can do an
inorder traversal of BST in O(n) time and thus we manage to sort n elements in O(n) time using just
comparisons which is known to take at least Ω(n log n) time.

An example construction of BST from a max-heap.

Max – Heap
Max Heap Array Representation:

Value 7 4 6 1 3 2 5
Array Index 1 2 3 4 5 6 7

Make binary search tree using Array Representation:

1. Pick elements from A[1] to A[7] one by one.

© Copyright GATE Overflow. Some rights reserved.


412 3 Programming and DS: DS (213)

2. Compare with all previous elements and find its respective place.

We’ll get Binary Search Tree as follows:

Elements
Number of comparisons in the worst case for each element = 1 2 3 4 5 6 7

0 1 2 3 4 5 6

Comparisons

So for n element heap the total no of comparisons could be


= 0 + 1 + 2 + … (n − 2) + (n − 1)
(n−1)n
=Θ 2
= Θ(n2 )
Note: By using more efficient method this time complexity could be reduced to O(n. log n) but it can never be O(n).
OPTION A is the correct answer.
 11 votes -- Nitesh Singh (4.9k points)

3.10.22 Heap: GATE IT 2004 | Question: 53 top☝ ☛ https://gateoverflow.in/3696

 By using Build Heap method we can create heap from complete binary tree.
which will take O(n).
Correct Answer: B
 41 votes -- Sneha Goel (819 points)

3.10.23 Heap: GATE IT 2006 | Question: 44 top☝ ☛ https://gateoverflow.in/3587

 For a heap(max heap) parent should be greater than or equal to children. in a heap of [1..n] left child of ith node
will be at 2 ∗ i th position and right child will be at 2 ∗ i + 1 position.

So, for given options we can verify it.


.
Option C seems to be following the property.
 16 votes -- Sankaranarayanan P.N (8.5k points)

3.10.24 Heap: GATE IT 2006 | Question: 72 top☝ ☛ https://gateoverflow.in/3616

 Here we need to call Heapify/ Bubble down procedure on Root. Which in worst case will take time O (log n). So
B is correct option.

Other options does not even make sense , because with O(n) we can even build entire Heap not just heapify on root. O (n log
n) & O (n log log n) is more than O(n)
 23 votes -- Akash Kanase (36k points)

3.11 Infix Prefix (3) top☝

3.11.1 Infix Prefix: GATE CSE 1989 | Question: 4-ii top☝ ☛ https://gateoverflow.in/87881

Compute the postfix equivalent of the following infix arithmetic expression

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 413

a+b∗c+d∗e↑f

where ↑ represents exponentiation. Assume normal operator precedences.

gate1989 descriptive data-structures stack infix-prefix

Answer ☟

3.11.2 Infix Prefix: GATE CSE 1997 | Question: 1.7 top☝ ☛ https://gateoverflow.in/2223

Which of the following is essential for converting an infix expression to the postfix form efficiently?

A. An operator stack
B. An operand stack
C. An operand stack and an operator stack
D. A parse tree

gate1997 normal infix-prefix stack data-structures

Answer ☟

3.11.3 Infix Prefix: GATE CSE 1998 | Question: 19b top☝ ☛ https://gateoverflow.in/15708

Compute the post fix equivalent of the following expression 3∗ log(x + 1) − a


2

gate1998 stack infix-prefix descriptive

Answer ☟

Answers: Infix Prefix

3.11.1 Infix Prefix: GATE CSE 1989 | Question: 4-ii top☝ ☛ https://gateoverflow.in/87881

 = a + (bc∗) + (d(ef ↑)∗)

= (abc ∗ +) + (def ↑ ∗)

= abc ∗ +def ↑ ∗+
 9 votes -- Aboveallplayer (12.5k points)

3.11.2 Infix Prefix: GATE CSE 1997 | Question: 1.7 top☝ ☛ https://gateoverflow.in/2223

 A. An operator stack // Infix to ( Postfix or Prefix )


B. An operand stack //Postfix or Prefix Evaluation
C. An operand stack and an operator stack //we never use two stacks
But for Prefix to (Infix or postfix) OR Postfix to (Infix or prefix) We can use a stack where both operator and operand can
present simultaneously
D. A parse tree // Not relevant to this question
Hence, Option A is Answer.
http://condor.depaul.edu/ichu/csc415/notes/notes9/Infix.htm is a good read.
References

 33 votes -- Rajesh Pradhan (18.9k points)

3.11.3 Infix Prefix: GATE CSE 1998 | Question: 19b top☝ ☛ https://gateoverflow.in/15708

 According to http://faculty.washington.edu/jstraub/dsa/aexp/

© Copyright GATE Overflow. Some rights reserved.


414 3 Programming and DS: DS (213)

'
The priority of the operators follows the usual conventions:

The highest priority is assigned to unary operators (note that, in this context, a function such as sin is considered a
unary operator). All unary operators have the same priority.
Exponentiation has the second highest priority.
The third highest priority is assigned to the multiplication and division operators.
The lowest priority is given to the addition and subtraction operators.

Example:->>
Infix expression: 3 ∗ log(10)
Postfix expression:
= 3 ∗ (10 log) //(Priority of unary operator log forces log(10) to evaluate first.)
= 3 10 log ∗

Now for our case 3 ∗ log(x + 1) − a/2


First content inside parenthesis will be evaluated
So, x + 1 will become x 1+
Now among (∗, /, log, +, −) operators, log has highest priority as it is the only unary operator
So, log(x 1+) will become x 1 + log
Now suppose z = x1 + log and we get 3 ∗ z − a/2
⟹ 3z ∗ a 2/−
Now, substitute z = x 1 + log and we get
3x 1 + log ∗a 2/− as answer.
References

 81 votes -- Rajesh Pradhan (18.9k points)

3.12 Linked Lists (20) top☝

3.12.1 Linked Lists: GATE CSE 1987 | Question: 1-xv top☝ ☛ https://gateoverflow.in/80298

In a circular linked list oraganisation, insertion of a record involves modification of

A. One pointer.
B. Two pointers.
C. Multiple pointers.
D. No pointer.

gate1987 data-structures linked-lists

Answer ☟

3.12.2 Linked Lists: GATE CSE 1987 | Question: 6a top☝ ☛ https://gateoverflow.in/82419

A list of n elements is commonly written as a sequence of n elements enclosed in a pair of square brackets. For
example. [10, 20, 30] is a list of three elements and [] is a nil list. Five functions are defined below:

car(l) returns the first element of its argument list l;


cdr(l) returns the list obtained by removing the first element of the argument list l;
glue(a, l) returns a list m such that car(m) = a and cdr(m) = l.
f(x, y) ≡ if x = [] then y
else glue(car(x), f(cdr(x), y));
g(x) ≡ if x = [] then []
else f(g(cdr(x)), glue(car(x), []))

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 415

What do the following compute?

a. f([32, 16, 8], [9, 11, 12])


b. g([5, 1, 8, 9])

gate1987 data-structures linked-lists descriptive

Answer ☟

3.12.3 Linked Lists: GATE CSE 1993 | Question: 13 top☝ ☛ https://gateoverflow.in/2310

Consider a singly linked list having n nodes. The data items d1 , d2 , … dn are stored in these n nodes. Let X be a
pointer to the jth node (1 ≤ j ≤ n) in which dj is stored. A new data item d stored in node with address Y is to be
inserted. Give an algorithm to insert d into the list to obtain a list having items d1 , d2 , … , dj , d, … , dn in order without using
the header.

gate1993 data-structures linked-lists normal descriptive

Answer ☟

3.12.4 Linked Lists: GATE CSE 1994 | Question: 1.17, UGCNET-Sep2013-II: 32 top☝ ☛ https://gateoverflow.in/2460

Linked lists are not suitable data structures for which one of the following problems?

A. Insertion sort
B. Binary search
C. Radix sort
D. Polynomial manipulation

gate1994 data-structures linked-lists normal ugcnetsep2013ii

Answer ☟

3.12.5 Linked Lists: GATE CSE 1995 | Question: 2.22 top☝ ☛ https://gateoverflow.in/2634

Which of the following statements is true?

I. As the number of entries in a hash table increases, the number of collisions increases.
II. Recursive programs are efficient
III. The worst case complexity for Quicksort is O(n2 )
IV. Binary search using a linear linked list is efficient

A. I and II
B. II and III
C. I and IV
D. I and III

gate1995 data-structures linked-lists hashing

Answer ☟

3.12.6 Linked Lists: GATE CSE 1997 | Question: 1.4 top☝ ☛ https://gateoverflow.in/2220

The concatenation of two lists is to be performed on O(1) time. Which of the following implementations of a list
should be used?

A. Singly linked list


B. Doubly linked list
C. Circular doubly linked list
D. Array implementation of list

gate1997 data-structures linked-lists easy

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


416 3 Programming and DS: DS (213)

3.12.7 Linked Lists: GATE CSE 1997 | Question: 18 top☝ ☛ https://gateoverflow.in/2278

Consider the following piece of 'C' code fragment that removes duplicates from an ordered list of integers.
Node *remove-duplicates (Node* head, int *j)
{
Node *t1, *t2; *j=0;
t1 = head;
if (t1! = NULL)
t2 = t1 ->next;
else return head;
*j = 1;
if(t2 == NULL) return head;
while (t2 != NULL)
{
if (t1.val != t2.val) ----------------> (S1)
{
(*j)++;
t1 -> next = t2;
t1 = t2; -----> (S2)
}
t2 = t2 ->next;
}
t1 -> next = NULL;
return head;
}

Assume the list contains n elements ( n ≥ 2 ) in the following questions.

a. How many times is the comparison in statement S1 made?


b. What is the minimum and the maximum number of times statements marked S2 get executed?
c. What is the significance of the value in the integer pointed to by j when the function completes?

gate1997 data-structures linked-lists normal descriptive

Answer ☟

3.12.8 Linked Lists: GATE CSE 1998 | Question: 19a top☝ ☛ https://gateoverflow.in/1733

Let p be a pointer as shown in the figure in a single linked list.

What do the following assignment statements achieve?


q:= p -> next
p -> next:= q -> next
q -> next:=(q -> next) -> next
(p -> next) -> next:= q

gate1998 data-structures linked-lists normal descriptive

Answer ☟

3.12.9 Linked Lists: GATE CSE 1999 | Question: 11b top☝ ☛ https://gateoverflow.in/93575

Write a constant time algorithm to insert a node with data D just before the node with address p of a singly linked list.

gate1999 data-structures linked-lists descriptive

Answer ☟

3.12.10 Linked Lists: GATE CSE 2002 | Question: 1.5 top☝ ☛ https://gateoverflow.in/809

In the worst case, the number of comparisons needed to search a single linked list of length n for a given element is

A. log n
B. n2
C. log2 n − 1
D. n

gate2002-cse easy data-structures linked-lists

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 417

Answer ☟

3.12.11 Linked Lists: GATE CSE 2003 | Question: 90 top☝ ☛ https://gateoverflow.in/973

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)));
}

For a given linked list p, the function f returns 1 if and only if

A. the list is empty or has exactly one element


B. the elements in the list are sorted in non-decreasing order of data value
C. the elements in the list are sorted in non-increasing order of data value
D. not all elements in the list have the same data value

gate2003-cse data-structures linked-lists normal

Answer ☟

3.12.12 Linked Lists: GATE CSE 2004 | Question: 36 top☝ ☛ https://gateoverflow.in/1033

A circularly linked list is used to represent a Queue. A single variable p is used to access the Queue. To which node
should p point such that both the operations enQueue and deQueue can be performed in constant time?

A. rear node
B. front node
C. not possible with a single pointer
D. node next to front

gate2004-cse data-structures linked-lists normal

Answer ☟

3.12.13 Linked Lists: GATE CSE 2004 | Question: 40 top☝ ☛ https://gateoverflow.in/1037

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?
A. union only
B. intersection, membership
C. membership, cardinality
D. union, intersection

gate2004-cse data-structures linked-lists normal

Answer ☟

3.12.14 Linked Lists: GATE CSE 2008 | Question: 62 top☝ ☛ https://gateoverflow.in/485

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 function completes execution?

© Copyright GATE Overflow. Some rights reserved.


418 3 Programming and DS: DS (213)

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;
}
}

A. 1, 2, 3, 4, 5, 6, 7
B. 2, 1, 4, 3, 6, 5, 7
C. 1, 3, 2, 5, 4, 7, 6
D. 2, 3, 4, 5, 6, 7, 1

gate2008-cse data-structures linked-lists normal

Answer ☟

3.12.15 Linked Lists: GATE CSE 2010 | Question: 36 top☝ ☛ https://gateoverflow.in/2337

The following C function takes a singly-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.
typedef struct node
{
int value;
struct node *next;
} node;
Node *move_to-front(Node *head)
{
Node *p, *q;
if ((head == NULL) || (head -> next == NULL))
return head;
q = NULL;
p = head;
while (p->next != NULL)
{
q=p;
p=p->next;
}
_______________

return head;

Choose the correct alternative to replace the blank line.

A. q = NULL; p → next = head; head = p ;


B. q → next = NULL; head = p; p → next = head ;
C. head = p; p → next = q; q → next = NULL ;
D. q → next = NULL; p → next = head; head = p ;

gate2010-cse data-structures linked-lists normal

Answer ☟

3.12.16 Linked Lists: GATE CSE 2016 Set 2 | Question: 15 top☝ ☛ https://gateoverflow.in/39557

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(log2 N)
B. O(N)
2
O( )
© Copyright GATE Overflow. Some rights reserved.
3 Programming and DS: DS (213) 419

C. O(N 2 )
D. Θ (N 2 log N)

gate2016-cse-set2 data-structures linked-lists time-complexity normal

Answer ☟

3.12.17 Linked Lists: GATE CSE 2017 Set 1 | Question: 08 top☝ ☛ https://gateoverflow.in/118711

Consider the C code fragment given below.


typedef struct node {
int data;
node* next;
} node;

void join(node* m, node* n) {


node* p = n;
while(p->next != NULL) {
p = p->next;
}
p->next = m;
}

Assuming that m and n point to valid NULL-terminated linked lists, invocation of join will

A. append list m to the end of list n for all inputs.


B. either cause a null pointer dereference or append list m to the end of list n.
C. cause a null pointer dereference for all inputs.
D. append list n to the end of list m for all inputs.

gate2017-cse-set1 data-structures linked-lists normal

Answer ☟

3.12.18 Linked Lists: GATE CSE 2020 | Question: 16 top☝ ☛ https://gateoverflow.in/333215

What is the worst case time complexity of inserting n elements into an empty linked list, if the linked list needs to be
maintained in sorted order?

A. Θ(n)
B. Θ(n log n)
C. Θ(n)2
D. Θ(1)

gate2020-cse linked-lists

Answer ☟

3.12.19 Linked Lists: GATE IT 2004 | Question: 13 top☝ ☛ https://gateoverflow.in/3654

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)
B. O(log2 n)
C. O(log n)
D. O(1)

gate2004-it data-structures linked-lists normal ambiguous

Answer ☟

3.12.20 Linked Lists: GATE IT 2005 | Question: 54 top☝ ☛ https://gateoverflow.in/3815

The following C function takes a singly-linked list of integers as a parameter and rearranges the elements of the list.
The list is represented as pointer to a structure. 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?

© Copyright GATE Overflow. Some rights reserved.


420 3 Programming and DS: DS (213)

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;
}
}

A. 1, 2, 3, 4, 5, 6, 7
B. 2, 1, 4, 3, 6, 5, 7
C. 1, 3, 2, 5, 4, 7, 6
D. 2, 3, 4, 5, 6, 7, 1

gate2005-it data-structures linked-lists normal

Answer ☟

Answers: Linked Lists

3.12.1 Linked Lists: GATE CSE 1987 | Question: 1-xv top☝ ☛ https://gateoverflow.in/80298

 Suppose we have to insert node p after node q then

p → next = q → next
q → next = p

So, two pointers,

Answer is (B).
 20 votes -- Sanket_ (3.1k points)

3.12.2 Linked Lists: GATE CSE 1987 | Question: 6a top☝ ☛ https://gateoverflow.in/82419

 Part (a) Concatenate the two lists.


Part (b) Reverse the given list.
Part (a):
f([32, 16, 8], [9, 11, 12])

glue(car[32, 16, 8], f(cdr([32, 16, 8]), [9, 11, 12]))

glue(32, f([16, 8], [9, 11, 12]))

glue(32, glue(car([16, 8]), f(cdr([16, 8]), [9, 11, 12])))

glue(32, glue(16, f([8], [9, 11, 12])))

glue(32, glue(16, glue(car([8]), f(cdr([8]), [9, 11, 12]))))

glue(32, glue(16, glue(8, f([]), [9, 11, 12])))

glue(32, glue(16, glue(8, [9, 11, 12])))

glue(32, glue(16, [8, 9, 11, 12]))

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 421


glue(32, [16, 8, 9, 11, 12])

[32, 16, 8, 9, 11, 12] Answer.

Part (b):
g([5, 1, 8, 9])

f(g(cdr([5, 1, 8, 9])), glue(car([5, 1, 8, 9]), []))

f(g([1, 8, 9]), glue(5, [])))

f(g([1, 8, 9]), [5])
So, we can say, g([5, 1, 8, 9]) = f(g([1, 8, 9]), [5])
Similarly,
g([1, 8, 9]) = f(g([8, 9]), [1])
g([8, 9]) = f(g([9]), [8])
g([9]) = f(g([]), [9]) = f([], [9]) = [9]
Now, backtrack
g([8, 9]) = f([9], [8]) = [9, 8] (From part (a))
& g([1, 8, 9]) = f([9, 8], [1])
g([1, 8, 9]) = [9, 8, 1] (From part (a))
Now, g([5, 1, 8, 9]) = f([9, 8, 1], [5]) = [9, 8, 1, 5]
So, g([5, 1, 8, 9]) = [9, 8, 1, 5] Answer

 11 votes -- ankitgupta.1729 (15k points)

3.12.3 Linked Lists: GATE CSE 1993 | Question: 13 top☝ ☛ https://gateoverflow.in/2310

 Following 2 lines are enough to realize above constraint :

1. Y->next = X-> next


2. X->next = Y

 22 votes -- Rajesh Pradhan (18.9k points)

3.12.4 Linked Lists: GATE CSE 1994 | Question: 1.17, UGCNET-Sep2013-II: 32 top☝ ☛ https://gateoverflow.in/2460

 Linked lists are suitable for:


Insertion sort: No need to swap here just find appropriate place and join the link
Polynomial manipulation: Linked List is a natural solution for polynomial manipulation
Radix sort: Here we are putting digits according to same position(unit,tens) into buckets; which can be effectively handled
by linked lists.
Not Suitable for:
Binary search: Because finding mid element itself takes O(n) time.
So, Option B is answer.
 32 votes -- Rajesh Pradhan (18.9k points)

3.12.5 Linked Lists: GATE CSE 1995 | Question: 2.22 top☝ ☛ https://gateoverflow.in/2634

 Correct Option: D
Binary search using a linked list is not efficient as it will not give O(log n), because we will not be able to find the
mid in constant time. Finding mid in linked list takes O(n) time.

© Copyright GATE Overflow. Some rights reserved.


422 3 Programming and DS: DS (213)

Recursive programs are not efficient because they take a lot of space, Recursive methods will often throw Stack Overflow
Exception while processing big sets. moreover, it has its own advantages too.
 31 votes -- Gate Keeda (15.9k points)

3.12.6 Linked Lists: GATE CSE 1997 | Question: 1.4 top☝ ☛ https://gateoverflow.in/2220

 Option C ( Circular Doubly linked List)


Analyze below Code which is O(1)
Suppose List1's first element is pointed by pointer p1
And List2's first element is pointed by p2
And tmp is a temporary pointer of node type.
p1->prev->next = p2 ;

tmp= p2-> prev ;

p2-> prev= p1-> prev ;

p1-> prev = tmp;

tmp -> next = p1;

Options A&B of linked list are not possible in O(1). Because they cannot find out rear element without doing a
linear traversal.
For Option D. Array implementation requires O(n1 + n2 ) copy operations where n1 and n2 represent the sizes of
List1 and List2 respectively.
 30 votes -- Rajesh Pradhan (18.9k points)

3.12.7 Linked Lists: GATE CSE 1997 | Question: 18 top☝ ☛ https://gateoverflow.in/2278


a. As we are comparing here pair wise so for n elements we require compulsory n − 1 comparison
b. S2 is executed only for distinct elements so max n − 1 times and min 0 when all r duplicates or list contain no or 1
element.
c. j holds the count on number of distinct elements in the ordered list.

 27 votes -- Rajesh Pradhan (18.9k points)

3.12.8 Linked Lists: GATE CSE 1998 | Question: 19a top☝ ☛ https://gateoverflow.in/1733

 Swaps the two nodes next to p in the linked list.


 33 votes -- Arjun Suresh (330k points)

3.12.9 Linked Lists: GATE CSE 1999 | Question: 11b top☝ ☛ https://gateoverflow.in/93575

 Let A, B, C, D, E, F be the data.


A→B→C→E→F

Let the pointer to E be p.


A node with data D has to be inserted before E.
I'll do one thing - add D just after node E and it'll take constant time.
p → next = Daddr
Daddr → next = Faddr

A→B→C→E→D→F

Take a temporary variable and swap the values E and D.


temp = p-> data
p->data = p->next->data
p->next->data = temp

Now linked list will look like


A→B→C→D→E→F

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 423

Still one more work left - now pointer p pointing to D so increment pointer p to point data E.
p = p → next
void InsertBeforeGivenPointer(struct node* p, int D){
struct node* temp = (node*)malloc(sizeof(struct node));
temp->next = p->next;
p->next = temp;
temp->data = p->data;
p->data = D;
}

 40 votes -- Digvijay (44.9k points)

3.12.10 Linked Lists: GATE CSE 2002 | Question: 1.5 top☝ ☛ https://gateoverflow.in/809

 A & C are not correct as we can not do binary search in Linked list.

B seems like average case, be we are asked for worst case.

Worst case is we do not find the element in list. We might end up searching entire list & comparing with each element. So,
answer -> (D). n
 24 votes -- Akash Kanase (36k points)

3.12.11 Linked Lists: GATE CSE 2003 | Question: 90 top☝ ☛ https://gateoverflow.in/973

 It returns 1 if and only if the linked list is sorted in non-decreasing order- (B) option.

It returns 1 if the list is empty or has just 1 element also, but if and only if makes (A) option false.
 34 votes -- Bhagirathi Nayak (11.7k points)

3.12.12 Linked Lists: GATE CSE 2004 | Question: 36 top☝ ☛ https://gateoverflow.in/1033

 The pointer points to the Rear node.


EnQueue: Insert newNode after Rear, and make Rear point to the newly inserted node:
//struct node *newNode;
newNode->next = rear->next;
rear->next = newNode;
rear=newNode;

DeQueue: Delete the Front node, and make the second node the front node.
//rear->next points to the front node.
//front->next points to the second node.
struct node* front;
front = rear->next;
rear->next = front->next;
free(front);

 92 votes -- Pragy Agarwal (18.3k points)

3.12.13 Linked Lists: GATE CSE 2004 | Question: 40 top☝ ☛ https://gateoverflow.in/1037

 Answer is (D).

Membership is linear search - O(n1 + n2 )

Cardinality is linear - O(n1 + n2 )

For union we need to ensure no duplicate elements should be present - O(n1 × n2 ) for each element we need to check if
that element exists in other set

For intersection also for every element in set1 we need to scan set2 - O(n1 × n2 )
 74 votes -- Ankit Rokde (6.9k points)

© Copyright GATE Overflow. Some rights reserved.


424 3 Programming and DS: DS (213)

3.12.14 Linked Lists: GATE CSE 2008 | Question: 62 top☝ ☛ https://gateoverflow.in/485

 The loop is interchanging the adjacent elements of the list. But after each interchange, next interchange starts from
the unchanged elements only (due to p = q → next ;).

1st iteration 1, 2, 3, 4, 5, 6, 7
⇒ 2, 1, 3, 4, 5, 6, 7

2nd iteration 2, 1, 4, 3, 5, 6, 7

3rd iteration 2, 1, 4, 3, 6, 5, 7

p pointing to null q pointing to 7, as p is false hence q = p? p → next :0; will return q = 0 ending the loop
Answer is option B.
 30 votes -- Manali (2.1k points)

3.12.15 Linked Lists: GATE CSE 2010 | Question: 36 top☝ ☛ https://gateoverflow.in/2337

 As per given code p points to last node which should be head in modified.

q is the previous node of tail which should be tail for modified

Answer is (D).
 37 votes -- Sankaranarayanan P.N (8.5k points)

3.12.16 Linked Lists: GATE CSE 2016 Set 2 | Question: 15 top☝ ☛ https://gateoverflow.in/39557

 Answer is (C).

Delete O(1)
Insert O(N)
Find O(N)

Decrease Key ⇒ O(N) //Because we need to search position in Linked list. (It is similar to a Delete followed by an Insert
with the decreased value)

O(n) delete ⇒ O(N × 1) = O(N)


O(log N) find ⇒ O(log N × N) = O(N log N)
O(log N) insert ⇒ O(N log N)
O(N) decrease key ⇒ O(N × N) = O(N 2 )

Even though it says at start we got N elements, then we are deleting Q(N) elements, here Q(N) can be anything like
N /2, N /4, N /3 and list need not be empty, then above explanation holds !
In case it actually deleted all elements at start analysis will be something like below ⇒
All N elements are deleted, Time complexity O(1) each delete, total delete O(N)
Now log N insert, it'll take 1 + 2 + log N time, then ( log N ∗ log N − 1)/2 ⇒ O((log N )2 )
Now log N finds ⇒ it'll take log N time per find (because find take O(N) but here N = log N )
⇒ O((log N )2 )
Now N decrease key, Size of list is log N , each decrease key can take O(size of list)
So, size of list * no. of decrease key ⇒ N × log N = O(N log N)
There is no option like O(N log N)
So, correct answer is O(N 2 ) .
 107 votes -- Akash Kanase (36k points)

3.12.17 Linked Lists: GATE CSE 2017 Set 1 | Question: 08 top☝ ☛ https://gateoverflow.in/118711

 Here is the implemented code in c (-std=c99).

#include <stdio.h>

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 425

#include <stdlib.h>

#define M 5
#define N 4

int M_data[M] = {1,2,3,4,5};


int N_data[N] = {6,7,8,9};

typedef struct node {


int data;
struct node * next;
}node;

void join(node *m,node *n) {


node * p = n;
while(p->next != NULL) p = p->next;
p->next = m;
}

node * bulk_insert(int list_data[],int size) {


node * head = NULL;
for(int i=0;i<size;i++) {
node * newnode = malloc(sizeof(node));
newnode->data = list_data[i];
newnode->next = NULL;

if(head == NULL) {
head = newnode;
}else {
node * temp = head;
while(temp->next != NULL) temp = temp->next;
temp->next = newnode;
}
}
return head;
}
void display(node *);
void list_dealloc(node *); /*deallocation prototype*/

int main() {
node * m = NULL;
node * n = NULL;
// insert m_list data
m = bulk_insert(M_data,M);
n = bulk_insert(N_data,N); // commenting this causes runtime error
// is list n is empty
printf("\n before join operation :\n");
display(m);
display(n);

join(m,n);

printf("\n after join operation :\n");


display(m);
display(n);

//list_dealloc(m); no need now


list_dealloc(n); // OK
return 0;

void display(node *head) {


while(head != NULL) {
printf("%d->",head->data);
head = head->next;
}
printf("null\n");
}
void list_dealloc(node * head) {
while(head != NULL) {
node * temp = head;
head = head->next;
free(temp);
}
}

With both n and m and n being non-empty linked list, then,


O/P:

before join operation :

© Copyright GATE Overflow. Some rights reserved.


426 3 Programming and DS: DS (213)

1->2->3->4->5->null
6->7->8->9->null

after join operation :


1->2->3->4->5->null
6->7->8->9->1->2->3->4->5->null

With n being empty linked list, then,


O/P:

Correct Answer: B
 52 votes -- Debashish Deka (40.7k points)

3.12.18 Linked Lists: GATE CSE 2020 | Question: 16 top☝ ☛ https://gateoverflow.in/333215

 "Inserting n elements into an empty linked list, list needs to be maintained in sorted order".
It is not mentioned if the "n elements" are given initially itself or we must insert one element at a time.

1. For the former case, we can just sort the initial n element array - can be done in O(n lg n) and then we'll insert them one
by one to the linked list where the sorted order is always maintained. This process will take O(n) and so the entire
process can be done in Θ(n log n) time.
2. For the latter case, where we have to do insertion to the linked list one element at a time, the only way to ensure sorted
order for the linkedlist is to follow insertion sort mechanism. This will take Θ(n2 ) time in the worst case.

Since, the question is ambiguous in saying how the elements are presented, both options A and B should be given marks.
Unfortunately official key considered later case only. Option C.
 26 votes -- Arjun Suresh (330k points)

3.12.19 Linked Lists: GATE IT 2004 | Question: 13 top☝ ☛ https://gateoverflow.in/3654

 In the worst case x could be last or second last node, In that case full traversal of the list is required. Therefore
answer is (A).

PS: We can simulate the deletion by moving the x′ s next node data to x and then delete x′ s next node. But this is technically
not the same as DELETING NODE x as mentioned in the question though effect is the same as long as there are a constant
number of elements to be moved from x′ s next node.
 38 votes -- suraj (4.8k points)

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 427

3.12.20 Linked Lists: GATE IT 2005 | Question: 54 top☝ ☛ https://gateoverflow.in/3815

 It is (B) 2, 1, 4, 3, 6, 5, 7 :
As, p and q are swapping each other where q is p → next all the time.
 24 votes -- sumit kumar singh dixit (1.6k points)

3.13 Priority Queue (1) top☝

3.13.1 Priority Queue: GATE CSE 1997 | Question: 4.7 top☝ ☛ https://gateoverflow.in/2248

A priority queue Q is used to implement a stack that stores characters. PUSH (C) is implemented as INSERT
(Q, C, K) where K is an appropriate integer key chosen by the implementation. POP is implemented as DELETEMIN
(Q). For a sequence of operations, the keys chosen are in
A. non-increasing order
B. non-decreasing order
C. strictly increasing order
D. strictly decreasing order

gate1997 data-structures stack normal priority-queue

Answer ☟

Answers: Priority Queue

3.13.1 Priority Queue: GATE CSE 1997 | Question: 4.7 top☝ ☛ https://gateoverflow.in/2248

 Implementing stack using priority queue require first element inserted in stack will be deleted at last, and to
implement it using deletemin() operation of queue will require first element inserted in queue must have highest
priority.

So the keys must be in strictly decreasing order.

Correct Answer: D
 34 votes -- Suraj Kaushal (273 points)

3.14 Queue (12) top☝

3.14.1 Queue: GATE CSE 1992 | Question: 09 top☝ ☛ https://gateoverflow.in/588

Suggest a data structure for representing a subset S of integers from 1 to n. Following operations on the set S are to be
performed in constant time (independent of cardinality of S ).

i. MEMBER (X) : Check whether X is in the set S or not


ii. FIND-ONE (S) : If S is not empty, return one element of the set S
(any arbitrary element will do)
iii. ADD (X) : Add integer X to set S
ii. DELETE (X) : Delete integer X from S

Give pictorial examples of your data structure. Give routines for these operations in an English like language. You may assume
that the data structure has been suitable initialized. Clearly state your assumptions regarding initialization.

gate1992 data-structures normal descriptive queue

Answer ☟

3.14.2 Queue: GATE CSE 1994 | Question: 26 top☝ ☛ https://gateoverflow.in/2522

A queue Q containing n items and an empty stack S are given. It is required to transfer all the items from the queue to
the stack, so that the item at the front of queue is on the TOP of the stack, and the order of all other items are preserved.
Show how this can be done in O(n) time using only a constant amount of additional storage. Note that the only operations
which can be performed on the queue and stack are Delete, Insert, Push and Pop. Do not assume any implementation of the
queue or stack.

© Copyright GATE Overflow. Some rights reserved.


428 3 Programming and DS: DS (213)

gate1994 data-structures queue stack normal descriptive

Answer ☟

3.14.3 Queue: GATE CSE 1996 | Question: 1.12 top☝ ☛ https://gateoverflow.in/2716

Consider the following statements:

i. First-in-first out types of computations are efficiently supported by STACKS.


ii. Implementing LISTS on linked lists is more efficient than implementing LISTS on an array for almost all the basic LIST
operations.
iii. Implementing QUEUES on a circular array is more efficient than implementing QUEUES on a linear array with two
indices.
iv. Last-in-first-out type of computations are efficiently supported by QUEUES.

A. (ii) and (iii) are true


B. (i) and (ii) are true
C. (iii) and (iv) are true
D. (ii) and (iv) are true

gate1996 data-structures easy queue stack linked-lists

Answer ☟

3.14.4 Queue: GATE CSE 2001 | Question: 2.16 top☝ ☛ https://gateoverflow.in/734

What is the minimum number of stacks of size n required to implement a queue of size n?

A. One
B. Two
C. Three
D. Four

gate2001-cse data-structures easy stack queue

Answer ☟

3.14.5 Queue: GATE CSE 2006 | Question: 49 top☝ ☛ https://gateoverflow.in/1826

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);
}

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?

A. n + m ≤ x < 2n and 2m ≤ y ≤ n + m
B. n + m ≤ x < 2n and 2m ≤ y ≤ 2n
C. 2m ≤ x < 2n and 2m ≤ y ≤ n + m
D. 2m ≤ x < 2n and 2m ≤ y ≤ 2n

gate2006-cse data-structures queue stack normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 429

3.14.6 Queue: GATE CSE 2012 | Question: 35 top☝ ☛ https://gateoverflow.in/1756

Suppose a circular queue of capacity (n − 1) elements is implemented with an array of n elements. Assume that the
insertion and deletion operations 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

A. full: (REAR + 1) mod n == FRONT


empty: REAR == FRONT

B. full: (REAR + 1) mod n == FRONT


empty: (FRONT + 1) mod n == REAR

C. full: REAR == FRONT


empty: (REAR + 1) mod n == FRONT

D. full: (FRONT + 1) mod n == REAR


empty: REAR == FRONT

gate2012-cse data-structures queue normal

Answer ☟

3.14.7 Queue: GATE CSE 2013 | Question: 44 top☝ ☛ https://gateoverflow.in/61

Consider the following operation along with Enqueue and Dequeue operations on queues, where k is a global
parameter.
MultiDequeue(Q){
m = k
while (Q is not empty) and (m > 0) {
Dequeue(Q)
m = m – 1
}
}

What is the worst case time complexity of a sequence of n queue operations on an initially empty
queue?

A. Θ(n)
B. Θ(n + k)
C. Θ(nk)
D. Θ(n2 )

gate2013-cse data-structures algorithms normal queue

Answer ☟

3.14.8 Queue: GATE CSE 2016 Set 1 | Question: 10 top☝ ☛ https://gateoverflow.in/39667

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) ?

A. Both operations can be performed in O(1) time.


B. At most one operation can be performed in O(1) time but the worst case time for the operation will be Ω(n).
C. The worst case time complexity for both operations will be Ω(n).
D. Worst case time complexity for both operations will be Ω(log n)

gate2016-cse-set1 data-structures queue normal

Answer ☟

3.14.9 Queue: GATE CSE 2016 Set 1 | Question: 41 top☝ ☛ https://gateoverflow.in/39684

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.
while Q is not Empty do
if S is Empty OR Top(S) ≤ Head (Q) then

© Copyright GATE Overflow. Some rights reserved.


430 3 Programming and DS: DS (213)

x:= Dequeue (Q);


Push (S, x);
else
x:= Pop(S);
Enqueue (Q, x);
end
end

The maximum possible number of iterations of the while loop in the algorithm is _______.

gate2016-cse-set1 data-structures queue difficult numerical-answers

Answer ☟

3.14.10 Queue: GATE CSE 2017 Set 2 | Question: 13 top☝ ☛ https://gateoverflow.in/118253

A circular queue has been implemented using a singly linked list where each node consists of a value and a single
pointer pointing to the next node. We maintain exactly two external pointers FRONT and REAR pointing to the front
node and the rear node of the queue, respectively. Which of the following statements is/are CORRECT for such a circular
queue, so that insertion and deletion operations can be performed in O(1) time?

I. Next pointer of front node points to the rear node.


II. Next pointer of rear node points to the front node.

A. (I) only.
B. (II) only.
C. Both (I) and (II).
D. Neither (I) nor (II).

gate2017-cse-set2 data-structures queue

Answer ☟

3.14.11 Queue: GATE CSE 2018 | Question: 3 top☝ ☛ https://gateoverflow.in/204077

A queue is implemented using a non-circular singly linked list. The queue has a head pointer and a tail pointer, as
shown in the figure. Let n denote the number of nodes in the queue. Let 'enqueue' be implemented by inserting a new
node at the head, and 'dequeue' be implemented by deletion of a node from the tail.

Which one of the following is the time complexity of the most time-efficient implementation of 'enqueue' and 'dequeue,
respectively, for this data structure?

A. Θ(1), Θ(1)
B. Θ(1), Θ(n)
C. Θ(n), Θ(1)
D. Θ(n), Θ(n)

gate2018-cse algorithms data-structures queue normal linked-lists

Answer ☟

3.14.12 Queue: GATE IT 2007 | Question: 30 top☝ ☛ https://gateoverflow.in/3463

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 ;

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 431

if (!isEmpty(Q)) {
i = delete(Q);
f(Q);
insert(Q, i);
}
}

What operation is performed by the above function f ?

A. Leaves the queue Q unchanged


B. Reverses the order of the elements in the queue Q
C. Deletes the element at the front of the queue Q and inserts it at the rear keeping the other elements in the same order
D. Empties the queue Q

gate2007-it data-structures queue normal

Answer ☟

Answers: Queue

3.14.1 Queue: GATE CSE 1992 | Question: 09 top☝ ☛ https://gateoverflow.in/588

A queue with a hashtable.

Intialize hashtable with 0.

When inserting X into the queue update hashtable[X] = 0 to hashtable[X] = 1 .

i. If hashtable[X] = 1 then return true.


ii. Return the element at the front or rear of the queue.
iii. Add the element X to the queue at the rear end and update hashtable[X] = 0 to hashtable[X] = 1 .
iv. Delete the element X from the front end of the queue and update hashtable[X] = 1 to hashtable[X] = 0 .

 22 votes -- Rajarshi Sarkar (27.8k points)

3.14.2 Queue: GATE CSE 1994 | Question: 26 top☝ ☛ https://gateoverflow.in/2522

 We can do this be first extracting items one by one from Q, and inserting them to S . After all items are done, S
will contain the items in reverse order. Now, pop the elements from S and insert to Q. After this operation, items in Q
will be in reverse order from the starting. Now, extract items from Q and push on to stack and we are done.
Do
Delete an item from Q
Push the item to S
While (! empty Q);
Do
Pop an item from S
Insert the item to Q
While (! empty S);
Do
Delete an item from Q
Push the item to S
While (! empty Q);

 48 votes -- Arjun Suresh (330k points)

3.14.3 Queue: GATE CSE 1996 | Question: 1.12 top☝ ☛ https://gateoverflow.in/2716

 (A). (i) and (iv) are false.


http://en.wikipedia.org/wiki/List_(abstract_data_type)#Operations
References

 26 votes -- Gate Keeda (15.9k points)

© Copyright GATE Overflow. Some rights reserved.


432 3 Programming and DS: DS (213)

3.14.4 Queue: GATE CSE 2001 | Question: 2.16 top☝ ☛ https://gateoverflow.in/734

 A queue can be implemented using two stacks.

Let queue be represented as " q "


and stacks used to implement q be "stack1" and "stack2".

q can be implemented in two ways:

Method 1 (By making EnQueue operation costly)

This method makes sure that newly entered element is always at the bottom of stack 1, so that deQueue operation just pops
from stack1. To put the element at top of stack1, stack2 is used.

enQueue(q, x)

1. While stack1 is not empty, push everything from stack1 to stack2.


2. Push x to stack1 (assuming size of stacks is unlimited).
3. Push everything back to stack1.

dnQueue(q)

1. If stack1 is empty then error


2. Pop an item from stack1 and return it

Method 2 (By making deQueue operation costly)

In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is
empty then all the elements are moved to stack2 and finally top of stack2 is returned.
enQueue(q, x)

1. Push x to stack1 (assuming size of stacks is unlimited).

deQueue(q)

1. If both stacks are empty then error.


2. If stack2 is empty
While stack1 is not empty, push everything from stack1 to stack2.
3. Pop the element from stack2 and return it.

Correct Answer: B
 28 votes -- Dipak Majhi (757 points)

3.14.5 Queue: GATE CSE 2006 | Question: 49 top☝ ☛ https://gateoverflow.in/1826

 Answer is (A).
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 m push for delete())
 52 votes -- Kalpna Bhargav (2.5k points)

3.14.6 Queue: GATE CSE 2012 | Question: 35 top☝ ☛ https://gateoverflow.in/1756

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 433

REAR = Write
FRONT = Read
full: (REAR + 1) mod n == FRONT
empty: REAR == FRONT
Only option (A) matches.
 37 votes -- Prashant Singh (47.1k points)

3.14.7 Queue: GATE CSE 2013 | Question: 44 top☝ ☛ https://gateoverflow.in/61

 There are three possible operations on queue- Enqueue, Dequeue and MultiDequeue. MultiDequeue is calling
Dequeue multiple times based on a global variable k. Since, the queue is initially empty, whatever be the order of
these operations, there cannot be more number of Dequeue operations than Enqueue operations. Hence, the total number
operations will be n only.

Correct Answer: A
 112 votes -- Arjun Suresh (330k points)

3.14.8 Queue: GATE CSE 2016 Set 1 | Question: 10 top☝ ☛ https://gateoverflow.in/39667

 Consider a normal array implementation of a queue. We’ll have 2 pointers Front and Rear where Front points
to the first element of the queue and Rear points to the next free space. When queue is full Rear points to NULL.
The below figure depicts the Queue full condition and then a DEQUEUE is performed which removes element 4. In the
second part of the figure, all elements are shifted by one position or else we won’t be able to make use of the free space for
the next element to be inserted. So, this means Θ(n) operations for DEQUEUE where as ENQUEUE can be done in
O(1).

But we can in fact do both ENQUEUE and DEQUEUE operations in O(1) and fully utlizie the array space by smartly
using the Front and Rear pointers as shown in DEQUEUEopt . If MAX denote the total size of the array, here,

for ENQUEUE
Rear = (Rear + 1) mod MAX
for DEQUEUE
Front = (Front + 1) mod MAX
Condition for QUEUE Empty
Front == NULL (Whenever after a DEQUEUE operation Front becomes equal to Rear it means Queue is now
empty and we make Front = NULL to mark this condition as Rear = Front is the condition we use for checking
if QUEUE is full
Condition for QUEUE Full
Rear == NULL

© Copyright GATE Overflow. Some rights reserved.


434 3 Programming and DS: DS (213)

So, correct answer: A.


 1 votes -- Arjun Suresh (330k points)

3.14.9 Queue: GATE CSE 2016 Set 1 | Question: 41 top☝ ☛ https://gateoverflow.in/39684

 While loop will run for the maximum number of times when the Queue elements are sorted in descending order.

Let's suppose that initially, Queue elements are 16, 15, 14, 13, … , 2, 1

Now, 16 will be first pushed into the stack, So, now stack top is 16 and Head(Q) is 15, So 16 will be popped out of the
stack ( since, "if S is Empty OR Top(S) ≤ Head(Q) "returns false, hence else part will be executed) and enqueued into the
Queue.

So, after two iterations Queue elements will be → 15, 14, 13, … , 2, 1, 16 and stack will be empty.

Similarly, each of the elements 15, 14, 13, … , 2 will be pushed into the stack and immediately popped out of the
stack(when popped out of the stack then also enqueue into the queue).So after 30 iterations stack will be empty and Queue
contains will be like ⇒ 1, 16, 15, 14, … , 2 .

Now 1 will be Dequeued and pushed into the stack. Once 1 is pushed into the stack, it will never be popped(or we can say
never be enqueued into the Queue again) because in order to Pop 1, there should be an element into the Queue which is less
than 1 and that element comes at the front of the queue, since there is no element currently present in the Queue which is less
than 1, there is no way to pop 1.

So, after 31 iterations Queue is ⇒ 16, 15, 14, … , 2 and stack contains 1.

Now, the problem boils down to Queue with 15 elements.

Using the similar logic we can say after another 29 iterations (Total = 31 + 29 )Queue will be like ⇒ 16, 15, 14, … , 3 and
stack contains 1, 2 (stack top is 2) and then 2 will remain there in the stack forever.

Similar way if we go on then, after 31 + 29 + 27 + 25 + … + 1 iterations Queue will be empty.

This is in A.P. series with d = 2 . Sum = (16 ∗ (1 + 31))/2 = 16 ∗ 32/2 = 256


 176 votes -- Sourav Basu (2.7k points)

3.14.10 Queue: GATE CSE 2017 Set 2 | Question: 13 top☝ ☛ https://gateoverflow.in/118253

Reference: https://gateoverflow.in/1033/gate2004-36
This is how the things look.
We do insertion by cutting in between Rear and Front and we do deletion by forwarding the Front pointer and updating the
Rear accordingly.
Correct Answer: B
References

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 435

 10 votes -- Shamik Banerjee (1.2k points)

3.14.11 Queue: GATE CSE 2018 | Question: 3 top☝ ☛ https://gateoverflow.in/204077

 New node to be inserted is P .

Enqueue(){
P->Data=Data
P->Next=Head
Head=P
}

Time Complexity = O(1) Because only pointer manipulation is involved which takes constant time.
Delete Tail
Dequeue(){
temp=head
While(temp->Next->Next!=NULL)
temp=temp->next
temp->next=NULL
tail=temp
}

Time Complexity = Time for Traversing list, free the last node and keep track of Tail pointer = O(n)
Answer is B
 33 votes -- Digvijay (44.9k points)

3.14.12 Queue: GATE IT 2007 | Question: 30 top☝ ☛ https://gateoverflow.in/3463

insert() will inserts the values in reverse order.


Correct Answer: B− Reverses the order of the elements in the queue Q.
 36 votes -- srestha (85.2k points)

3.15 Stack (16) top☝

3.15.1 Stack: GATE CSE 1991 | Question: 03,vii top☝ ☛ https://gateoverflow.in/522

The following sequence of operations is performed on a stack:

© Copyright GATE Overflow. Some rights reserved.


436 3 Programming and DS: DS (213)

P USH(10), P USH(20), P OP , P USH(10), P USH(20), P OP , P OP , P OP , P USH(20), P OP


The sequence of values popped out is

A. 20, 10, 20, 10, 20


B. 20, 20, 10, 10, 20
C. 10, 20, 20, 10, 20
D. 20, 20, 10, 20, 10

gate1991 data-structures stack easy multiple-selects

Answer ☟

3.15.2 Stack: GATE CSE 1994 | Question: 1.14 top☝ ☛ https://gateoverflow.in/2457

Which of the following permutations can be obtained in the output (in the same order) using a stack assuming that the
input is the sequence 1, 2, 3, 4, 5 in that order?

A. 3, 4, 5, 1, 2
B. 3, 4, 5, 2, 1
C. 1, 5, 2, 3, 4
D. 5, 4, 3, 1, 2

gate1994 data-structures stack normal

Answer ☟

3.15.3 Stack: GATE CSE 1995 | Question: 2.21 top☝ ☛ https://gateoverflow.in/2633

The postfix expression for the infix expression A + B ∗ (C + D)/F + D ∗ E is:

A. AB + CD + ∗F /D + E∗
B. ABCD + ∗F /DE ∗ ++
C. A ∗ B + CD/F ∗ DE + +
D. A + ∗BCD/F ∗ DE + +

gate1995 data-structures stack easy

Answer ☟

3.15.4 Stack: GATE CSE 2000 | Question: 13 top☝ ☛ https://gateoverflow.in/684

Suppose a stack implementation supports, in addition to PUSH and POP, an operation REVERSE, which reverses the
order of the elements on the stack.

A. To implement a queue using the above stack implementation, show how to implement ENQUEUE using a single operation
and DEQUEUE using a sequence of 3 operations.
B. The following post fix expression, containing single digit operands and arithmetic operators + and ∗, is evaluated using a
stack.
5 2 ∗ 3 4 + 5 2 ∗ ∗+
Show the contents of the stack
i. After evaluating 5 2 ∗ 3 4+
ii. After evaluating 5 2 ∗ 3 4 + 5 2
iii. At the end of evaluation

gate2000-cse data-structures stack normal descriptive

Answer ☟

3.15.5 Stack: GATE CSE 2003 | Question: 64 top☝ ☛ https://gateoverflow.in/951

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 operations 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 P ush(m) to the start of the pop operation that removes
m from S. The average stack-life of an element of this stack is

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 437

A. n(X + Y )
B. 3Y + 2X
C. n(X + Y ) − X
D. Y + 2X

gate2003-cse data-structures stack normal

Answer ☟

3.15.6 Stack: GATE CSE 2004 | Question: 3 top☝ ☛ https://gateoverflow.in/1000

A single array A[1 … MAXSIZE] is used to implement two stacks. The two stacks grow from opposite ends of the
array. Variables top1 and top2 (top1 < top2) point to the location of the topmost element in each of the stacks. If the
space is to be used efficiently, the condition for “stack full” is

A. (top1 = MAXSIZE/2) and (top2 = MAXSIZE/2 + 1)


B. top1 + top2 = MAXSIZE
C. (top1 = MAXSIZE/2) or (top2 = MAXSIZE)
D. top1 = top2 − 1

gate2004-cse data-structures stack easy

Answer ☟

3.15.7 Stack: GATE CSE 2004 | Question: 38, ISRO2009-27 top☝ ☛ https://gateoverflow.in/1035

Assume that the operators +, −, × are left associative and ^ is right associative. The order of precedence (from highest
to lowest) is ^ , ×, +, − . The postfix expression corresponding to the infix expression a + b × c − d^ e^ f is

A. abc × +def ^ ^ −
B. abc × +de^ f ^ −
C. ab + c × d − e^ f ^
D. − + a × bc^^ def

gate2004-cse stack isro2009

Answer ☟

3.15.8 Stack: GATE CSE 2004 | Question: 5 top☝ ☛ https://gateoverflow.in/1002

The best data structure to check whether an arithmetic expression has balanced parentheses is a

A. queue
B. stack
C. tree
D. list

gate2004-cse data-structures easy stack

Answer ☟

3.15.9 Stack: GATE CSE 2007 | Question: 38, ISRO2016-27 top☝ ☛ https://gateoverflow.in/1236

The following postfix expression with single digit operands is evaluated using a stack:

8 2 3 ^ ∕ 2 3 ∗ +5 1 ∗ −

Note that ^ is the exponentiation operator. The top two elements of the stack after the first ∗ is evaluated are

A. 6, 1
B. 5, 7
C. 3, 2
D. 1, 5

© Copyright GATE Overflow. Some rights reserved.


438 3 Programming and DS: DS (213)

gate2007-cse data-structures stack normal isro2016

Answer ☟

3.15.10 Stack: GATE CSE 2014 Set 2 | Question: 41 top☝ ☛ https://gateoverflow.in/2007

Suppose a stack 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. A queue cannot be implemented using this stack.


B. A queue can be implemented where ENQUEUE takes a single instruction and DEQUEUE takes a sequence of two
instructions.
C. A queue can be implemented where ENQUEUE takes a sequence of three instructions and DEQUEUE takes a single
instruction.
D. A queue can be implemented where both ENQUEUE and DEQUEUE take a single instruction each.

gate2014-cse-set2 data-structures stack easy

Answer ☟

3.15.11 Stack: GATE CSE 2015 Set 2 | Question: 38 top☝ ☛ https://gateoverflow.in/8164

Consider the C program below


#include <stdio.h>
int *A, stkTop;
int stkFunc (int opcode, int val)
{
static int size=0, stkTop=0;
switch (opcode) {
case -1: size = val; break;
case 0: if (stkTop < size ) A[stkTop++]=val; break;
default: if (stkTop) return A[--stkTop];
}
return -1;
}
int main()
{
int B[20]; A=B; stkTop = -1;
stkFunc (-1, 10);
stkFunc (0, 5);
stkFunc (0, 10);
printf ("%d\n", stkFunc(1, 0)+ stkFunc(1, 0));
}

The value printed by the above program is ________.

gate2015-cse-set2 data-structures stack easy numerical-answers

Answer ☟

3.15.12 Stack: GATE CSE 2015 Set 3 | Question: 12 top☝ ☛ https://gateoverflow.in/8408

The result evaluating the postfix expression 10 5 + 60 6/ ∗ 8− is

A. 284
B. 213
C. 142
D. 71

gate2015-cse-set3 data-structures stack normal

Answer ☟

3.15.13 Stack: GATE CSE 2021 Set 1 | Question: 21 top☝ ☛ https://gateoverflow.in/357430

Consider the following sequence of operations on an empty stack.

push(54); push(52); pop(); push(55); push(62); s = pop();

Consider the following sequence of operations on an empty queue.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 439

enqueue(21); enqueue(24); dequeue(); enqueue(28); enqueue(32); q = dequeue();

The value of s+q is ___________.

gate2021-cse-set1 data-structures stack numerical-answers

Answer ☟

3.15.14 Stack: GATE IT 2004 | Question: 52 top☝ ☛ https://gateoverflow.in/3695

A program attempts to generate as many permutations as possible of the string, ' abcd' by pushing the characters
a, b, c, d in the same order onto a stack, but it may pop off the top character at any time. Which one of the following
strings CANNOT be generated using this program?

A. abcd
B. dcba
C. cbad
D. cabd

gate2004-it data-structures normal stack

Answer ☟

3.15.15 Stack: GATE IT 2005 | Question: 13 top☝ ☛ https://gateoverflow.in/3758

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
B. 4
C. 3
D. 2

gate2005-it data-structures stack normal

Answer ☟

3.15.16 Stack: GATE IT 2007 | Question: 32 top☝ ☛ https://gateoverflow.in/3465

Consider the following C program:


#include <stdio.h>
#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 ());
}

What is the output of the program for the following input?


5 2 ∗ 3 3 2 + ∗+
A. 15
B. 25
C. 30
D. 150

© Copyright GATE Overflow. Some rights reserved.


440 3 Programming and DS: DS (213)

gate2007-it stack normal

Answer ☟

Answers: Stack

3.15.1 Stack: GATE CSE 1991 | Question: 03,vii top☝ ☛ https://gateoverflow.in/522

 Let us try something different when you read the word pop then delete the last pushed element and print it. Now,
delete the push word which we have already executed. Now, go on from left to right and do the same.
So, output will be 20, 20, 10, 10, 20.
Correct Answer: B.
 31 votes -- Bhagirathi Nayak (11.7k points)

3.15.2 Stack: GATE CSE 1994 | Question: 1.14 top☝ ☛ https://gateoverflow.in/2457

 Push 1 push 2 push 3 pop 3 push 4 pop 4 push 5 pop 5 pop 2 pop 1 then o/p is 3, 4, 5, 2, 1
So, option is B.
 40 votes -- Sankaranarayanan P.N (8.5k points)

3.15.3 Stack: GATE CSE 1995 | Question: 2.21 top☝ ☛ https://gateoverflow.in/2633

Thus before considering + which has the least priority, we get A + (BCD + ∗F /) + (DE∗)
Now if we assume left associativity for + (default), we get ABCD + ∗F / + DE ∗ + but this is not among the options.
So, considering right associativity for + we get ABCD + ∗F /DE ∗ ++
Correct Answer: B
 48 votes -- Amar Vashishth (25.2k points)

3.15.4 Stack: GATE CSE 2000 | Question: 13 top☝ ☛ https://gateoverflow.in/684


a. For enqueue push operation is sufficient
For dequeue operation do the following
-reverse, pop, reverse

b. Contents of stack from top to bottom:

i) 7 10
ii) 2 5 7 10
ii) 80
 31 votes -- Pooja Palod (24.1k points)

3.15.5 Stack: GATE CSE 2003 | Question: 64 top☝ ☛ https://gateoverflow.in/951

 Let us represent stack-life of ith element as S(i). The ith element will be in stack till (n − i) elements are pushed
and popped. Plus one more Y for the time interval between the push of ith element and the i + 1th element. So,

S(i) = Y + 2.(n − i)(Y + X) = Y + 2.(n − i)Z = Y + 2nZ − 2iZ

where Z = Y + X

S(i)
average stack-life will, A = Σ n

nA = nY + 2.n. n. Z − 2.Z. Σi
(n(n+1))
nA = nY + 2.n. n. Z − 2.Z
© Copyright GATE Overflow. Some rights reserved.
3 Programming and DS: DS (213) 441

(n(n+1))
nA = nY + 2.n. n. Z − 2.Z 2

nA = nY + 2.n. n. Z − Z(n. n) − n. Z

A = Y + 2.n. Z − (n + 1). Z

A = Y + (n − 1). Z = Y + (n − 1)(X + Y ) = n(X + Y ) − X

Correct Answer: C
 63 votes -- Vikrant Singh (11.2k points)

3.15.6 Stack: GATE CSE 2004 | Question: 3 top☝ ☛ https://gateoverflow.in/1000

 Answer is (D).

Since the stacks are growing from opposite ends, initially top1 = 1 and top2 = MAXSIZE . Now, to make the space
usage most efficient we should allow one stack to use the maximum possible space as long as other stack doesn't need it. So,
either of the stack can grow as long as there is space on the array and hence the condition must be top1 = top2 − 1.
 52 votes -- Aditi Dan (4k points)

3.15.7 Stack: GATE CSE 2004 | Question: 38, ISRO2009-27 top☝ ☛ https://gateoverflow.in/1035

 Answer is (A).

Here is the procedure first :


Scan Infix Expression from left to right whenever you see operand just print it.
But, in case of operator
if(stack is empty) then push it.
if(precedence(tos) < precedence(current operator) ) push it. where, tos means top of stack.
else if (precedence(tos) > precedence(current operator) ) pop and print.
else if (precedence(tos) == precedence(current operator) ) then check for associativity.In case Operators are Left to right
then pop and print it otherwise push the current operator (Right to Left Associativity)
And once you have scanned infix expression completely. Make sure pop all the element and print it in same order.

Here, the infix expression is a + b × c − d^ e^ f


a : print it
+ : push into the Operator Stack
b : print it
∗ : its having higher precedence than + then push into Operator Stack
c : print it
′ −′ : ′ −′ is having less precedence than ′ ∗′ so pop from operator stack and print ′ ∗′ .after this stack will be having ′ +′ on

top.which is having same precedence as ′ −′ but both are left to right associative then just pop + and print it. Now stack is
empty. Push ′ −′ to it.
d : print it
'^ ' : top of the stack is having ′ −′ .'^ ' has higher precedence than ′ −′ .so simply push ' ^ ' into stack
e : print it.
'^ ' : Now top of the stack is ' ^ ' and has same precedence so associativity will come to picture. Since ' ^ ' is right associative as
given in question. So '^ ' will be pushed.
f : print it.

Now, we have scanned entire infix expression.Now pop the stack until it becomes empty.This way you will get
abc ∗ +def ^ ^ −.
 59 votes -- IgnitorSandeep (345 points)

3.15.8 Stack: GATE CSE 2004 | Question: 5 top☝ ☛ https://gateoverflow.in/1002

 STACK scan the expression from left to right whenever a left paranthesis is encountered just PUSH it into stack
and whenever a right paranthesis is encountered just POP it from stack. If at the end of expression we are left with an
empty stack then it is a correctly parenthesized expression.
 30 votes -- Bhagirathi Nayak (11.7k points)

© Copyright GATE Overflow. Some rights reserved.


442 3 Programming and DS: DS (213)

3.15.9 Stack: GATE CSE 2007 | Question: 38, ISRO2016-27 top☝ ☛ https://gateoverflow.in/1236

 push 8 so stack is 8

push 2 so stack is 8 2

push 8 2 3

^ pop 3 and 2 perform opn 2^ 3 and push to stack. stack is 8 8

/ pop 8 and 8 perform 8/8 and push result to stack . stack is 1

push 2 stack is 1 2

push 3 stack is 1 2 3

∗ pop 3 and 2 perform by 2 ∗ 3 and push . stack is 1 6

Hence, answer is A.
 36 votes -- Sankaranarayanan P.N (8.5k points)

3.15.10 Stack: GATE CSE 2014 Set 2 | Question: 41 top☝ ☛ https://gateoverflow.in/2007

 Correct Option: C
While ENQUEUE we REVERSE the stack, PUSH the element and then again REVERSE the stack. For DEQUE we
simply POP the element.

Option B can be used to get the first element from the stack by doing a POP after REVERSE for DEQUEUE and
PUSH for ENQUEUE. But we have to restore the stack using REVERSE (otherwise next POP won't work) which
means DEQUEUE actually needs 3 instructions and not 2.
 64 votes -- Arjun Suresh (330k points)

3.15.11 Stack: GATE CSE 2015 Set 2 | Question: 38 top☝ ☛ https://gateoverflow.in/8164

 Answer: 15

The code is pushing 5 and 10 on stack and then popping the top two elements and printing their sum.

http://ideone.com/kIUdQT
References

 32 votes -- Rajarshi Sarkar (27.8k points)

Initially stack is empty = -1


stkFunc (-1, 10); this function
case -1: size = val; break; and static size= 10 // size memory declare one time
only// and control comes out of switch b/c of break
stkFunc (0, 5); this function run
case 0: if (stkTop < size ) A[stkTop++]=val; break; here stktop is static value so
memory declare at compile time only now check if condition 0< 10 true then
A[stktop++== A[0+1]=val= 5 i.e. push 5 into stack break comes so control comes
outside
stkFunc (0, 10); this comes
case 0: if (stkTop < size ) A[stkTop++]=val; break; same as above make A[stkTop++]=
10 i,e. push 10 into stack and break comes so control comes outside
printf ("%d\n", stkFunc(1, 0)+ stkFunc(1, 0));

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 443

this function
stkFunc(1, 0) this will run
default: if (stkTop) return A[--stkTop] return top of stack which is 10
stkFunc(1, 0) this will run
default: if (stkTop) return A[--stkTop] return top of stack which is 5
printf ("%d\n", stkFunc(1, 0)+ stkFunc(1, 0));= 5+10=15 15 will be printed
 39 votes -- Prashant Singh (47.1k points)

3.15.12 Stack: GATE CSE 2015 Set 3 | Question: 12 top☝ ☛ https://gateoverflow.in/8408

 We have to keep symbol into stack and when we get two operands followed by operator. We will apply operator
on last two operands.

symbol stack
10 10 (keep in stack)
5 10 5 (keep in stack)
+ 10 5 + (apply operator on last 2 operands ⟹ 10 + 5 = 15)
60 15 60 (keep in stack)
6 15 60 6 (keep in stack)
/ 15 60 6 / (apply operator on last 2 operands ⟹ 60/6 = 10)
* 15 10 * (apply operator on last 2 operands ⟹ 10 ∗ 15 = 150)
8 150 8 (keep in stack)
− 150 8 − (apply operator on last 2 operands ⟹ 50 − 8 = 142)

So, answer is 142.


 43 votes -- Praveen Saini (41.9k points)

3.15.13 Stack: GATE CSE 2021 Set 1 | Question: 21 top☝ ☛ https://gateoverflow.in/357430

 Stack:

Push 54, push 52, pop (remove top element of stack)


Now stack 54 (remove 52), push 55, push 62, pop
Now top element is 62 (remove 62 as S )
S = 62

Queue

Enqueue 21, Enqueue 24 dequeue (remove first element of queue)


Now queue 24 (remove 21), Enqueue 28, Enqueue 32, dequeue
Starting element is 24 (remove 24 as Q)
Q = 24

S + Q = 62 + 24 = 86
 5 votes -- Ankur tiwari (557 points)

3.15.14 Stack: GATE IT 2004 | Question: 52 top☝ ☛ https://gateoverflow.in/3695


A. push a & pop a, push b & pop b, push c & pop c, and finally push d and pop d
sequence of popped elements will come to abcd
B. first push abcd, and after that pop one by one, sequence of popped elements will come to dcba
C. push abc, and after that pop one by one sequence of popped elements will come to cba, now push d and pop d, final
sequence comes to cbad
D. this sequence is not possible because ' a' can not be popped before ' b' any how

© Copyright GATE Overflow. Some rights reserved.


444 3 Programming and DS: DS (213)

 28 votes -- Manu Thakur (34.1k points)

3.15.15 Stack: GATE IT 2005 | Question: 13 top☝ ☛ https://gateoverflow.in/3758


i : Element to be pushed
Initial State f(∅) = 0. For Empty Stack f(S) is 0
Then we push each element ( i)one by one and calculate f(s) for each insertion as given

fnew (S) = max(fprevious (S), 0) + i

is the function to compute f(S) for each insertions

1. INSERT 2 on to Stack
fprevious (S) = 0 [Stack was empty ]
i = 2 (inserting element is i )
fnew (S) = max(fprevious (S), 0) + i
fnew (S) = max(0, 0) + 2 = 2
2. INSERT −3 on to Stack
fprevious (S) = 2 [Stack was empty ]
i = −3 (inserting element is i )
fnew (S) = max(fprevious (S), 0) + i
fnew (S) = max(2, 0) + −3 = −1

Similarly,

i: The element to be pushed


S: Stack
Initially f(S) = 0.

f(S) max(f(S), 0) i fnew (S) = max(f(S), 0) + i


0 0 2 2
2 2 -3 -1
-1 0 2 2
2 2 -1 1
1 1 2 3

Thus, the answer is Option C.


The value of f(S) after inserting all elements into stack is 3.
 88 votes -- Shridhar (311 points)

3.15.16 Stack: GATE IT 2007 | Question: 32 top☝ ☛ https://gateoverflow.in/3465

 Correct Option: B
25
let first part
5 ----push
2------push
push------5 ∗ 2 = 10 . (pops 5 and 2)

push 3
push 3
push 2
push 3 + 2 = 5 (pops 2 and 3)
push 5 ∗ 3 = 15 (pops ( 5 and 3)
push 15 + 10 = 25 (pops ( 15 and 10)
 26 votes -- Arpit Dhuriya (2.9k points)

3.16 Trees (14) top☝

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 445

3.16.1 Trees: GATE CSE 1990 | Question: 13a top☝ ☛ https://gateoverflow.in/86224

Consider the height-balanced tree Tt with values stored at only the leaf nodes, shown in Fig .4.

(i) Show how to merge to the tree, T1 elements from tree T2 shown in Fig .5 using node D of tree T1 .

(ii) What is the time complexity of a merge operation of balanced trees T1 and T2 where T1 and T2 are of height h1 and h2
respectively, assuming that rotation schemes are given. Give reasons.

gate1990 data-structures trees descriptive

Answer ☟

3.16.2 Trees: GATE CSE 1992 | Question: 02,vii top☝ ☛ https://gateoverflow.in/562

A 2 − 3 tree is such that

a. All internal nodes have either 2 or 3 children


b. All paths from root to the leaves have the same length

The number of internal nodes of a 2 − 3 tree having 9 leaves could be

A. 4
B. 5
C. 6
D. 7

gate1992 trees data-structures normal multiple-selects

Answer ☟

3.16.3 Trees: GATE CSE 1994 | Question: 5 top☝ ☛ https://gateoverflow.in/2501

A 3 − ary tree is a tree in which every internal node has exactly three children. Use induction to prove that the number
of leaves in a 3 − ary tree with n internal nodes is 2(n + 1).

gate1994 data-structures trees proof descriptive

Answer ☟

3.16.4 Trees: GATE CSE 1998 | Question: 1.24 top☝ ☛ https://gateoverflow.in/1661

Which of the following statements is false?

A. A tree with a n nodes has (n– 1) edges


B. A labeled rooted binary tree can be uniquely constructed given its postorder and preorder traversal results.
C. A complete binary tree with n internal nodes has (n + 1) leaves.
D. The maximum number of nodes in a binary tree of height h is 2h+1 − 1

© Copyright GATE Overflow. Some rights reserved.


446 3 Programming and DS: DS (213)

gate1998 data-structures trees multiple-selects normal

Answer ☟

3.16.5 Trees: GATE CSE 1998 | Question: 2.11 top☝ ☛ https://gateoverflow.in/1683

A complete n-ary tree is one in which every node has 0 or n sons. If x is the number of internal nodes of a complete n-
ary tree, the number of leaves in it is given by

A. x(n − 1) + 1
B. xn − 1
C. xn + 1
D. x(n + 1)

gate1998 data-structures trees normal

Answer ☟

3.16.6 Trees: GATE CSE 1998 | Question: 21 top☝ ☛ https://gateoverflow.in/1735

A. Derive a recurrence relation for the size of the smallest AVL tree with height h.
B. What is the size of the smallest AVL tree with height 8?

gate1998 data-structures trees descriptive numerical-answers

Answer ☟

3.16.7 Trees: GATE CSE 2002 | Question: 2.9 top☝ ☛ https://gateoverflow.in/839

The number of leaf nodes in a rooted tree of n nodes, with each node having 0 or 3 children is:
n
A. 2
(n−1)
B. 3
(n−1)
C. 2
(2n+1)
D. 3

gate2002-cse data-structures trees normal

Answer ☟

3.16.8 Trees: GATE CSE 2004 | Question: 6 top☝ ☛ https://gateoverflow.in/1003

Level order traversal of a rooted tree can be done by starting from the root and performing

A. preorder traversal
B. in-order traversal
C. depth first search
D. breadth first search

gate2004-cse data-structures trees easy

Answer ☟

3.16.9 Trees: GATE CSE 2005 | Question: 36 top☝ ☛ https://gateoverflow.in/1372

In a complete k-ary tree, every internal node has exactly k children. The number of leaves in such a tree with n internal
node is:

A. nk
B. (n − 1)k + 1
C. n(k − 1) + 1
D. n(k − 1)

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 447

gate2005-cse data-structures trees normal

Answer ☟

3.16.10 Trees: GATE CSE 2007 | Question: 43 top☝ ☛ https://gateoverflow.in/1241

A complete n − ary tree is a tree in which each node has n children or no children. Let I be the number of internal
nodes and L be the number of leaves in a complete n − ary tree. If L = 41 and I = 10 , what is the value of n?

A. 3
B. 4
C. 5
D. 6

gate2007-cse data-structures trees normal

Answer ☟

3.16.11 Trees: GATE CSE 2014 Set 3 | Question: 12 top☝ ☛ https://gateoverflow.in/2046

Consider the following rooted tree with the vertex labeled P as the root:

The order in which the nodes are visited during an in-order traversal of the tree is

A. SQPT RWUV
B. SQPT UWRV
C. SQPT WUV R
D. SQPT RUWV

gate2014-cse-set3 data-structures trees easy

Answer ☟

3.16.12 Trees: GATE CSE 2014 Set 3 | Question: 41 top☝ ☛ https://gateoverflow.in/2075

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);
}

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

© Copyright GATE Overflow. Some rights reserved.


448 3 Programming and DS: DS (213)

A. number of internal nodes in the tree.


B. height of the tree.
C. number of nodes without a right sibling in the tree.
D. number of leaf nodes in the tree

gate2014-cse-set3 data-structures trees normal

Answer ☟

3.16.13 Trees: GATE CSE 2017 Set 1 | Question: 20 top☝ ☛ https://gateoverflow.in/118300

Let T be a tree with 10 vertices. The sum of the degrees of all the vertices in T is ________

gate2017-cse-set1 data-structures trees numerical-answers

Answer ☟

3.16.14 Trees: GATE CSE 2021 Set 1 | Question: 41 top☝ ☛ https://gateoverflow.in/357410

A n articulation point in a connected graph is a vertex such that removing the vertex and its incident edges
disconnects the graph into two or more connected components.
Let T be a DFS tree obtained by doing DFS in a connected undirected graph G.
Which of the following options is/are correct?

A. Root of T can never be an articulation point in G.


B. Root of T is an articulation point in G if and only if it has 2 or more children.
C. A leaf of T can be an articulation point in G.
D. If u is an articulation point in G such that x is an ancestor of u in T and y is a descendent of u in T , then all paths from
x to y in G must pass through u.

gate2021-cse-set1 multiple-selects data-structures trees

Answer ☟

Answers: Trees

3.16.1 Trees: GATE CSE 1990 | Question: 13a top☝ ☛ https://gateoverflow.in/86224

 Superscripts near the nodes indicate their Balance factor. LL and RR rotations are same as those done on AVL
trees.

 9 votes -- Charan (1.1k points)

3.16.2 Trees: GATE CSE 1992 | Question: 02,vii top☝ ☛ https://gateoverflow.in/562

 Correct Options: A;D

4 → When each leaf has 3 childs. So 9/3 = 3 Internal nodes, Then one internal node those internal nodes.

7 → When each leaf has 2 childs & one leaf out of 4 get 3 childs. Ex → 8/4 = 2 child per internal node. Then one of that
internal node get extra third child. Then 2 internal nodes to connect these 4. Then 1 internal node to connect this 2. So
4 + 2 + 1 = 7.

No other way is possible.

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 449

 26 votes -- Akash Kanase (36k points)

3.16.3 Trees: GATE CSE 1994 | Question: 5 top☝ ☛ https://gateoverflow.in/2501

 Number of nodes at level i = 3i

Let height of the tree be h

3h −1
So total no of internal nodes, n = 30 + 31 + 32 + ⋯ + 3h−1 = 2

2n = 3h − 1

Number of leaf nodes = 3h = 2n + 1 = 2(n − 1) + 3

Let us prove by induction

Base case

n = 1 (one internal node i.e., root node)

No of leaves = 2(1 − 1) + 3 = 3

Let it be true for n internal nodes

Now we prove for m nodes where m = n + 1

We have L(m) = 2(n + 1 − 1) + 3

Also L(m) = L(n) + 3 − 1 = 2(n − 1) + 3 + 3 − 1 = 2n + 3

So if L(n) is true then L(n + 1) is also true

Hence proved by induction.


 13 votes -- Pooja Palod (24.1k points)

3.16.4 Trees: GATE CSE 1998 | Question: 1.24 top☝ ☛ https://gateoverflow.in/1661


Tree with n nodes must have n − 1 edges.
A labeled rooted binary tree can be uniquely constructed given its postorder and preorder traversal results. (inorder must
be needed with either preorder or postorder for that)
A complete binary tree with n nodes can have n leaves also
Example:

Since: A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all
nodes are as far left as possible. So false

The maximum number of nodes in a binary tree of height h is

1 + 2 + 4+. . . . . +2h = 2h+1 − 1 So true


Answer is b and c both.
Since, 2 answers are there I would choose b, because in some places by "complete" binary tree they mean "full binary tree"
which has all the levels completely filled.

© Copyright GATE Overflow. Some rights reserved.


450 3 Programming and DS: DS (213)

 27 votes -- Prashant Singh (47.1k points)

3.16.5 Trees: GATE CSE 1998 | Question: 2.11 top☝ ☛ https://gateoverflow.in/1683

 Correct Option: A
x(n − 1) + 1
Originally when we have root , there is only 1 node, which is leaf. (There is no internal node.) From this base case "+1"
part of formula comes.
When we n children to root, we make root internal. So then Total Leaves = = 1(n − 1) + 1 = n .
In complete n ary tree every time you add n children to node, you add n − 1 leaves & make that node to which you are
inserting childen internal.( +n for leaves, −1 for node which you are attaching ). So if you had originally few leaves, you
add n − 1 "New" leaves to them. This is how x(n − 1) + 1 makes sense.
 33 votes -- Akash Kanase (36k points)

3.16.6 Trees: GATE CSE 1998 | Question: 21 top☝ ☛ https://gateoverflow.in/1735


a. Consider a function N(h) which represents the smallest number of nodes n for an AVL tree with height h and
satisfies n = N(h).
For h = 0 we have, number of nodes = 1. So N(0) = 1
For h = 1 , we have, number of nodes = 2. We could take 3, but we require the smallest graph (a graph with smallest
number of nodes) so we take 2. It means that to create a tree with height $14 we need at least 24 nodes.
So N(1) = 2
Now, for h = 2 , we need to create a node with a child subtree of height 1. This may be the right or left subtree. But since
this is an AVL tree, to balance a child subtree of height let's say Hs , we need the other child to have a height of Hs − 1 ,
Hs or Hs + 1 . But we take Hs − 1 for minimal case. In simple words, a node with height 5 must have a child with
height 4(Hs) and another child with height 3(Hs − 1). So N(2) can be obtained as:
N(2) = N(1) + (0) + 1 ( 1 is added to count the parent node, N(1) or N(Hs) and N(0) or N(Hs − 1) represent
two subtrees.)
Similarly:
N(3) = N(2) + N(1) + 1
and generalizing:
N(h) = N(h − 1) + N(h − 2) + 1

b. This recursion can be graphically seen as below:

Using the above recursion, we need to find N(8)


N(0) = 1
N(1) = 2
N(2) = N(1) + N(0) + 1 = 1 + 2 + 1 = 4
N(3) = N(2) + N(1) + 1 = 2 + 4 + 1 = 7
N(4) = N(3) + N(2) + 1 = 4 + 7 + 1 = 12
N(5) = N(4) + N(3) + 1 = 7 + 12 + 1 = 20
N(6) = N(5) + N(4) + 1 = 12 + 20 + 1 = 33
N(7) = N(6) + N(5) + 1 = 20 + 33 + 1 = 54
N(8) = N(7) + N(6) + 1 = 33 + 54 + 1 = 88

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 451

So, answer for (b) is 88.


 30 votes -- Ashis Kumar Sahoo (699 points)

3.16.7 Trees: GATE CSE 2002 | Question: 2.9 top☝ ☛ https://gateoverflow.in/839

 L = leaf nodes
I = internal nodes
n = total nodes = L + I
In a tree no. of edges = n − 1
All edges are produced by only internal nodes so,
k×I=n−1 → (1) (for k − ary tree, in this question k = 3 )
L+I=n → (2)
Here, given options are in terms of "n". So, eliminating I from (1) and (2),
L = ((k − 1)n + 1)/k
you get L = (2n + 1)/3
Answer is D.
 50 votes -- Vikrant Singh (11.2k points)

3.16.8 Trees: GATE CSE 2004 | Question: 6 top☝ ☛ https://gateoverflow.in/1003

 Answer is option D.
Breadth first seach.
 20 votes -- anshu (2.7k points)

3.16.9 Trees: GATE CSE 2005 | Question: 36 top☝ ☛ https://gateoverflow.in/1372

 Correct Option: C
Originally when we have root , there is only 1 node, which is leaf.(There is no internal node.) From that " +1" part of
formula comes from this base case.

When we k children to nodes, we make root internal. So then Total Leaves = n(k − 1) + 1 = (k − 1) + 1 = k

In k complete k ary tree every time you add k children , you add k − 1 leaves.( +k for leaves, −1 for node which you are
attaching )
 16 votes -- Akash Kanase (36k points)

3.16.10 Trees: GATE CSE 2007 | Question: 43 top☝ ☛ https://gateoverflow.in/1241

 If you do little bit experiments on no of leaves, Internal nodes, you will realize that they have equation like
following :-

No of leaves (L) = (n − 1)∗ Internal Nodes (I) + 1

Here we need to find n.

Putting values

41 = (n − 1) ∗ 10 + 1
⟹ (n − 1) ∗ 10 = 40
⟹ n−1=4
⟹ n=5

So, answer is C.
 29 votes -- Akash Kanase (36k points)

Sum of degrees in tree = L + I × (n + 1) − 1 = 10n + 50( Each leaf node has degree 1 and all internal nodes have
degree k + 1, except root which has degree k)

© Copyright GATE Overflow. Some rights reserved.


452 3 Programming and DS: DS (213)

So, number of edges = 5n + 25(Number of edges in a graph (hence applicable for tree also) is half the sum of degrees as
each edge contribute 2 to the sum of degrees)

In a tree with n nodes we have n − 1 edges, so with 41 + 10 = 51 nodes, there must be 50 edges.

So, 5n + 25 = 50

⟹ 5n = 25

⟹ n=5
 36 votes -- Arjun Suresh (330k points)

3.16.11 Trees: GATE CSE 2014 Set 3 | Question: 12 top☝ ☛ https://gateoverflow.in/2046

 Correct Option: A
The inorder traversal order of a ternary tree is left → root → middle → right.
 46 votes -- Gate Keeda (15.9k points)

3.16.12 Trees: GATE CSE 2014 Set 3 | Question: 41 top☝ ☛ https://gateoverflow.in/2075

 Here, the condition for count value = 1 is


if ( tree → leftMostchild == Null)

so, if there is no left-most child of the tree (or the sub-tree or the current node called in recursion)
Which means there is no child to that particular node (since if there is no left-most child, there is no child at all as per the
tree representation given).
∴ the node under consideration is a leaf node.
The function recursively counts, and adds to value, whenever a leaf node is encountered.

So, The function returns the number of leaf nodes in the tree. Answer is D
 32 votes -- Kalpish Singhal (1.6k points)

3.16.13 Trees: GATE CSE 2017 Set 1 | Question: 20 top☝ ☛ https://gateoverflow.in/118300

 Tree with n vertices which means n − 1 edges.

n = 10 ∴ edges = n − 1 = 9 .

∴ Sum of degree of all vertices ≤ 2E ≤ 2 ∗ 9 ≤ 18

Answer is 18
 41 votes -- Kantikumar (3.4k points)

3.16.14 Trees: GATE CSE 2021 Set 1 | Question: 41 top☝ ☛ https://gateoverflow.in/357410

As per the option B it says root of T can be an articulation point in G if and only if it has 2 or more children, now here for
simplicity I have taken simple case where root will have 2 children and I will tell you for the generalized case later. Also as

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 453

its double implication lets see it as separately


Case 1: If root is articulation point then root will have 2 or more children
If a vertex is articulation point then its removal disconnects the graph into 2 or more components means there must exist at
least 2 vertices for which each and every path in between them will pass through articulation point and removal of
articulation point will destroy all the paths in between them and thereby disconnecting the graph into components, otherwise
that vertex can not be an articulation point because even if we remove that vertex still every pair of vertices has some other
path and hence graph wont get disconnected.
Now when we start DFS Traversal from vertex V (articulation point) we may visit either the vertex from G1 or G2 first, lets
say we visited vertex of G2 first now during the DFS traversal which becomes child of V now we can never visit any vertex
in G1 unless and until we do not use vertex V because every path will go through vertex V only, and by the nature of
DFS no vertex during the traversal of sub-graph G2 can visit the vertex V again as it will be having Gray color/ not yet
finished (refer DFS algorithm from CLRS for better understanding) and because of this property all the vertices in G2 will be
exhausted and we will be back to the vertex V but vertex V still has path to the unvisited vertices of sub-graph G1 and hence
the first vertex which will be visited in G1 will become the new child of V thereby making 2 children for the root vertex V
which is the articulation point.
Case 2: If root vertex has 2 or more children then it is articulation point
Lets say in an undirected graph if root has 2 children then it is true that there is no path between the vertices in left sub-tree
and right sub-tree of vertex V (w.r.t DFS traversal tree) because if there had been any path between the left and right sub-tree
the in that case if we start with right child then before reaching to the root all the vertices in left sub-tree would have been
visited and root had only single child but it is contradiction as root has 2 children and hence there can be no path between the
left and right sub-tree of vertex V , thereby making it the ONLY vertex through which vertices in left and right sub-tree are
connected
Hence above two cases proves the option B is correct and A is incorrect
For the generalized case visualize star graph with many vertices where center is articulation point, now you got the intuition
and apply this on any graph!
Lets understand option C.
Option C says that leaf of tree T can be an articulation point, its FALSE because if some vertex is leaf of tree T then all the
vertices to which it connects are already been visited which indicates that even without using this leaf vertex there exists path
between all of its neighbors and hence it can not be an articulation point.
Hence option C is incorrect
Now option D
Option D talks about ancestors and decedents X and Y and says that if X is ancestor of U in T and Y is decedent then all
the paths between X and Y must pass through U but we have counter for this as shown below.

Hence option D is incorrect


 16 votes -- Jaydeep Vasudev Pawar (295 points)

Answer Keys
3.1.1 C 3.2.1 N/A 3.2.2 C 3.2.3 N/A 3.2.4 N/A
3.2.5 A 3.2.6 A 3.2.7 N/A 3.2.8 A 3.2.9 B
3.2.10 C 3.2.11 B 3.2.12 5 3.2.13 C 3.3.1 B
3.3.2 C 3.3.3 A 3.4.1 80 3.4.2 511 3.4.3 C
3.5.1 B 3.5.2 N/A 3.5.3 D 3.5.4 N/A 3.5.5 C
3.5.6 B 3.5.7 B 3.5.8 B 3.5.9 B 3.5.10 A

© Copyright GATE Overflow. Some rights reserved.


454 3 Programming and DS: DS (213)

3.5.11 B 3.5.12 C 3.5.13 D 3.5.14 C 3.5.15 110


3.5.16 A 3.5.17 B 3.5.18 B 3.5.19 64 3.5.20 B
3.5.21 B 3.5.22 B 3.5.23 B 3.5.24 D 3.5.25 C
3.5.26 D 3.5.27 C 3.5.28 A 3.5.29 D 3.5.30 C
3.5.31 B 3.6.1 False 3.6.2 False 3.6.3 N/A 3.6.4 N/A
3.6.5 N/A 3.6.6 N/A 3.6.7 B 3.6.8 144 3.6.9 N/A
3.6.10 N/A 3.6.11 N/A 3.6.12 N/A 3.6.13 N/A 3.6.14 N/A
3.6.15 B 3.6.16 N/A 3.6.17 B 3.6.18 C 3.6.19 N/A
3.6.20 N/A 3.6.21 C 3.6.22 D 3.6.23 D 3.6.24 N/A
3.6.25 B 3.6.26 D 3.6.27 D 3.6.28 C 3.6.29 B
3.6.30 A 3.6.31 C 3.6.32 A 3.6.33 B 3.6.34 A
3.6.35 1 3.6.36 A 3.6.37 19 3.6.38 199 3.6.39 C
3.6.40 4 3.6.41 4.25 3.6.42 1:1 3.6.43 D 3.6.44 B
3.6.45 D 3.6.46 C 3.6.47 B 3.6.48 D 3.6.49 B
3.6.50 A 3.7.1 A;C;D 3.8.1 B 3.8.2 D 3.8.3 B
3.8.4 12 3.8.5 C 3.9.1 B 3.9.2 C 3.9.3 N/A
3.9.4 N/A 3.9.5 C 3.9.6 B 3.9.7 C 3.9.8 C
3.9.9 C 3.9.10 A 3.9.11 A 3.9.12 B 3.9.13 80
3.9.14 C 3.9.15 B 3.9.16 D 3.10.1 N/A 3.10.2 C
3.10.3 N/A 3.10.4 B 3.10.5 D 3.10.6 A 3.10.7 D
3.10.8 A 3.10.9 D 3.10.10 A 3.10.11 B 3.10.12 C
3.10.13 D 3.10.14 B 3.10.15 A 3.10.16 B 3.10.17 A
3.10.18 D 3.10.19 B 3.10.20 8 3.10.21 A 3.10.22 B
3.10.23 C 3.10.24 B 3.11.1 N/A 3.11.2 A 3.11.3 N/A
3.12.1 B 3.12.2 N/A 3.12.3 N/A 3.12.4 B 3.12.5 D
3.12.6 C 3.12.7 N/A 3.12.8 N/A 3.12.9 N/A 3.12.10 D
3.12.11 B 3.12.12 A 3.12.13 D 3.12.14 B 3.12.15 D
3.12.16 C 3.12.17 B 3.12.18 C 3.12.19 A 3.12.20 B
3.13.1 D 3.14.1 N/A 3.14.2 N/A 3.14.3 A 3.14.4 B
3.14.5 A 3.14.6 A 3.14.7 A 3.14.8 A 3.14.9 256
3.14.10 B 3.14.11 B 3.14.12 B 3.15.1 B 3.15.2 B
3.15.3 B 3.15.4 N/A 3.15.5 C 3.15.6 D 3.15.7 A
3.15.8 B 3.15.9 A 3.15.10 C 3.15.11 15 3.15.12 C
3.15.13 86 : 86 3.15.14 D 3.15.15 C 3.15.16 B 3.16.1 N/A
3.16.2 A;D 3.16.3 N/A 3.16.4 B;C 3.16.5 A 3.16.6 N/A
3.16.7 D 3.16.8 D 3.16.9 C 3.16.10 C 3.16.11 A
3.16.12 D 3.16.13 18 3.16.14 B

© Copyright GATE Overflow. Some rights reserved.


3 Programming and DS: DS (213) 455

4 Programming and DS: Programming (108)

Programming in C. Recursion.

Mark Distribution in Previous GATE


Year 2021-1 2021-2 2020 2019 2018 2017-1 2017-2 2016-1 2016-2 Minimum Average Maximum
1 Mark Count 0 2 1 2 2 1 2 2 1 0 1.4 2
2 Marks Count 2 2 2 3 3 4 4 2 2 2 2.6 4
Total Marks 4 6 5 8 8 9 10 6 5 4 6.7 10

4.1 Aliasing (1) top☝

4.1.1 Aliasing: GATE CSE 2000 | Question: 1.16 top☝ ☛ https://gateoverflow.in/639

Aliasing in the context of programming languages refers to

A. multiple variables having the same memory location


B. multiple variables having the same value
C. multiple variables having the same identifier
D. multiple uses of the same variable

gate2000-cse programming easy aliasing

Answer ☟

Answers: Aliasing

4.1.1 Aliasing: GATE CSE 2000 | Question: 1.16 top☝ ☛ https://gateoverflow.in/639

 Option is A.
In computer programming, aliasing refers to the situation where the same memory location can be accessed using different
names. For instance, if a function takes two pointers A and B which have the same value, then the name A aliases the name
B.
 37 votes -- Prasanna Ranganathan (3.9k points)

4.2 Arrays (11) top☝

4.2.1 Arrays: GATE CSE 2011 | Question: 22 top☝ ☛ https://gateoverflow.in/2124

What does the following fragment of C program print?


char c[] = "GATE2011";
char *p = c;
printf("%s", p + p[3] - p[1]);

A. GATE2011
B. E2011
C. 2011
D. 011

gate2011-cse programming programming-in-c normal arrays

Answer ☟

4.2.2 Arrays: GATE CSE 2015 Set 3 | Question: 30 top☝ ☛ https://gateoverflow.in/8486

Consider the following two C code segments. Y and X are one and two dimensional arrays of size n and n × n
respectively, where 2 ≤ n ≤ 10 . Assume that in both code segments, elements of Y are initialized to 0 and each
element X[i][j] of array X is initialized to i + j. Further assume that when stored in main memory all elements of X are in
same main memory page frame.
Code segment 1:
// initialize elements of Y to 0
// initialize elements of X[i][j] of X to i+j
for (i=0; i<n; i++)
Y[i] += X[0][i];

© Copyright GATE Overflow. Some rights reserved.


456 3 Programming and DS: DS (213)

Code segment 2:
// initialize elements of Y to 0
// initialize elements of X[i][j] of X to i+j
for (i=0; i<n; i++)
Y[i] += X[i][0];

Which of the following statements is/are correct?


S1: Final contents of array Y will be same in both code segments
S2: Elements of array X accessed inside the for loop shown in code segment 1 are contiguous in main memory
S3: Elements of array X accessed inside the for loop shown in code segment 2 are contiguous in main memory

A. Only S2 is correct
B. Only S3 is correct
C. Only S1 and S2 are correct
D. Only S1 and S3 are correct

gate2015-cse-set3 programming-in-c normal arrays

Answer ☟

4.2.3 Arrays: GATE CSE 2015 Set 3 | Question: 7 top☝ ☛ https://gateoverflow.in/8401

Consider the following C program segment.


# include <stdio.h>
int main()
{
char s1[7] = "1234", *p;
p = s1 + 2;
*p = '0';
printf("%s", s1);
}

What will be printed by the program?

A. 12
B. 120400
C. 1204
D. 1034

gate2015-cse-set3 programming programming-in-c normal arrays

Answer ☟

4.2.4 Arrays: GATE CSE 2017 Set 2 | Question: 55 top☝ ☛ https://gateoverflow.in/118335

Consider the following C program.


#include<stdio.h>
#include<string.h>
int main() {
char* c=”GATECSIT2017”;
char* p=c;
printf(“%d”, (int)strlen(c+2[p]-6[p]-1));
return 0;
}

The output of the program is _______

gate2017-cse-set2 programming-in-c numerical-answers arrays

Answer ☟

4.2.5 Arrays: GATE CSE 2019 | Question: 24 top☝ ☛ https://gateoverflow.in/302824

Consider the following C program:


#include <stdio.h>
int main() {
int arr[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5}, *ip=arr+4;
printf(“%d\n”, ip[1]);
return 0;

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 457

The number that will be displayed on execution of the program is _______

gate2019-cse numerical-answers programming-in-c programming arrays

Answer ☟

4.2.6 Arrays: GATE CSE 2020 | Question: 22 top☝ ☛ https://gateoverflow.in/333209

Consider the following C program.


#include <stdio.h>
int main () {
int a[4] [5] = {{1, 2, 3, 4, 5},
{6, 7,8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17,18, 19, 20}};
printf(“%d\n”, *(*(a+**a+2)+3));
return(0);
}

The output of the program is _______.

gate2020-cse numerical-answers programming-in-c arrays

Answer ☟

4.2.7 Arrays: GATE CSE 2021 Set 2 | Question: 10 top☝ ☛ https://gateoverflow.in/357530

Consider the following ANSI C program.


#include <stdio.h>
int main()
{
int arr[4][5];
int i, j;
for (i=0; i<4; i++)
​​​​​​{
for (j=0; j<5; j++)
{
arr[i][j] = 10 * i + j;
}
}
printf(“%d”, *(arr[1]+9));
return 0;
}

What is the output of the above program?

A. 14
B. 20
C. 24
D. 30

gate2021-cse-set2 programming-in-c arrays output

Answer ☟

4.2.8 Arrays: GATE IT 2004 | Question: 58 top☝ ☛ https://gateoverflow.in/3701

Consider the following C program which is supposed to compute the transpose of a given 4 × 4 matrix M . Note that,
there is an X in the program which indicates some missing statements. Choose the correct option to replace X in the
program.
#include<stdio.h>
#define ROW 4
#define COL 4
int M[ROW][COL] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
main()
{
int i, j, t;
for (i = 0; i < 4; ++i)
{
X
}

© Copyright GATE Overflow. Some rights reserved.


458 4 Programming and DS: Programming (108)

for (i = 0; i < 4; ++i)


for (j = 0; j < 4; ++j)
printf ("%d", M[i][j]);
}

A. for(j = 0; j < 4; ++j){


t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}

B. for(j = 0; j < 4; ++j){


M[i][j] = t;
t = M[j][i];
M[j][i] = M[i][j];
}

C. for(j = i; j < 4; ++j){


t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}

D. for(j = i; j < 4; ++j){


M[i][j] = t;
t = M[j][i];
M[j][i] = M[i][j];
}

gate2004-it programming easy programming-in-c arrays

Answer ☟

4.2.9 Arrays: GATE IT 2008 | Question: 49 top☝ ☛ https://gateoverflow.in/3359

What is the output printed by the following C code?


# include <stdio.h>
int main ()
{
char a [6] = "world";
int i, j;
for (i = 0, j = 5; i < j; a [i++] = a [j--]);
printf ("%s\n", a);
}

A. dlrow
B. Null string
C. dlrld
D. worow

gate2008-it programming programming-in-c normal arrays

Answer ☟

4.2.10 Arrays: GATE IT 2008 | Question: 51 top☝ ☛ https://gateoverflow.in/3361

Consider the C program given below. What does it print?


#include <stdio.h>
int main ()
{
int i, j;
int a [8] = {1, 2, 3, 4, 5, 6, 7, 8};
for(i = 0; i < 3; i++) {
a[i] = a[i] + 1;
i++;
}
i--;
for (j = 7; j > 4; j--) {
int i = j/2;
a[i] = a[i] - 1;
}
printf ("%d, %d", i, a[i]);
}

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 459

A. 2, 3
B. 2, 4
C. 3, 2
D. 3, 3

gate2008-it programming programming-in-c normal arrays

Answer ☟

4.2.11 Arrays: GATE IT 2008 | Question: 52 top☝ ☛ https://gateoverflow.in/3362

C program is given below:


# include <stdio.h>
int main ()
{
int i, j;
char a [2] [3] = {{'a', 'b', 'c'}, {'d', 'e', 'f'}};
char b [3] [2];
char *p = *b;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
*(p + 2*j + i) = a [i] [j];
}
}
}

What should be the contents of the array b at the end of the program?

A. a b
c d
e f

B. a d
b e
c f

C. a c
e b
d f

D. a e
d c
b f

gate2008-it programming programming-in-c normal arrays

Answer ☟

Answers: Arrays

4.2.1 Arrays: GATE CSE 2011 | Question: 22 top☝ ☛ https://gateoverflow.in/2124

 2011 is the answer.

In C, there is a rule that whatever character code be used by the compiler, codes of all alphabets and digits must be in order.
So, if character code of 'A' is x, then for ' B' it must be x + 1.

Now %s means printf takes and address and prints all bytes starting from that address as characters till any byte becomes the
code for '\0'. Now, the passed value to printf here is
p + p[3] − p[1]

p is the starting address of array c. p[3] =′ E ′ and p[1] =′ A′ . So, p[3] − p[1] = 4, and p + 4 will be pointing to the fifth
position in the array c. So, printf starts printing from 2 and prints 2011.

(Here "GATE2011" is a string literal and by default a '\0' is added at the end of it by the compiler).

NB: In this question %s is not required.

© Copyright GATE Overflow. Some rights reserved.


460 4 Programming and DS: Programming (108)

printf(p + p[3] - p[1]);

Also gives the same result as first argument to printf is a character pointer and only if we want to pass more arguments we
need to use a format string.

 72 votes -- Arjun Suresh (330k points)

4.2.2 Arrays: GATE CSE 2015 Set 3 | Question: 30 top☝ ☛ https://gateoverflow.in/8486

 Option is C. Only S1 and S2 are correct because Y have same element in both code and in code 1.
Y[i] += X[0][i];

This row major order (In C, arrays are stored in row-major order) which gives address of each element in sequential order
(1, 2, 3, . . . . , n) means we cross single element each time to move next shows contiguous in main memory but in code2
for:
Y [i]+ = X[i][0];
We are crossing n element (row crossing with n element )to move next.

 36 votes -- Anoop Sonkar (4.1k points)

4.2.3 Arrays: GATE CSE 2015 Set 3 | Question: 7 top☝ ☛ https://gateoverflow.in/8401

 p = s1 + 2;

Type of s1 is char[7] and sizeof *s1 is sizeof (char) = 1. So, s1 + 2 will return address in s1 + 2 *sizeof(char) = address in s1
+ 2. So, p now points to the third element in s1.
*p = '0';

The third element in s1 is made 0. So, 1234 becomes 1204. C choice.


 57 votes -- Arjun Suresh (330k points)

4.2.4 Arrays: GATE CSE 2017 Set 2 | Question: 55 top☝ ☛ https://gateoverflow.in/118335


char c[]="GATECSIT2017";
char *p=c;
printf("%d",strlen(c+2[p]-6[p]-1));

2[p] = ∗(2 + p) = p[2]


6[p] = ∗(6 + p) = p[6]
c + 2[p] − 6[p] − 1 = c +′ T ′ −′ I ′ − 1 = c + 11 − 1 = c + 10 (In any character coding all alphabet letters are
assigned consecutive int values as per C)
printf will print 2 which is the length of " 17".
 71 votes -- Arjun Suresh (330k points)

4.2.5 Arrays: GATE CSE 2019 | Question: 24 top☝ ☛ https://gateoverflow.in/302824

 6
ip is an integer pointer and the initial assignment sets it to the element at array index 4 i.e. 5.(holds address of ar
index 4)
The next statement refers to the next integer after it which is 6(ip[1] = ∗(ip + 1)).
 19 votes -- vin101 (853 points)

4.2.6 Arrays: GATE CSE 2020 | Question: 22 top☝ ☛ https://gateoverflow.in/333209

 'a' is a two dimensional array.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 461

a = address of 0th index of 2-D array which means address of 1-D array
∗a = address of 0th index element of 0th index 1-D array
∗∗ a = value at 0th index element of 0th index 1-D array

⟹ ∗∗ a = 1
⟹ ∗∗ a + 2 = 1 + 2 = 3
a + 3 = address of 3rd index 1-D array
∗ (a + 3) = address of 0th index element of 3rd index 1-D array
∗ (a + 3) + 3 = address of 3rd index element of 3rd index 1-D array
∗ (∗ (a + 3) + 3) = value at 3rd index element of 3rd index 1-D array = 19

Correct Answer: 19.


 28 votes -- Shaik Masthan (50.4k points)

4.2.7 Arrays: GATE CSE 2021 Set 2 | Question: 10 top☝ ☛ https://gateoverflow.in/357530

 arr[1] + 9
arr[1] is a pointer to 1D array of 5 integers and so the above expression involves pointer arithmetic.
For a pointer value p and integer value d,

p + d ⟹ p + sizeof(∗p) + d

So,
arr[1]+9 = *(arr+1) + 9 //arr is again a pointer but to the 2D array arr[4][5]

arr+1 = arr + sizeof(*arr)


= arr + 5 * sizeof (int)

*(arr+1)+9 = arr + 5 * sizeof(int) + sizeof(**arr) * 9


//* operator in *(arr+1) just changes the type of the pointer here
= arr + 5 * sizeof(int) + 9 * sizeof(int)
= arr + 14 * sizeof(int)

Now, C language follows row major ordering for arrays which means that when a multi dimensional array gets linearized in
memory the lower dimensions get arranged contiguously. For the 2D array arr[4][5] it’ll be
5 elements of arr[0][5] followed by 5 elements of arr[1][5] followed by 5 elements of arr[2][5] and so on.
So, the 14th element will be at row number ⌈14/5⌉ = 2 and column number 14%5 = 4, which is
arr[2][4] = 10 × 2 + 4 = 24.
More Read: https://gatecse.in/chapter-3-pointers/
References

 1 votes -- gatecse (62.6k points)

© Copyright GATE Overflow. Some rights reserved.


462 4 Programming and DS: Programming (108)

4.2.8 Arrays: GATE IT 2004 | Question: 58 top☝ ☛ https://gateoverflow.in/3701

 Ooption C:
look at the initial value of j, if j starts with 0, then double for loop will swap M[i][j] with M[j][i] and also M[j][i] and
M[i][j] so the matrix M will remain unchanged, so to avoid this double swapping we need to initialize j = i and swap only
upper triangular matrix with lower triangular matrix.
for(j = i; j < 4; ++j){
// code for swapping M[i][j] with M[j][i]
t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}

 45 votes -- Vikrant Singh (11.2k points)

4.2.9 Arrays: GATE IT 2008 | Question: 49 top☝ ☛ https://gateoverflow.in/3359

 Char a[6] = w o r l d \0
After the loop executes for the first time,
a[0] = a[5]
a[0] =`\0`
Next two more iterations of the loop till i < j condition becomes false, are not important for the output as the first position is
'\0';
printf(‘’%s’’, a);
printf function for format specifier '%s' prints the characters from the corresponding parameter (which should be an address)
until "\0" occurs. Here, first character at a is "\0" and hence it will print NOTHING.
So, option (B).
 33 votes -- Mitali (151 points)

4.2.10 Arrays: GATE IT 2008 | Question: 51 top☝ ☛ https://gateoverflow.in/3361

 Answer is (C) 3, 2
First 2 variable integer type declared named i and j
Then int type array a[8] declared and initialized.
a[0] = 1, a[1] = 2, a[2] = 3, a[3] = 4, a[4] = 5, a[5] = 6, a[6] = 7, a[7] = 8
Then for loop started
i = 0, i < 3 (true)
a[0] = a[0] + 1 = 1 + 1 = 2
i + + (outside for loop) , i + + (inside for loop);
i = 2, i < 3 (true)
a[2] = a[2] + 1 = 3 + 1 = 4
i + +, i + +(outside for loop) ,
i = 4, i < 3 (false) //Now come out of loop
i − −; (so i = 3 )
Now another for loop started where in loop integer type variable named i declared
Block Scope: A Block is a set of statements enclosed within left and right braces ({ and } respectively). Blocks may be
nested in C (a block may contain other blocks inside it). A variable declared in a block is accessible in the block and all inner
blocks of that block, but not accessible outside the block.
What if the inner block itself has one variable with the same name?
If an inner block declares a variable with the same name as the variable declared by the outer block, then the visibility of the
outer block variable ends at the point of declaration by inner block.
So here inner block int i has the scope in this block only and outer block int i visibility is not allowed in that block
j = 7, j > 4 (true)
int i = 7/2 = 3

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 463

a[3] = a[3] − 1 = 4 − 1 = 3
j = 6, j > 4 (true)
int i = 6/2 = 3
a[3] = a[3] − 1 = 3 − 1 = 2
j = 5, j > 4 (true)
int i = 5/2 = 2
a[2] = a[2] − 1 = 4 − 1 = 3
j = 4, j > 4 (false)
Now when the for loop ends its variable named i scope is also end and the outer block variable now visible. So, in printf
outer variable i is used.
So, the output would be: 3, 2.
 124 votes -- Kalpna Bhargav (2.5k points)

4.2.11 Arrays: GATE IT 2008 | Question: 52 top☝ ☛ https://gateoverflow.in/3362

 The correct answer is option (B).


first integer type two variables declared i and j
then an integer type 2 − d array a[2][3] is declared and initialized and 2 − d array b[3][2] is created but not initialized. i.e
address value address value
a[0]0[] 2000 a b[0][0] 3000 garbage value
a[0][1] 2001 b b[0][1] 3001 garbage value
a[0][2] 2002 c b[1][0] 3002 garbage value
a[1][0] 2003 d b[1][1] 3003 garbage value
a[1][1] 2004 e b[2][0] 3004 garbage value
a[1][2] 2005 f b[2][1] 3005 garbage value
now the char type pointer is declared and the base address of array b is put in it. so p = 3000
now the for loop is started where i is initialized to 0 ,so
i = 0 : i < 2 (true)
j = 0; j < 3 (true)
∗(3000 + 2 ∗ 0 + 0) = a[0][0] ⇒ ∗(3000) = a
j++
j = 1; j < 3 (true)
∗(3000 + 2 ∗ 1 + 0) = a[0][1] ⇒ ∗(3002) = b
j++
j = 2; j < 3 (true)
∗(3000 + 2 ∗ 2 + 0) = a[0][2] ⇒ ∗(3004) = c
j++
j = 3; j < 3 (false)
i++
i = 1 : i < 2 (true)
j = 0; j < 3 (true)
∗(3000 + 2 ∗ 0 + 1) = a[1][0] ⇒ ∗(3001) = d
j++
j = 1; j < 3 (true)
∗(3000 + 2 ∗ 1 + 1) = a[1][1] ⇒ ∗(3003) = e
j++
j = 2; j < 3 (true)
∗(3000 + 2 ∗ 2 + 1) = a[1][2] ⇒ ∗(3005) = f
j++

© Copyright GATE Overflow. Some rights reserved.


464 4 Programming and DS: Programming (108)

j = 3; j < 3 (false)
i++
now the values in array b is
b[0][0] 3000 a
b[0][1] 3001 d
b[1][0] 3002 b
b[1][1] 3003 e
b[2][0] 3004 c
b[2][1] 3005 f
Hence, the output will be ( B) choice.
Note:
*(p + 2*j + i)

p+ size of inner dimension ∗j + i, hence is same as p[j][i]. Hence with this statement we can identify that the code
is transposing the matrix a and storing in b using pointer p.
 47 votes -- Kalpna Bhargav (2.5k points)

4.3 Goto (2) top☝

4.3.1 Goto: GATE CSE 1989 | Question: 3-i top☝ ☛ https://gateoverflow.in/87095

An unrestricted use of the "go to" statement is harmful because of which of the following reason (s):

A. It makes it more difficult to verify programs.


B. It makes programs more inefficient.
C. It makes it more difficult to modify existing programs.
D. It results in the compiler generating longer machine code.

gate1989 normal programming goto

Answer ☟

4.3.2 Goto: GATE CSE 1994 | Question: 1.5 top☝ ☛ https://gateoverflow.in/2442

An unrestricted use of the " goto" statement is harmful because

A. it makes it more difficult to verify programs


B. it increases the running time of the programs
C. it increases the memory required for the programs
D. it results in the compiler generating longer machine code

gate1994 programming easy goto

Answer ☟

Answers: Goto

4.3.1 Goto: GATE CSE 1989 | Question: 3-i top☝ ☛ https://gateoverflow.in/87095

 Solution : A) It makes it more difficult to verify programs.


Proof of correctness : https://en.wikipedia.org/wiki/Goto#Criticism
(1st Paragraph, last 4 lines.)
Option B: goto has no role in making a program inefficient. Adding a "goto" introduces a branch instruction but assuming
same program logic this can never be avoided and even when replaced by a proper structural construct like for/while/if -- will
still have the branch instruction.
Option C: Actually using "goto" kind of makes it easy to modify an existing program as to make the control flow from say
line number 'x' to line number 'y', we can simply do a "goto". This is much harder to do in a proper structural way.
Option D: This is also false as goto introduces only a single "JUMP" instruction (machine code will be its equivalent;
OPCODE for JMP followed by the destination address) and equivalent structural constructs will have longer machine codes.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 465

References

 17 votes -- Siddharth Mahapatra (1.2k points)

4.3.2 Goto: GATE CSE 1994 | Question: 1.5 top☝ ☛ https://gateoverflow.in/2442

 Use of goto takes out the structural decomposition of the code and hence it becomes very difficult to verify or
debug the code. As far as performance or memory impact is concerned, goto has no effect on them.

Correct Answer: A
 37 votes -- Arjun Suresh (330k points)

4.4 Identify Function (4) top☝

4.4.1 Identify Function: GATE CSE 1995 | Question: 3 top☝ ☛ https://gateoverflow.in/2639

Consider the following high level programming segment. Give the contents of the memory locations for variables
W, X, Y and Z after the execution of the program segment. The values of the variables A and B are 5CH and 92H ,
respectively. Also indicate error conditions if any.
var
A, B, W, X, Y :unsigned byte;
Z :unsigned integer, (each integer is represented by two bytes)
begin
X :=A+B
Y :=abs(A-B);
W :=A-B
Z :=A*B
end;

gate1995 programming identify-function descriptive

Answer ☟

4.4.2 Identify Function: GATE CSE 1998 | Question: 2.13 top☝ ☛ https://gateoverflow.in/1685

What is the result of the following program?


program side-effect (input, output);
var x, result: integer;
function f (var x:integer):integer;
begin
x:x+1;f:=x;
end
begin
x:=5;
result:=f(x)*f(x);
writeln(result);
end

A. 5
B. 25
C. 36
D. 42

gate1998 programming normal identify-function

Answer ☟

4.4.3 Identify Function: GATE CSE 2017 Set 2 | Question: 43 top☝ ☛ https://gateoverflow.in/118388

Consider the following snippet of a C program. Assume that swap (&x, &y) exchanges the content of x and y:
int main () {
int array[] = {3, 5, 1, 4, 6, 2};
int done =0;
int i;
while (done==0) {
done =1;

© Copyright GATE Overflow. Some rights reserved.


466 4 Programming and DS: Programming (108)

for (i=0; i<=4; i++) {


if (array[i] < array[i+1]) {
swap(&array[i], &array[i+1]);
done=0;
}
}
for (i=5; i>=1; i--) {
if (array[i] > array[i-1]) {
swap(&array[i], &array[i-1]);
done =0;
}
}
}
printf(“%d”, array[3]);
}

The output of the program is _______

gate2017-cse-set2 programming algorithms numerical-answers identify-function

Answer ☟

4.4.4 Identify Function: GATE IT 2004 | Question: 15 top☝ ☛ https://gateoverflow.in/3656

Let x be an integer which can take a value of 0 or 1. The statement


if (x == 0) x = 1; else x = 0;

is equivalent to which one of the following ?

A. x = 1 + x;
B. x = 1 − x;
C. x = x − 1;
D. x = 1%x;

gate2004-it programming easy identify-function

Answer ☟

Answers: Identify Function

4.4.1 Identify Function: GATE CSE 1995 | Question: 3 top☝ ☛ https://gateoverflow.in/2639

 The maximum value that can be accommodated in an unsigned byte = 255 and unsigned int = 65535.

A and B are given in Hexadecimal.

A = 5CH = (92)10
B = 92H = (146)10
X = A + B = (238)10 = EEH
Y = abs(A − B) = (54)10 = 36H
W = A − B = (−54)10

Negative numbers represented in 2's complement form ⟹ −54 = 11001010 ( in 8-bit representations )

But W is unsigned, therefore it cannot look for the sign ⟹ W = 11001010 = CAH
Z = A ∗ B = (13432)10 = 3478H
 26 votes -- Ravi Ranjan (3k points)

4.4.2 Identify Function: GATE CSE 1998 | Question: 2.13 top☝ ☛ https://gateoverflow.in/1685

 Call by value: 36,


Call by reference: undefined behaviour for C/C++ but 42 for languages having ∗ as a sequence point.

f(x) ∗ f(x);

If the value of x is being modified inside the function (call by reference) we cannot be sure if this modified value or the old
value will be passed as argument for the second call to f(). This is because left and right operand of any arithmetic

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 467

expression in C/C++ can be evaluated in any order. For languages like Java, strict left-right order is maintained.
 18 votes -- Arjun Suresh (330k points)

4.4.3 Identify Function: GATE CSE 2017 Set 2 | Question: 43 top☝ ☛ https://gateoverflow.in/118388

 Well, the above program is sorting the array in descending order.


Initially, while loop starts execution by evaluating the iniatial condition

' while(done==0)

For the first time the first for loop will be executed completey, the content of array will be as follows :

5, 3, 4, 6, 2, 1

After the second for executed completey the content of array will be as follows:

6, 5, 3, 4, 2, 1

But the value variable done is still 0 so while loop will execute again,so now the content of array after executing the first for
loop will be 6, 5, 4, 3, 2, 1 and no change in second for loop but still the done variable is 0.

So, while loop execute again,now done variable is modified to 1 and there will be no change in done variable because inside
first and second for loop no if condition will satisfied .
Finally, the while condition is evaluted false and value of array[3] will be printed which is 3.
 54 votes -- Manoj Kumar (26.7k points)

4.4.4 Identify Function: GATE IT 2004 | Question: 15 top☝ ☛ https://gateoverflow.in/3656

 Firstly, our requirement is for x = 1 it makes ' 0' and for x = 0 it makes ' 1'
Let's consider options one by one:

A. x = 1 + x
For x = 1 , it gives 2 So, False

B. x = 1 − x
Here, B is correct, as
For x = 0 , it gives 1.
For x = 1 , it gives 0.

C. x = x − 1
For x = 0 , it gives −1. So, False

D. x = 1%x
For x = 0 , it gives 1%0 . I think it is undefined
Even if we consider x = x%1
for x = 0 ,it gives 0%1 = 0 But we require 1.

So, Option (B) is correct.


 31 votes -- Himanshu Agarwal (12.4k points)

4.5 Loop Invariants (8) top☝

4.5.1 Loop Invariants: GATE CSE 1987 | Question: 7a top☝ ☛ https://gateoverflow.in/82425

List the invariant assertions at points A, B, C, D and E in program given below:


Program division (input, output)
Const
dividend = 81;
divisor = 9;
Var remainder, quotient:interger

© Copyright GATE Overflow. Some rights reserved.


468 4 Programming and DS: Programming (108)

begin
(*(dividend >= 0) AND (divisor > 0)*)
remainder := dividend;
quotient := 9;
(*A*)
While (remainder >= 0) do
begin (*B*)
quotient := quotient + 1;
remainder := remainder - divisor;
(*C*)
end;
(*D*)
quotient := quotient - 1;
remainder := remainder + divisor;
(*E*)
end

gate1987 programming loop-invariants descriptive

Answer ☟

4.5.2 Loop Invariants: GATE CSE 1988 | Question: 6ii top☝ ☛ https://gateoverflow.in/94364

Below figure is the flow-chart corresponding to a program to calculate the gcd of two integers, M and N respectively,
(M, N > 0). Use assertions at the cut point C1 , C2 and C3 to prove that the flow-chart is correct.

gate1988 normal descriptive loop-invariants

Answer ☟

4.5.3 Loop Invariants: GATE CSE 1988 | Question: 8ii top☝ ☛ https://gateoverflow.in/94379

Consider the two program segments below:

a. for
i:=1 to f(x) by 1 do
S
end

b. i:=1;
While i<=f(x) do
S
i:=i+1
end

Under what conditions are these two programs equivalent? Treat S as any sequence of statements and f as a function.

gate1988 programming descriptive loop-invariants

Answer ☟

4.5.4 Loop Invariants: GATE CSE 1991 | Question: 1,vi top☝ ☛ https://gateoverflow.in/504

Consider the following PASCAL program segment:

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 469

if i mod 2 = 0 then
while i >= 0 do
begin
i := i div 2;
if i mod 2 < > 0 then i := i - 1;
else i := i – 2;
end;

An appropriate loop-invariant for the while-loop is ________

gate1991 programming loop-invariants normal fill-in-the-blanks

Answer ☟

4.5.5 Loop Invariants: GATE CSE 2004 | Question: 32 top☝ ☛ https://gateoverflow.in/1029

Consider the following program fragment for reversing the digits in a given integer to obtain a new integer.
Let n = d1 d2 … dm .
int n, rev;
rev = 0;
while(n > 0) {
rev = rev * 10 + n%10;
n = n/10;
}

The loop invariant condition at the end of the ith iteration is:

A. n = d1 d2 … dm−i and rev = dm dm−1 … dm−i+1


B. n = dm−i+1 … dm−1 dm or rev = dm−i … d2 d1
C. n ≠ rev
D. n = d1 d2 … dm or rev = dm … d2 d1

gate2004-cse programming loop-invariants normal

Answer ☟

4.5.6 Loop Invariants: GATE CSE 2015 Set 1 | Question: 33 top☝ ☛ https://gateoverflow.in/8276

Consider the following pseudo code, where x and y are positive integers.
begin
q := 0
r := x
while r ≥ y do
begin
r := r - y
q := q + 1
end
end

The post condition that needs to be satisfied after the program terminates is

A. {r = qx + y ∧ r < y}
B. {x = qy + r ∧ r < y}
C. {y = qx + r ∧ 0 < r < y}
D. {q + 1 < r − y ∧ y > 0}

gate2015-cse-set1 programming loop-invariants normal

Answer ☟

4.5.7 Loop Invariants: GATE CSE 2016 Set 2 | Question: 35 top☝ ☛ https://gateoverflow.in/39578

The following function computes X Y for positive integers X and Y .


int exp (int X, int Y) {
int res =1, a = X, b = Y;

while (b != 0) {
if (b % 2 == 0) {a = a * a; b = b/2; }
else {res = res * a; b = b - 1; }

© Copyright GATE Overflow. Some rights reserved.


470 4 Programming and DS: Programming (108)

}
return res;
}

Which one of the following conditions is TRUE before every iteration of the loop?

A. X Y = ab
B. (res ∗ a)Y = (res ∗ X)b
C. X Y = res ∗ ab
D. X Y = (res ∗ a)b

gate2016-cse-set2 programming loop-invariants normal

Answer ☟

4.5.8 Loop Invariants: GATE CSE 2017 Set 2 | Question: 37 top☝ ☛ https://gateoverflow.in/118381

Consider the C program fragment below which is meant to divide x by y using repeated subtractions. The variables x,
y, q and r are all unsigned int.
while (r >= y) {
r=r-y;
q=q+1;
}

Which of the following conditions on the variables x, y, q and r before the execution of the fragment will ensure that the loop
terminated in a state satisfying the condition x == (y ∗ q + r) ?

A. (q == r) && (r == 0)
B. (x > 0) && (r == x) && (y > 0)
C. (q == 0) && (r == x) && (y > 0)
D. (q == 0) && (y > 0)

gate2017-cse-set2 programming loop-invariants

Answer ☟

Answers: Loop Invariants

4.5.1 Loop Invariants: GATE CSE 1987 | Question: 7a top☝ ☛ https://gateoverflow.in/82425

A: remainder >= 0 and quotient = 9;

B: remainder >= 0 and quotient <= divident/divisor

C: quotient - 1 <= divident/divisor

D: remainder < 0 and quotient - 1 = ⌊ divident/divisor ⌋

E: divident = divisor * quotient + remainder

PS: To be fixed.
 6 votes -- Arjun Suresh (330k points)

4.5.2 Loop Invariants: GATE CSE 1988 | Question: 6ii top☝ ☛ https://gateoverflow.in/94364

Cond 3 : Evaluating condition where two integers are equal and thus GCD(x,x)=x Thus it is returning X itself.
Cond 2 : We are reducing the Greater integer among 2 by the smallest one which will ultimately reduce it by factor
of smaller integer.
Cond1: Provides updated value at other iteration and Original value at 1st iteration./
EX: M=9 N=6
L=9,K=6
Iteration 1 ::Cond 1 :(9! = 6)True --> (K>L)False --> L=3 -->Cond2::Cond1 (Updated value : L=3 K=6)
Iteration 2 ::Cond1 :(3!=6) True --> (K>L)True --> K=3--> Cond2:: Cond1(Updated Value L=3,K=3)
Iteration 3 ::Cond1 (3!=6) False Cond 3 :: Return K=3 Which is GCD(9,6)=3

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 471

 8 votes -- Akshay Saxena (8.3k points)

4.5.3 Loop Invariants: GATE CSE 1988 | Question: 8ii top☝ ☛ https://gateoverflow.in/94379

In both program segment if f(x) returns same value


 1 votes -- learner_geek (1.1k points)

4.5.4 Loop Invariants: GATE CSE 1991 | Question: 1,vi top☝ ☛ https://gateoverflow.in/504

 Loop invariant is some condition which holds at the end of each iteration of the loop. i.e. it is "invariant" => does
not vary (or change). It might change inside one iteration, but it will be true at the end of every iteration.
We often use loop invariants to prove that our algorithm works correctly.
In the given program, a loop invariant is:
i mod 2 = 0
i.e. i is even after every iteration.
One can verify this as follows:

Before the execution of first iteration the loop invariant is true, because of this line of code:

if i mod 2 = 0 then

In every iteration, we divide i by 2, so now i will be either odd or even.


If odd, we subtract 1 from i

if i mod 2 < > 0 then i := i - 1;

so it's now even.


otherwise, if even, we subtract 2 from i

else i := i – 2;

so, it remains even


So, at the end of every iteration i remains even.

https://stackoverflow.com/questions/3221577/what-is-a-loop-invariant
References

 22 votes -- Rishabh Gupta (12.5k points)

4.5.5 Loop Invariants: GATE CSE 2004 | Question: 32 top☝ ☛ https://gateoverflow.in/1029

 A loop invariant is something that hold at the start of a loop, across each iteration (inside an iteration it can change
but before the iteration ends original condition must be true) and at the end also. So, we can check for the
satisfiability of the condition at the loop header for start of the loop, for each iteration and also at the exit.

Here, in each iteration the right most digit of n, is moving to the right end of rev. So, answer is (A). i.e. the 2 conditions given
in (A) choice are true on entry to loop, after each iteration (not necessarily during an iteration), and at end of loop.
 32 votes -- Arjun Suresh (330k points)

4.5.6 Loop Invariants: GATE CSE 2015 Set 1 | Question: 33 top☝ ☛ https://gateoverflow.in/8276

 Correct Option: B
The loop terminates when r < y. So, r < y is one post condition.
In each iteration q is incremented by 1 and y is subtracted from r. Initial value of r is x. So, loop iterates x/y times and q
will be equal to x/y and r = x%y ⇒ x = qy + r;
 60 votes -- Arjun Suresh (330k points)

© Copyright GATE Overflow. Some rights reserved.


472 4 Programming and DS: Programming (108)

4.5.7 Loop Invariants: GATE CSE 2016 Set 2 | Question: 35 top☝ ☛ https://gateoverflow.in/39578

 Take X = 10, Y = 3
In that case,
Before
−−−−−−Iteration
−−−−−−−1: −
res = 1, a = 10, b = 3
All options are satisfied here.

−Iteration
−−−−−−−1: −
while(b! = 0) ⟹ 3! = 0 ✓
if(b%2 == 0) ⟹ 3%2 == 0 ×
else
res = res ∗ a ⟹ res = 1 ∗ 10 = 10

b=b−1 ⟹ b=3−1=2
Before
−−−−−−Iteration
−−−−−−−2: −
res = 10, a = 10, b = 2
option A : X Y = ab ⟹ 103 = 102 ×
option B : (res ∗ a)Y = (res ∗ X)b ⟹ (10 ∗ 10)3 = (10 ∗ 10)2 ×
option C : X Y = res ∗ ab ⟹ 103 = 10 ∗ 102 ✓
option D : X Y = (res ∗ a)b ⟹ 103 = (10 ∗ 10)2 ×
Lets see one more iteration to verify option C.

−Iteration
−−−−−−−2: −
res = 10, a = 10, b = 2

while(b! = 0) ⟹ 2! = 0 ✓
if(b%2 == 0) ⟹ 2%2 == 0 ✓
a=a∗a
= 10 ∗ 10 = 100
b
b=
2
2
= =1
2
Before
−−−−−−Iteration
−−−−−−−3:−
res = 10, a = 100, b = 1
Option C : X Y = res ∗ ab ⟹ 103 = 10 ∗ 1001 = 103 ✓
Option C is answer
 64 votes -- Akash Kanase (36k points)

4.5.8 Loop Invariants: GATE CSE 2017 Set 2 | Question: 37 top☝ ☛ https://gateoverflow.in/118381

 Here, x == (y ∗ q + r) says q = quotient and r = remainder.

To divide a number with repeated subtraction, quotient should be initialized to 0 and should be incremented for each
subtraction.

Initially q = 0 ⇒ r = x .

∴ Initial conditions should be C] (q == 0) && (r == x) && (y > 0).


 40 votes -- Kantikumar (3.4k points)

4.6 Parameter Passing (12) top☝

4.6.1 Parameter Passing: GATE CSE 1992 | Question: 10b top☝ ☛ https://gateoverflow.in/43584

Show the activation records and the display structure just after the procedures called at lines marked x and y have
started their execution. Be sure to indicate which of the two procedures named A you are referring to.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 473

Program Test;
Procedure A;
Procedure B;
Procedure A;
begin
……
end A;
begin
y: A;
end B;
begin
B;
end A;

begin
x: A;
end Test

gate1992 parameter-passing programming runtime-environments normal descriptive

Answer ☟

4.6.2 Parameter Passing: GATE CSE 1994 | Question: 1.20 top☝ ☛ https://gateoverflow.in/305

In which of the following cases is it possible to obtain different results for call-by-reference and call-by-name
parameter passing methods?

A. Passing a constant value as a parameter


B. Passing the address of an array as a parameter
C. Passing an array element as a parameter
D. Passing an array

gate1994 programming parameter-passing easy

Answer ☟

4.6.3 Parameter Passing: GATE CSE 2001 | Question: 2.17 | UGCNET-AUG2016-III: 21 top☝

☛ https://gateoverflow.in/735
What is printed by the print statements in the program P 1 assuming call by reference parameter
passing?
Program P1()
{
x = 10;
y = 3;
func1(y,x,x);
print x;
print y;
}

func1(x,y,z)
{
y = y + 4;
z = x + y + z
}

A. 10, 3
B. 31, 3
C. 27, 7
D. None of the above

gate2001-cse programming compiler-design parameter-passing normal runtime-environments ugcnetaug2016iii

Answer ☟

4.6.4 Parameter Passing: GATE CSE 2003 | Question: 73 top☝ ☛ https://gateoverflow.in/960

The following program fragment is written in a programming language that allows global variables and does not allow
nested declarations of functions.
global int i=100, j=5;
void P(x) {
int i=10;
print(x+10);

© Copyright GATE Overflow. Some rights reserved.


474 4 Programming and DS: Programming (108)

i=200;
j=20;
print (x);
}
main() {P(i+j);}

If the programming language uses static scoping and call by need parameter passing mechanism, the values printed by the
above program are:

A. 115, 220
B. 25, 220
C. 25, 15
D. 115, 105

gate2003-cse compiler-design normal runtime-environments parameter-passing

Answer ☟

4.6.5 Parameter Passing: GATE CSE 2008 | Question: 60 top☝ ☛ https://gateoverflow.in/483

What is printed by the following C program?


int f(int x, int *py, int **ppz)
{
int y, z;
**ppz += 1; z = **ppz; // corrected z = *ppz; to z = **ppz;
*py += 2; y = *py;
x += 3;
return x+y+z;
}

void main()
{
int c, *b, **a;
c = 4; b = &c; a = &b;
printf("%d", f(c, b, a));

A. 18
B. 19
C. 21
D. 22

gate2008-cse programming programming-in-c normal parameter-passing

Answer ☟

4.6.6 Parameter Passing: GATE CSE 2010 | Question: 11 top☝ ☛ https://gateoverflow.in/2184

What does the following program print?


#include<stdio.h>

void f(int *p, int *q) {


p=q;
*p=2;
}

int i=0, j=1;

int main() {
f(&i, &j);
printf("%d %d\n", i,j);
return 0;
}

A. 22
B. 21
C. 01
D. 02

gate2010-cse programming programming-in-c easy parameter-passing

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 475

Answer ☟

4.6.7 Parameter Passing: GATE CSE 2013 | Question: 42 top☝ ☛ https://gateoverflow.in/60

What is the return value of f(p, p), if the value of p is initialized to 5 before the call? Note that the first parameter is
passed by reference, whereas the second parameter is passed by value.

int f (int &x, int c) {


c = c - 1;
if (c==0) return 1;
x = x + 1;
return f(x,c) * x;
}

gate2013-cse compiler-design normal marks-to-all numerical-answers parameter-passing runtime-environments

Answer ☟

4.6.8 Parameter Passing: GATE CSE 2016 Set 1 | Question: 15 top☝ ☛ https://gateoverflow.in/39642

Consider the following C program.


# include <stdio.h>
void mystery (int *ptra, int *ptrb) {
int *temp;
temp = ptrb;
ptrb =ptra;
ptra = temp;
}
int main () {
int a = 2016, b=0, c= 4, d = 42;
mystery (&a, &b);
if (a < c)
mystery (&c, &a);
mystery (&a, &d);
printf("%d\n", a);
}

The output of the program is _________.

gate2016-cse-set1 programming-in-c easy numerical-answers parameter-passing

Answer ☟

4.6.9 Parameter Passing: GATE CSE 2016 Set 2 | Question: 12 top☝ ☛ https://gateoverflow.in/39565

The value printed by the following program is _______.


void f (int * p, int m) {
m = m + 5;
*p = *p + m;
return;
}
void main () {
int i=5, j=10;

f (&i, j);
printf ("%d", i+j);
}

gate2016-cse-set2 programming-in-c normal numerical-answers parameter-passing

Answer ☟

4.6.10 Parameter Passing: GATE CSE 2018 | Question: 29 top☝ ☛ https://gateoverflow.in/204103

#include<stdio.h>
void fun1(char* s1, char* s2){
char* temp;
temp = s1;
s1 = s2;
s2 = temp;
}
void fun2(char** s1, char** s2){

© Copyright GATE Overflow. Some rights reserved.


476 4 Programming and DS: Programming (108)

char* temp;
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
int main(){
char *str1="Hi", *str2 = "Bye";
fun1(str1, str2); printf("%s %s", str1, str2);
fun2(&str1, &str2); printf("%s %s", str1, str2);
return 0;
}

The output of the program above is:

A. Hi Bye Bye Hi
B. Hi Bye Hi Bye
C. Bye Hi Hi Bye
D. Bye Hi Bye Hi

gate2018-cse programming-in-c pointers parameter-passing normal programming

Answer ☟

4.6.11 Parameter Passing: GATE IT 2006 | Question: 50 top☝ ☛ https://gateoverflow.in/3593

Which one of the choices given below would be printed when the following program is executed?
#include <stdio.h>
void swap (int *x, int *y)
{
static int *temp;
temp = x;
x = y;
y = temp;
}
void printab ()
{
static int i, a = -3, b = -6;
i = 0;
while (i <= 4)
{
if ((i++)%2 == 1) continue;
a = a + i;
b = b + i;
}
swap (&a, &b);
printf("a = %d, b = %d\n", a, b);
}
main()
{
printab();
printab();
}

A. a = 0, b = 3
a = 0, b = 3
B. a = 3, b = 0
a = 12, b = 9
C. a = 3, b = 6
a = 3, b = 6
D. a = 6, b = 3
a = 15, b = 12

gate2006-it programming programming-in-c normal parameter-passing

Answer ☟

4.6.12 Parameter Passing: GATE IT 2008 | Question: 50 top☝ ☛ https://gateoverflow.in/3360

Consider the C program below. What does it print?


# include <stdio.h>
# define swapl (a, b) tmp = a; a = b; b = tmp
void swap2 ( int a, int b)
{

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 477

int tmp;
tmp = a; a = b; b = tmp;
}
void swap3 (int*a, int*b)
{
int tmp;
tmp = *a; *a = *b; *b = tmp;
}
int main ()
{
int num1 = 5, num2 = 4, tmp;
if (num1 < num2) {swap1 (num1, num2);}
if (num1 < num2) {swap2 (num1 + 1, num2);}
if (num1 > = num2) {swap3 (&num1, &num2);}
printf ("%d, %d", num1, num2);
}

A. 5, 5
B. 5, 4
C. 4, 5
D. 4, 4

gate2008-it programming programming-in-c normal parameter-passing

Answer ☟

Answers: Parameter Passing

4.6.1 Parameter Passing: GATE CSE 1992 | Question: 10b top☝ ☛ https://gateoverflow.in/43584

Initially activation stack is empty.


I have used A1, A2, B1, B2 for understanding purpose, which refers to A and B respectively.
Test()
{//Scope of Test begins. In activation record Test is added
A()
{
//Scope of A begins.
// Activation stack: Test---> A
B1()
{
//Scope of B1 begins.
// Activation stack: Test---> A--->B1
A1()
{
//Scope of A1 begins
// Activation stack: Test---> A--->B1--->A1
}//Scope of A1 ends
//Activation record before y pt of execution Test---> A--->B1

At y point of execution
A2()
{
//New Activation record of A created
//Activation stack: Test---> A--->B1--->A2
}//Scope of A2 ends
}//End of scope B

//Activation stack: Test---> A


B2()
{
//Activation of B2 added
//Activation stack: Test---> A--->B2
}
}//End of scope A
//Activation Record before x point of execution: Test

At x point of execution
A()
{
//Activation Record: Test--->A
}
}//End of scope Test

 0 votes -- SatyamK (225 points)

© Copyright GATE Overflow. Some rights reserved.


478 4 Programming and DS: Programming (108)

4.6.2 Parameter Passing: GATE CSE 1994 | Question: 1.20 top☝ ☛ https://gateoverflow.in/305

 Correct Option: C
Passing an array element as a parameter is the answer.

Consider this function call


{
....
a[] = {0,1,2,3,4};
i = 0;
fun(a[i]);
print a[0];
}

fun(int x)
{
int i = 1;
x = 8;
}

Output:

call-by-reference: 8
call-by-name: 0

In Call-by-name, each occurrence of the formal parameter is replaced by the actual argument text. So, the function fun will
be executed like:
{
int i = 1;
a[i] = 8; //a[1] is changed to 8 and not a[0]
}

A very good read: http://courses.cs.washington.edu/courses/cse341/03wi/imperative/parameters.html


 34 votes -- Arjun Suresh (330k points)

4.6.3 Parameter Passing: GATE CSE 2001 | Question: 2.17 | UGCNET-AUG2016-III: 21 top☝

☛ https://gateoverflow.in/735
 Answer is B.

Here, variable x of func1 points to address of variable y.

and variables y and z of func1 points to address of variable x.

Therefore, y = y + 4 ⟹ y = 10 + 4 = 14

and z = x + y + z ⟹ z = 14 + 14 + 3 = 31

z will be stored back in x. Hence, x = 31 and y will remain as it is. (y = 3)

Answer is 31, 3
 27 votes -- jayendra (6.7k points)

4.6.4 Parameter Passing: GATE CSE 2003 | Question: 73 top☝ ☛ https://gateoverflow.in/960

 Answer : D
First refer the following question on Call-by-name parameter passing technique then solve this question.
https://gateoverflow.in/43575/gate2003-74?show=338119#a338119
Call by Name vs. Call by Need :
Assume X is the formal and e the corresponding actual expression.
Call-by-Name :
1. Delays evaluation of arguments past call until a reference to the formal.
2. Re-evaluates argument e on each reference to X in environment of caller.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 479

3. No local variable X is allocated


Call-by-Need :
1. Delays evaluation of arguments past call until a reference to the formal.
2. Evaluates e on 1st reference in environment of caller & loads local variable X; no re-evaluation: subsequent references
use local X

Since "Call by need" parameter passing technique, it is almost same as Call-by-name But the difference is that Actual
argument is evaluated only once(on the first reference) and then that value is saved and re-used on further references But the
actual argument is Not re-evaluated.
Caller function's Actual argument contains variable i which clashes with called function P's local variable i, hence, we
rename called function P's local variable i and change it to i′ .
global int i=100, j=5;
void P(x) {
int i'=10; // this i' refers to the local variable i' in function P.
print(x+10); // this is first reference of x, so here, x= i+j, and these i,j refer to i,j in the caller functio
i'=200; // this i' refers to the local variable i' in function P.
j=20; // this j refers to j in the caller function i.e. main function's environment
print (x); // this x is second reference, so, we do not replace it with i+j because in call by need, we do not
}
main() {
P(i+j);
}

In case of Static scoping : 115, 105


In case of Dynamic scoping : 115, 105
Note that there are no local variable i, j in main function, so, when we say that i, j refer to the i, j in main's environment , we
mean that If i, j were accessed/updated in main function then depending on the scoping, which i, j would they refer.
Here, in this question, in both static and dynamic scoping case, i, j will refer to the Global variables.
And in function P, in the 4th statement (i.e. j = 20), the Global variable j will be updated.
References

 18 votes -- Deepak Poonia (23.3k points)

4.6.5 Parameter Passing: GATE CSE 2008 | Question: 60 top☝ ☛ https://gateoverflow.in/483

Return x + y + z = return 7 + 7 + 5 = return 19


So, option B = 19 is correct.
 42 votes -- Amar Vashishth (25.2k points)

4.6.6 Parameter Passing: GATE CSE 2010 | Question: 11 top☝ ☛ https://gateoverflow.in/2184


p=q; // now p and q are pointing to same address i.e. address of j
*p=2;// value of j will be updated to 2

Hence, answer is (D) 0 2


 41 votes -- Manu Thakur (34.1k points)

© Copyright GATE Overflow. Some rights reserved.


480 4 Programming and DS: Programming (108)

4.6.7 Parameter Passing: GATE CSE 2013 | Question: 42 top☝ ☛ https://gateoverflow.in/60

 In GATE 2013 marks were given to all as the same code in C/C++ produces undefined behavior. This is because ∗
is not a sequence point in C/C++. The correct code must replace:
return f(x,c) * x;
with

res = f(x,c); // ';' forms a sequence point


//and all side-effects are guaranteed to be completed here
//-- updation of the x parameter inside f is guaranteed
//to be reflected in the caller from the next point onwards.
return res * x;

In this code, there will be 4 recursive calls with parameters (6, 4), (7, 3), (8, 2) and (9, 1). The last call returns 1. But due to
pass by reference, x in all the previous functions is now 9. Hence, the value returned by f(p, p) will be
9 ∗ 9 ∗ 9 ∗ 9 ∗ 1 = 6561 .
Good Read:

http://stackoverflow.com/questions/41775973/is-this-undefined-behaviour-in-c-if-not-predict-the-output-logically
https://gateoverflow.in/108445/c-programming?show=108582#a108582

References

 78 votes -- Arjun Suresh (330k points)

4.6.8 Parameter Passing: GATE CSE 2016 Set 1 | Question: 15 top☝ ☛ https://gateoverflow.in/39642

 The mystery about mystery function is it does not affect values in main. As in C , parameters are passed by value-
even if they are pointer. So, here the pointer values are exchanged within the function only. (we can use ∗ operator to
exchange the values at the location of the pointers and this will affect the values in main).

So, NO CHANGES in a, b, c, d.
And ANSWER is 2016
 74 votes -- Abhilash Panicker (7.6k points)

4.6.9 Parameter Passing: GATE CSE 2016 Set 2 | Question: 12 top☝ ☛ https://gateoverflow.in/39565

 i is called by reference and j is called by value.

So, in function f() only value of i might change,


Now, in function f(∗p, m)
∗p is pointing to i
Thus ∗p is 5.
m is 10 because of call by value of j.

1. m = 10 + 5 hence m = 15
2. ∗p = 5 + 15 hence ∗p = 20 , that is, value of variable i is now 20
3. returns nothing

Now, back to main


i = 20 and j is as it is 10

Hence, output of printf will be i + j = 20 + 10 = 30.


 41 votes -- Shashank Chavan (2.4k points)

4.6.10 Parameter Passing: GATE CSE 2018 | Question: 29 top☝ ☛ https://gateoverflow.in/204103


func1(char* s1, char* s2){
char* temp;
temp = s1;

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 481

s1 = s2;
s2 = temp;
}

Everything is local here. So, once function completes its execution all modification go in vain.
func2(char** s1, char** s2){
char* temp
temp = *s1
*s1 = *s2
*s2 = temp
}

This will retain modification and swap pointers of string.


So output would be Hi Bye Bye Hi
Correct Answer: A
 32 votes -- Digvijay (44.9k points)

4.6.11 Parameter Passing: GATE IT 2006 | Question: 50 top☝ ☛ https://gateoverflow.in/3593

 First of all, the swap function just swaps the pointers inside the function and has no effect on the variables being
passed.
Inside printab, a and b are added odd integers from 1-5, i.e., 1 + 3 + 5 = 9 . So, in first call to printab, a = −3 + 9 = 6
and b = −6 + 9 = 3 .
Static variables have one memory throughout program run (initialized during program start) and they keep their values across
function calls. So, during second call to printab, a = 6 + 9 = 15 , b = 3 + 9 = 12 .
Hence, (D) is choice.
 72 votes -- Arjun Suresh (330k points)

4.6.12 Parameter Passing: GATE IT 2008 | Question: 50 top☝ ☛ https://gateoverflow.in/3360

 Answer is C.
Only:
if (num1 > = num2) {swap3 (&num1, &num2);}

Statement works, which in turn swaps num1 and num2.


 27 votes -- Rajarshi Sarkar (27.8k points)

4.7 Pointers (9) top☝

4.7.1 Pointers: GATE CSE 2000 | Question: 1.12 top☝ ☛ https://gateoverflow.in/635

The most appropriate matching for the following pairs

X: m = malloc(5); m = NULL; 1 : using dangling pointers


Y : free(n); n -> value = 5; 2: using uninitialized pointers
Z: char *p , *p = ‘a’ ; 3: lost memory

is:

A. X−1 Y −3 Z −2
B. X−2 Y −1 Z −3
C. X−3 Y −2 Z −1
D. X−3 Y −1 Z −2

gate2000-cse programming programming-in-c normal pointers

Answer ☟

4.7.2 Pointers: GATE CSE 2001 | Question: 2.18 top☝ ☛ https://gateoverflow.in/736

Consider the following three C functions:


[P 1]

© Copyright GATE Overflow. Some rights reserved.


482 4 Programming and DS: Programming (108)

int *g(void)
{
int x = 10;
return (&x);
}

[P 2]
int *g(void)
{
int *px;
*px = 10;
return px;
}

[P 3]
int *g(void)
{
int *px;
px = (int*) malloc (sizeof(int));
*px = 10;
return px;
}

Which of the above three functions are likely to cause problems with pointers?

A. Only P3
B. Only P1 and P3
C. Only P1 and P2
D. P1, P2 and P3

gate2001-cse programming programming-in-c normal pointers

Answer ☟

4.7.3 Pointers: GATE CSE 2003 | Question: 2 top☝ ☛ https://gateoverflow.in/893

Assume the following C variable declaration:


int *A[10], B[10][10];

Of the following expressions:

I. A[2]
II. A[2][3]
III. B[1]
IV. B[2][3]

which will not give compile-time errors if used as left hand sides of assignment statements in a C program?

A. I, II, and IV only


B. II, III, and IV only
C. II and IV only
D. IV only

gate2003-cse programming programming-in-c easy pointers

Answer ☟

4.7.4 Pointers: GATE CSE 2003 | Question: 89 top☝ ☛ https://gateoverflow.in/972

Consider the C program shown below:


#include<stdio.h>
#define print(x) printf("%d", x)

int x;
void Q(int z)
{
z+=x;
print(z);
}

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 483

void P(int *y)


{
int x = *y + 2;
Q(x);
*y = x - 1;
print(x);
}
main(void) {
x = 5;
P(&x);
print(x);
}

The output of this program is:

A. 12 7 6
B. 22 12 11
C. 14 6 6
D. 766

gate2003-cse programming programming-in-c normal pointers

Answer ☟

4.7.5 Pointers: GATE CSE 2006 | Question: 57 top☝ ☛ https://gateoverflow.in/1835

Consider this C code to swap two integers and these five statements: the code
void swap (int *px, int *py)
{
*px = *px - *py;
*py = *px + *py;
*px = *py - *px;
}

S1: will generate a compilation error


S2: may generate a segmentation fault at runtime depending on the arguments passed
S3: correctly implements the swap procedure for all input pointers referring to integers stored in memory locations accessible
to the process
S4: implements the swap procedure correctly for some but not all valid input pointers
S5: may add or subtract integers and pointers

A. S1
B. S2 and S3
C. S2 and S4
D. S2 and S5

gate2006-cse programming programming-in-c normal pointers

Answer ☟

4.7.6 Pointers: GATE CSE 2014 Set 1 | Question: 10 top☝ ☛ https://gateoverflow.in/1770

Consider the following program in C language:


#include <stdio.h>

main()
{
int i;
int*pi = &i;

scanf("%d",pi);
printf("%d\n", i+5);
}

Which one of the following statements is TRUE?

A. Compilation fails.
B. Execution results in a run-time error.
C. On execution, the value printed is 5 more than the address of variable i.
D. On execution, the value printed is 5 more than the integer value entered.

© Copyright GATE Overflow. Some rights reserved.


484 4 Programming and DS: Programming (108)

gate2014-cse-set1 programming programming-in-c easy pointers

Answer ☟

4.7.7 Pointers: GATE CSE 2015 Set 3 | Question: 26 top☝ ☛ https://gateoverflow.in/8478

Consider the following C program


#include<stdio.h>
int main() {
static int a[] = {10, 20, 30, 40, 50};
static int *p[] = {a, a+3, a+4, a+1, a+2};
int **ptr = p;
ptr++;
printf("%d%d", ptr-p, **ptr);

The output of the program is _______.

gate2015-cse-set3 programming programming-in-c normal numerical-answers pointers

Answer ☟

4.7.8 Pointers: GATE CSE 2017 Set 1 | Question: 13 top☝ ☛ https://gateoverflow.in/118293

Consider the following C code:


#include<stdio.h>
int *assignval (int *x, int val) {
*x = val;
return x;
}

void main () {
int *x = malloc(sizeof(int));
if (NULL == x) return;
x = assignval (x,0);
if (x) {
x = (int *)malloc(sizeof(int));
if (NULL == x) return;
x = assignval (x,10);
}
printf("%d\n", *x);
free(x);
}

The code suffers from which one of the following problems:

A. compiler error as the return of malloc is not typecast appropriately.


B. compiler error because the comparison should be made as x == NULL and not as shown.
C. compiles successfully but execution may result in dangling pointer.
D. compiles successfully but execution may result in memory leak.

gate2017-cse-set1 programming-in-c programming pointers

Answer ☟

4.7.9 Pointers: GATE CSE 2021 Set 2 | Question: 35 top☝ ☛ https://gateoverflow.in/357505

Consider the following ANSI C program:


#include <stdio.h>
#include <stdlib.h>
struct Node{
int value;
struct Node *next;};
int main( ) {
struct Node *boxE, *head, *boxN; int index=0;
boxE=head= (struct Node *) malloc(sizeof(struct Node));
head → value = index;
for (index =1; index<=3; index++){
boxN = (struct Node *) malloc (sizeof(struct Node));
boxE → next = boxN;
boxN → value = index;
boxE = boxN; }

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 485

for (index=0; index<=3; index++) {


printf(“Value at index %d is %d\n”, index, head → value);
head = head → next;
printf(“Value at index %d is %d\n”, index+1, head → value); } }

Which one of the following statements below is correct about the program?

A. Upon execution, the program creates a linked-list of five nodes


B. Upon execution, the program goes into an infinite loop
C. It has a missing return which will be reported as an error by the compiler
D. It dereferences an uninitialized pointer that may result in a run-time error

gate2021-cse-set2 programming-in-c normal pointers

Answer ☟

Answers: Pointers

4.7.1 Pointers: GATE CSE 2000 | Question: 1.12 top☝ ☛ https://gateoverflow.in/635

 Answer is (D).

X : m = NULL ; makes the pointer m point to NULL . But the memory created using malloc is still there and but cannot
be used as we don't have a link to it. Hence, lost memory

Y : n is freed and so pointer n is now pointing to an invalid memory making it a Dangling pointer.

Z : p is not initialized. p = malloc(sizeof(char)); should have been used before assigning ' a' to ∗p.
 72 votes -- Aditi Dan (4k points)

4.7.2 Pointers: GATE CSE 2001 | Question: 2.18 top☝ ☛ https://gateoverflow.in/736

 [P 1] may cause an error because function is returning the address of locally declared variable.

[P 2] will cause a problem because px is an int pointer that is not assigned with any address and we are doing dereferencing.

[P 3] will work because memory in bytes of size of int will be reserved and its address will be stored in px that can be further
use, once function execution completes, this m/m will still exist in Heap until we free it using free() function.

Hence, answer is (C).


 83 votes -- Manu Thakur (34.1k points)

4.7.3 Pointers: GATE CSE 2003 | Question: 2 top☝ ☛ https://gateoverflow.in/893

 A is an array of pointers to int, and B is a 2-D array.

A[2] = can take a pointer


A[2][3] = can take an int
B[1] = B[1] is the base address of the array and it cannot be changed as the array in C is a constant pointer.
B[2][3] = can take an integer

So, (A) is the answer.


 79 votes -- Arjun Suresh (330k points)

4.7.4 Pointers: GATE CSE 2003 | Question: 89 top☝ ☛ https://gateoverflow.in/972


main: x = 5; //Global x becomes 5

P: int x = *y + 2; //local x in P becomes 5+2 = 7

Q: z+=x; //local z in Q becomes 7 + 5 = 12

Q: print(z); //prints 12

© Copyright GATE Overflow. Some rights reserved.


486 4 Programming and DS: Programming (108)

P: *y = x - 1;
//content of address of local variable y
(same as global variable x) becomes 7 - 1 = 6

P: print(x); //prints local variable x in P = 7

main: print(x); //prints the global variable x = 6

Correct Answer: A
 44 votes -- Arjun Suresh (330k points)

4.7.5 Pointers: GATE CSE 2006 | Question: 57 top☝ ☛ https://gateoverflow.in/1835

 S1 is false.

S2 is true, depending on the argument passed it may generate segmentation fault.

S3 is false because implementation is having some problem. Let x = 3 and I want to implement SWAP [x, x] . Now ans
would be 0 but that must be x. Problem is because we are not checking whether both pointer are pointing the same address or
different So, S4 is true.

S5 is obviously false so, option ( C) is right.


 73 votes -- Kalpna Bhargav (2.5k points)

4.7.6 Pointers: GATE CSE 2014 Set 1 | Question: 10 top☝ ☛ https://gateoverflow.in/1770


int i; //i is declared
int*pi = &i; //pi is a pointer variable
//and is assigned the address of i

scanf("%d",pi); //i is overwritten with the value


//we provided because pi is pointing to i earlier

printf("%d\n", i+5) //it will print the value stored in i+5

input=3; output=8
Option D is answer.
 43 votes -- Bhagirathi Nayak (11.7k points)

4.7.7 Pointers: GATE CSE 2015 Set 3 | Question: 26 top☝ ☛ https://gateoverflow.in/8478


static int a[] = {10, 20, 30, 40, 50};
static int *p[] = {a, a+3, a+4, a+1, a+2};
int **ptr = p;

ptr++;

ptr-p = address of ptr−address of p = 1


© Copyright GATE Overflow. Some rights reserved.
4 Programming and DS: Programming (108) 487

ptr-p = addresssizeof(*ptr))
of ptr−address of p
=1
**ptr = p[2] = *(a+3) = 40
printf("%d%d", ptr-p, **ptr); // 140

 49 votes -- Salman (701 points)

4.7.8 Pointers: GATE CSE 2017 Set 1 | Question: 13 top☝ ☛ https://gateoverflow.in/118293

 Answer is D.

Option A: In C++ we need to do typecasting. C does automatic implicit typecasting.


See the screenshot for C & C++ compilers below. C compiler is working fine but C++ compiler is giving error.

Option B: Null means address 0. if (a == 0) if (0 == a) There is no difference.

Option C: Do it step by step, always x is pointing to a valid memory location. Dangling Pointer means if it points to a
memory location which is deleted(freed). So no dangling pointer. http://www.geeksforgeeks.org/dangling-void-null-wild-
pointers/

Option D: x will loss the previous address it was pointing to. So it will result in memory
leak. http://www.geeksforgeeks.org/what-is-memory-leak-how-can-we-avoid/

Proof for Option A:

C Compiler:

References

 67 votes -- Ahwan Mishra (10.2k points)

4.7.9 Pointers: GATE CSE 2021 Set 2 | Question: 35 top☝ ☛ https://gateoverflow.in/357505

 Lets see the first for loop:

for (index =1; index<=3; index++){


boxN = (struct Node *) malloc (sizeof(struct Node));
boxE -> next = boxN;
boxN -> value = index;
boxE = boxN; }

After this we get a linked list of size 4 with head pointing to its beginning, and boxE and boxN pointing to the last node and
the next pointer of the last node being uninitialized.
Now the second for loop will do printing as follows until the second printf of the final iteration.

Value at index 0 is 0
Value at index 1 is 1
Value at index 1 is 1
Value at index 2 is 2
Value at index 2 is 2
Value at index 3 is 3
Value at index 3 is 3

After this, the head pointer being uninitialized will be having random content which gets treated as an address. So, when
head -> value happens it is basically reading data from uninitialized memory location and so can result (not saying will
result because by chance the uninitialized memory can be a valid location) in runtime error.
To correct the error, we just have to add an extra line of code as given below:
for (index =1; index<=3; index++){

© Copyright GATE Overflow. Some rights reserved.


488 4 Programming and DS: Programming (108)

boxN = (struct Node *) malloc (sizeof(struct Node));


boxE -> next = boxN;
boxN -> value= index;
boxN-> next = NULL;
boxE = boxN; }

Correct option: D
 1 votes -- Arjun Suresh (330k points)

4.8 Programming Constructs (1) top☝

4.8.1 Programming Constructs: GATE CSE 1999 | Question: 2.5 top☝ ☛ https://gateoverflow.in/1483

Given the programming constructs

i. assignment
ii. for loops where the loop parameter cannot be changed within the loop
iii. if-then-else
iv. forward go to
v. arbitrary go to
vi. non-recursive procedure call
vii. recursive procedure/function call
viii. repeat loop,

which constructs will you not include in a programming language such that it should be possible to program the terminates
(i.e., halting) function in the same programming language

A. (ii), (iii), (iv)


B. (v), (vii), (viii)
C. (vi), (vii), (viii)
D. (iii), (vii), (viii)

gate1999 programming normal programming-constructs

Answer ☟

Answers: Programming Constructs

4.8.1 Programming Constructs: GATE CSE 1999 | Question: 2.5 top☝ ☛ https://gateoverflow.in/1483

 This question is actually asking about the halting problem of Turing machines. Or in other words which of the
constructs are needed to make a programming language Turing complete – when it becomes Turing complete, halting
problem becomes undecidable for it.
To start with if we only have a linear sequence of instructions it is guaranteed to terminate because we only have a finite
number of instructions to execute and individual instructions can be assumed to finish within a finite time. This is similar to
deciding if a TM halts within a finite number of steps or not which is decidable.
The problem (of deciding whether a program halts or not) comes when there is a loop. Again, not all loops are a problem as
shown below.
int n = 100;
for(int i = 0; i < n; i++)
{
...
}

Consider the above loop code. We can unroll the loop and repeat the loop body 100 times and what we get is a linear
sequence of instructions. So, the above loop does not affect the decision of halting.
Well, in the above paragraph I did not specify one crucial requirement for unrolling the loop. Assume we have a statement
like
n = pow(n,x;)

where x is any program variable. Now, n is changing and so is the bound of the loop and we do not know how many times
we have to unroll the loop. (This is similar to a Turing machine tape changing direction from right to left). Does this change
make the halting decision undecidable now? “YES” it does. Because now whatever a Turing machine can do we can do in
this programming language – Turing complete. So, if we can decide halting problem for this programming language we are
indirectly solving the halting problem of Turing machines – which is known to be unsolvable.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 489

So now coming to the given constructs

1. assignment ✓
2. for loops where the loop parameter cannot be changed within the loop ✓
As described above this just translated to a finite number of sequential instructions when unrolled. Some people might be
confused with loops like
int n = 0;
for(int i = 1; i > n; )
{

Here, if the loop body is not touching either i or n, the loop never terminates. But this decision (that it never terminates)
can be decided easily by a written program (analyzing this is decidable and you can think of a C code to do it and
equivalently we can have a Turing machine to decide this). So, the above loop even though being non-halting does not
make the “halting decision” undecidable.
3. if-then-else ✓
This just reduces one path (a set of instructions) from the linear sequence of instructions and hence does not affect the
halting decision (assuming there are no other structures in either of the paths)
4. forward go to ✓
Like, if-else this also just eliminates some set of instructions.
5. arbitrary go to ❌
This can simulate a for loop and so can cause problem in deciding halting.
6. non-recursive procedure call ✓
Each of the called procedure contributes to the number of executed instructions but since there is no recursion they’ll
eventually halt as long as each of the called procedures halt.
7. recursive procedure/function call ❌
This will also run into the same problem of a loop where the loop variables are changed inside the loop body. We may
not be able to determine if the sequence of recursive calls ever terminates.
8. repeat loop ❌
Similar to a for loop if the looping condition is changed within the loop body this can make the halting decision
undecidable.

Correct Option: B.
 1 votes -- Arjun Suresh (330k points)

4.9 Programming In C (36) top☝

4.9.1 Programming In C: GATE CSE 2000 | Question: 2.20 top☝ ☛ https://gateoverflow.in/667

The value of j at the end of the execution of the following C program:


int incr (int i)
{
static int count = 0;
count = count + i;
return (count);
}
main () {
int i, j;
for (i = 0; i <= 4; i++)
j = incr (i);
}

is:

A. 10
B. 4
C. 6
D. 7

gate2000-cse programming programming-in-c easy

Answer ☟

4.9.2 Programming In C: GATE CSE 2002 | Question: 1.17 top☝ ☛ https://gateoverflow.in/822

In the C language:

© Copyright GATE Overflow. Some rights reserved.


490 4 Programming and DS: Programming (108)

A. At most one activation record exists between the current activation record and the activation record for the main
B. The number of activation records between the current activation record and the activation records from the main depends
on the actual function calling sequence.
C. The visibility of global variables depends on the actual function calling sequence
D. Recursion requires the activation record for the recursive function to be saved in a different stack before the recursive
function can be called.

gate2002-cse programming programming-in-c easy descriptive

Answer ☟

4.9.3 Programming In C: GATE CSE 2002 | Question: 2.18 top☝ ☛ https://gateoverflow.in/848

The C language is:

A. A context free language


B. A context sensitive language
C. A regular language
D. Parsable fully only by a Turing machine

gate2002-cse programming programming-in-c normal

Answer ☟

4.9.4 Programming In C: GATE CSE 2002 | Question: 2.8 top☝ ☛ https://gateoverflow.in/838

Consider the following declaration of a two-dimensional array in C:


char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored starting from memory address 0, the address of
a[40][50] is:
A. 4040
B. 4050
C. 5040
D. 5050

gate2002-cse programming-in-c programming easy

Answer ☟

4.9.5 Programming In C: GATE CSE 2004 | Question: 33 top☝ ☛ https://gateoverflow.in/1030

Consider the following C program segment:


char p[20]; int i;
char* s = "string";
int length = strlen(s);
for(i = 0; i < length; i++)
p[i] = s[length-i];
printf("%s", p);

The output of the program is:

A. gnirts
B. string
C. gnirt
D. no output is printed

gate2004-cse programming programming-in-c easy

Answer ☟

4.9.6 Programming In C: GATE CSE 2005 | Question: 1, ISRO2017-55 top☝ ☛ https://gateoverflow.in/1343

What does the following C-statement declare?

int (*f) (int * );

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 491

A. A function that takes an integer pointer as argument and returns an integer


B. A function that takes an integer as argument and returns an integer pointer
C. A pointer to a function that takes an integer pointer as argument and returns an integer
D. A function that takes an integer pointer as argument and returns a function pointer

gate2005-cse programming programming-in-c easy isro2017

Answer ☟

4.9.7 Programming In C: GATE CSE 2005 | Question: 32 top☝ ☛ https://gateoverflow.in/1368

Consider the following C program:


double foo (double); /* Line 1 */
int main() {
double da, db;
//input da
db = foo(da);
}
double foo (double a) {
return a;
}

The above code compiled without any error or warning. If Line 1 is deleted, the above code will show:

A. no compile warning or error


B. some compiler-warnings not leading to unintended results
C. some compiler-warnings due to type-mismatch eventually leading to unintended results
D. compiler errors

gate2005-cse programming programming-in-c compiler-design easy

Answer ☟

4.9.8 Programming In C: GATE CSE 2008 | Question: 18 top☝ ☛ https://gateoverflow.in/416

Which combination of the integer variables x, y and z makes the variable a get the value 4 in the following expression?

a = (x > y)?((x > z)?x : z) : ((y > z)?y : z)


A. x = 3, y = 4, z = 2
B. x = 6, y = 5, z = 3
C. x = 6, y = 3, z = 5
D. x = 5, y = 4, z = 5

gate2008-cse programming programming-in-c easy

Answer ☟

4.9.9 Programming In C: GATE CSE 2008 | Question: 61 top☝ ☛ https://gateoverflow.in/484

Choose the correct option to fill ?1 and ?2 so that the program below prints an input string in reverse order. Assume
that the input string is terminated by a new line character.
void reverse(void)
{
int c;
if(?1) reverse();
?2
}
main()
{
printf("Enter text");
printf("\n");
reverse();
printf("\n");
}

A. ?1 is (getchar()! =′ ∖n′ )

© Copyright GATE Overflow. Some rights reserved.


492 4 Programming and DS: Programming (108)

?2 is getchar(c);
B. ?1 is ((c = getchar())! =′ ∖n′ )
?2 is getchar(c);
C. ?1 is (c! =′ ∖n′ )
?2 is putchar(c);
D. ?1 is ((c = getchar())! =′ ∖n′ )
?2 is putchar(c);

gate2008-cse programming normal programming-in-c

Answer ☟

4.9.10 Programming In C: GATE CSE 2012 | Question: 3 top☝ ☛ https://gateoverflow.in/35

What will be the output of the following C program segment?


char inChar = 'A';
switch ( inChar ) {
case 'A' : printf ("Choice A \n");
case 'B' :
case 'C' : printf ("Choice B");
case 'D' :
case 'E' :
default : printf ("No Choice");
}

A. No Choice
B. Choice A
C. Choice A
Choice B No Choice
D. Program gives no output as it is erroneous

gate2012-cse programming easy programming-in-c

Answer ☟

4.9.11 Programming In C: GATE CSE 2012 | Question: 48 top☝ ☛ https://gateoverflow.in/2176

Consider the following C code segment.


int a, b, c = 0;
void prtFun(void);
main()
{
static int a = 1; /* Line 1 */
prtFun();
a += 1;
prtFun();
printf(“ \n %d %d ”, a, b);
}

void prtFun(void)
{
static int a = 2; /* Line 2 */
int b = 1;
a += ++b;
printf(“ \n %d %d ”, a, b);
}

What output will be generated by the given code segment?

3 1
A. 4 1
4 2
4 2
B. 6 1
6 1

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 493

4 2
C. 6 2
2 0
3 1
D. 5 2
5 2

gate2012-cse programming programming-in-c normal

Answer ☟

4.9.12 Programming In C: GATE CSE 2012 | Question: 49 top☝ ☛ https://gateoverflow.in/43314

Consider the following C code segment.


int a, b, c = 0;
void prtFun(void);
main()
{
static int a = 1; /* Line 1 */
prtFun();
a += 1;
prtFun();
printf(“ \n %d %d ”, a, b);
}

void prtFun(void)
{
static int a = 2; /* Line 2 */
int b = 1;
a += ++b;
printf(“ \n %d %d ”, a, b);
}

What output will be generated by the given code segment if:


Line 1 is replaced by auto int a = 1 ;
Line 2 is replaced by register int a = 2 ;
3 1
A. 4 1
4 2
4 2
B. 6 1
6 1
4 2
C. 6 2
2 0
4 2
D. 4 2
2 0

normal gate2012-cse programming-in-c programming

Answer ☟

4.9.13 Programming In C: GATE CSE 2014 Set 2 | Question: 11 top☝ ☛ https://gateoverflow.in/1965

nC .
Suppose n and p are unsigned int variables in a C program. We wish to set p to 3 If n is large, which one of the
following statements is most likely to set p correctly?

A. p = n ∗ (n − 1) ∗ (n − 2)/6;
B. p = n ∗ (n − 1)/2 ∗ (n − 2)/3;
C. p = n ∗ (n − 1)/3 ∗ (n − 2)/2;
D. p = n ∗ (n − 1) ∗ (n − 2)/6.0;

gate2014-cse-set2 programming programming-in-c normal

© Copyright GATE Overflow. Some rights reserved.


494 4 Programming and DS: Programming (108)

Answer ☟

4.9.14 Programming In C: GATE CSE 2014 Set 2 | Question: 42 top☝ ☛ https://gateoverflow.in/2008

Consider the C function given below.


int f(int j)
{
static int i = 50;
int k;
if (i == j)
{
printf("something");
k = f(i);
return 0;
}
else return 0;
}

Which one of the following is TRUE?

A. The function returns 0 for all values of j.


B. The function prints the string something for all values of j.
C. The function returns 0 when j = 50.
D. The function will exhaust the runtime stack or run into an infinite loop when j = 50.

gate2014-cse-set2 programming programming-in-c

Answer ☟

4.9.15 Programming In C: GATE CSE 2015 Set 1 | Question: 11 top☝ ☛ https://gateoverflow.in/8185

The output of the following C program is_____________.


void f1 ( int a, int b) {
int c;
c = a; a = b;
b = c;
}
void f2 ( int * a, int * b) {
int c;
c = * a; *a = *b; *b = c;
}
int main () {
int a = 4, b = 5, c = 6;
f1 ( a, b);
f2 (&b, &c);
printf ("%d", c - a - b);
}

gate2015-cse-set1 programming programming-in-c easy numerical-answers

Answer ☟

4.9.16 Programming In C: GATE CSE 2015 Set 1 | Question: 35 top☝ ☛ https://gateoverflow.in/8283

What is the output of the following C code? Assume that the address of x is 2000 (in decimal) and an integer requires
four bytes of memory.
int main () {
unsigned int x [4] [3] =
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
printf ("%u, %u, %u", x + 3, *(x + 3), *(x + 2) + 3);
}

A. 2036, 2036, 2036


B. 2012, 4, 2204
C. 2036, 10, 10
D. 2012, 4, 6

gate2015-cse-set1 programming programming-in-c normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 495

4.9.17 Programming In C: GATE CSE 2015 Set 2 | Question: 15 top☝ ☛ https://gateoverflow.in/8086

Consider the following function written in the C programming langauge :


void foo(char *a)
{
if (*a && *a != ' ')
{
foo(a+1);
putchar(*a);
}
}

The output of the above function on input " ABCD EFGH " is

A. ABCD EFGH
B. ABCD
C. HGFE DCBA
D. DCBA

gate2015-cse-set2 programming programming-in-c normal

Answer ☟

4.9.18 Programming In C: GATE CSE 2015 Set 3 | Question: 48 top☝ ☛ https://gateoverflow.in/8557

Consider the following C program:


#include<stdio.h>
int main()
{
int i, j, k = 0;
j=2 * 3 / 4 + 2.0 / 5 + 8 / 5;
k-=--j;
for (i=0; i<5; i++)
{
switch(i+k)
{
case 1:
case 2: printf("\n%d", i+k);
case 3: printf("\n%d", i+k);
default: printf("\n%d", i+k);
}
}
return 0;
}

The number of times printf statement is executed is _______.

gate2015-cse-set3 programming programming-in-c normal numerical-answers

Answer ☟

4.9.19 Programming In C: GATE CSE 2015 Set 3 | Question: 54 top☝ ☛ https://gateoverflow.in/8563

Consider the following C program:


#include<stdio.h>
int f1(void);
int f2(void);
int f3(void);
int x=10;
int main()
{
int x=1;
x += f1() + f2 () + f3() + f2();
printf("%d", x);
return 0;
}
int f1() { int x = 25; x++; return x;}
int f2() { static int x = 50; x++; return x;}
int f3() { x *= 10; return x;}

The output of the program is ______.

gate2015-cse-set3 programming programming-in-c normal numerical-answers

© Copyright GATE Overflow. Some rights reserved.


496 4 Programming and DS: Programming (108)

Answer ☟

4.9.20 Programming In C: GATE CSE 2016 Set 1 | Question: 12 top☝ ☛ https://gateoverflow.in/39638

Consider the following "C" program.


void f(int, short);
void main()
{
int i = 100;
short s = 12;
short *p = &s;
____________; // call to f()
}

Which one of the following expressions , when placed in the blank above, will NOT result in a type checking error?

A. f(s, ∗s)
B. i = f(i, s)
C. f(i, ∗s)
D. f(i, ∗p)

gate2016-cse-set1 programming-in-c easy

Answer ☟

4.9.21 Programming In C: GATE CSE 2016 Set 1 | Question: 34 top☝ ☛ https://gateoverflow.in/39704

The following function computes the maximum value contained in an integer array P [ ] of size n (n >= 1).

int max (int *p,int n) {


int a = 0, b=n-1;

while (__________) {
if (p[a]<= p[b]) {a = a+1;}
else {b = b-1;}
}
return p[a];
}

The missing loop condition is:

A. a !=n
B. b !=0
C. b > (a + 1)
D. b !=a

gate2016-cse-set1 programming-in-c normal

Answer ☟

4.9.22 Programming In C: GATE CSE 2017 Set 1 | Question: 53 top☝ ☛ https://gateoverflow.in/118473

Consider the following C program.


#include<stdio.h>
#include<string.h>

void printlength(char *s, char *t) {


unsigned int c=0;
int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t);
printf("%d\n", len);
}

void main() {
char *x = "abc";
char *y = "defgh";
printlength(x,y);
}

Recall that strlen is defined in string. h as returning a value of type size_t, which is an unsigned int. The output of the
program is __________ .

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 497

gate2017-cse-set1 programming programming-in-c normal numerical-answers

Answer ☟

4.9.23 Programming In C: GATE CSE 2017 Set 1 | Question: 55 top☝ ☛ https://gateoverflow.in/118442

The output of executing the following C program is _______________ .


#include<stdio.h>

int total(int v) {
static int count = 0;
while(v) {
count += v&1;
v >>= 1;
}
return count;
}

void main() {
static int x=0;
int i=5;
for(; i>0; i--) {
x = x + total(i);
}
printf("%d\n", x);
}

gate2017-cse-set1 programming programming-in-c normal numerical-answers

Answer ☟

4.9.24 Programming In C: GATE CSE 2017 Set 2 | Question: 2 top☝ ☛ https://gateoverflow.in/118171

Match the following:

P. static char var ; i. Sequence of memory locations to store addresses


Q. m = malloc(10); m =NULL ; ii. A variable located in data section of memory
R. char *ptr[10] ; iii. Request to allocate a CPU register to store data
S. register int varl; iv. A lost memory which cannot be freed

A. P-ii; Q-iv; R-i; S-iii


B. P-ii; Q-i; R-iv; S-iii
C. P-ii; Q-iv; R-iii; S-i
D. P-iii; Q-iv; R-i; S-ii

gate2017-cse-set2 programming programming-in-c

Answer ☟

4.9.25 Programming In C: GATE CSE 2017 Set 2 | Question: 54 top☝ ☛ https://gateoverflow.in/118272

Consider the following C program.


#include<stdio.h>
int main () {
int m=10;
int n, n1;
n=++m;
n1=m++;
n--;
--n1;
n-=n1;
printf(“%d”, n);
return 0;
}

The output of the program is ______

gate2017-cse-set2 programming-in-c numerical-answers

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


498 4 Programming and DS: Programming (108)

4.9.26 Programming In C: GATE CSE 2018 | Question: 32 top☝ ☛ https://gateoverflow.in/204106

Consider the following C code. Assume that unsigned long int type length is 64 bits.
unsigned long int fun(unsigned long int n) {
unsigned long int i, j=0, sum = 0;
for( i=n; i>1; i=i/2) j++;
for( ; j>1; j=j/2) sum++;
return sum;
}

The value returned when we call fun with the input 240 is:

A. 4
B. 5
C. 6
D. 40

gate2018-cse programming-in-c normal programming

Answer ☟

4.9.27 Programming In C: GATE CSE 2019 | Question: 27 top☝ ☛ https://gateoverflow.in/302821

Consider the following C program:


#include <stdio.h>
int r() {
static int num=7;
return num--;
}
int main() {
for (r();r();r())
printf(“%d”,r());
return 0;
}

Which one of the following values will be displayed on execution of the programs?

A. 41
B. 52
C. 63
D. 630

gate2019-cse programming-in-c programming

Answer ☟

4.9.28 Programming In C: GATE CSE 2019 | Question: 52 top☝ ☛ https://gateoverflow.in/302796

Consider the following C program:


#include <stdio.h>
int main() {
float sum = 0.0, j=1.0, i=2.0;
while (i/j > 0.0625) {
j=j+j;
sum=sum+i/j;
printf("%f\n", sum);
}
return 0;
}

The number of times the variable sum will be printed, when the above program is executed, is _________

gate2019-cse numerical-answers programming-in-c programming

Answer ☟

4.9.29 Programming In C: GATE CSE 2019 | Question: 53 top☝ ☛ https://gateoverflow.in/302795

Consider the following C program:


#include <stdio.h>
int main()

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 499

{
int a[] = {2, 4, 6, 8, 10};
int i, sum=0, *b=a+4;
for (i=0; i<5; i++)
sum=sum+(*b-i)-*(b-i);
printf("%d\n", sum);
return 0;
}

The output of the above C program is _______

gate2019-cse numerical-answers programming-in-c programming

Answer ☟

4.9.30 Programming In C: GATE CSE 2020 | Question: 46 top☝ ☛ https://gateoverflow.in/333185

Consider the following C functions.

int fun1(int n) { int fun2(int n) {


static int i= 0; static int i= 0;
if (n > 0) { if (n>0) {
++i; i = i+ fun1 (n) ;
fun1(n-1); fun2(n-1) ;
} }
return (i); return (i);
} }

The return value of fun2(5) is _________

gate2020-cse numerical-answers programming-in-c

Answer ☟

4.9.31 Programming In C: GATE CSE 2021 Set 1 | Question: 37 top☝ ☛ https://gateoverflow.in/357414

​Consider the following ANSI C program.


#include <stdio.h>
int main()
{
int i, j, count;
count=0;
i=0;
for (j=-3; j<=3; j++)
{
if (( j >= 0) && (i++))
count = count + j;
}
count = count +i;
printf("%d", count);
return 0;
}

Which one of the following options is correct?

A. The program will not compile successfully


B. The program will compile successfully and output 10 when executed
C. The program will compile successfully and output 8 when executed
D. The program will compile successfully and output 13 when executed

gate2021-cse-set1 programming-in-c

Answer ☟

4.9.32 Programming In C: GATE IT 2004 | Question: 59 top☝ ☛ https://gateoverflow.in/3702

What is the output of the following program?


#include<stdio.h>
int funcf (int x);
int funcg (int y);
main ()
{
int x = 5, y = 10, count;

© Copyright GATE Overflow. Some rights reserved.


500 4 Programming and DS: Programming (108)

for (count = 1; count <= 2; ++count) {


y += funcf(x) + funcg(x);
printf ("%d", y);
}
}
funcf (int x) {
int y;
y = funcg(x);
return (y);
}
funcg (int x) {
static int y = 10;
y += 1;
return (y + x);
}

A. 43 80
B. 42 74
C. 33 37
D. 32 32

gate2004-it programming programming-in-c normal

Answer ☟

4.9.33 Programming In C: GATE IT 2004 | Question: 60 top☝ ☛ https://gateoverflow.in/3703

Choose the correct option to fill the ?1 and ?2 so that the program prints an input string in reverse order. Assume that
the input string is terminated by a new line character.
#include <stdio.h>
void wrt_it (void);
int main (void)
{
printf("Enter Text");
printf ("\n");
wrt_it();
printf ("\n");
return 0;
}
void wrt_it (void)
{
int c;
if (?1)
wrt_it();
?2
}

A. ?1 is getchar()! = '\n'
?2 is getchar(c);
B. ?1 is (c = getchar()); ! = '\n'
?2 is getchar(c);
C. ?1 is c! = '\n'
?2 is putchar(c);
D. ?1 is (c = getchar())! = '\n'
?2 is putchar(c);

gate2004-it programming programming-in-c normal

Answer ☟

4.9.34 Programming In C: GATE IT 2005 | Question: 58 top☝ ☛ https://gateoverflow.in/3819

Let a be an array containing n integers in increasing order. The following algorithm determines whether there are two
distinct numbers in the array whose difference is a specified number S > 0 .
i = 0; j = 1;
while (j < n ){
if (E) j++;
else if (a[j] - a[i] == S) break;
else i++;
}
if (j < n) printf("yes") else printf ("no");

Choose the correct expression for E.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 501

A. a[j] − a[i] > S


B. a[j] − a[i] < S
C. a[i] − a[j] < S
D. a[i] − a[j] > S

gate2005-it programming normal programming-in-c

Answer ☟

4.9.35 Programming In C: GATE IT 2006 | Question: 51 top☝ ☛ https://gateoverflow.in/3594

Which one of the choices given below would be printed when the following program is executed?
#include <stdio.h>
int a1[] = {6, 7, 8, 18, 34, 67};
int a2[] = {23, 56, 28, 29};
int a3[] = {-12, 27, -31};
int *x[] = {a1, a2, a3};
void print(int *a[])
{
printf("%d,", a[0][2]);
printf("%d,", *a[2]);
printf("%d,", *++a[0]);
printf("%d,", *(++a)[0]);
printf("%d\n", a[-1][+1]);
}
main()
{
print(x);
}

A. 8, −12, 7, 23, 8
B. 8, 8, 7, 23, 7
C. −12, −12, 27, −31, 23
D. −12, −12, 27, −31, 56

gate2006-it programming programming-in-c normal

Answer ☟

4.9.36 Programming In C: GATE IT 2007 | Question: 31 top☝ ☛ https://gateoverflow.in/3464

Consider the C program given below :


#include <stdio.h>
int main () {
int sum = 0, maxsum = 0, i, n = 6;
int a [] = {2, -2, -1, 3, 4, 2};
for (i = 0; i < n; i++) {
if (i == 0 || a [i] < 0 || a [i] < a [i - 1]) {
if (sum > maxsum) maxsum = sum;
sum = (a [i] > 0) ? a [i] : 0;
}
else sum += a [i];
}
if (sum > maxsum) maxsum = sum ;
printf ("%d\n", maxsum);

What is the value printed out when this program is executed?

A. 9
B. 8
C. 7
D. 6

gate2007-it programming programming-in-c normal

Answer ☟

Answers: Programming In C

© Copyright GATE Overflow. Some rights reserved.


502 4 Programming and DS: Programming (108)

4.9.1 Programming In C: GATE CSE 2000 | Question: 2.20 top☝ ☛ https://gateoverflow.in/667

 Answer: (A)

At i = 0, j = 0
At i = 1, j = 1
At i = 2, j = 3
At i = 3, j = 6
At i = 4, j = 10

 29 votes -- Rajarshi Sarkar (27.8k points)

4.9.2 Programming In C: GATE CSE 2002 | Question: 1.17 top☝ ☛ https://gateoverflow.in/822


A. Each function call starts a new activation record and since C allows nested function calls more than one activation
record can exist between the current activation record and main.
B. TRUE
C. Since, C uses static scoping, the actual function calling sequence has no impact on the visibility of global variables. If a
variable is not found in the current activation record, it is looked in global address space and this is independent of the
calling sequence.
D. All function calls- whether recursive or not uses the same stack for saving the activation record. There is no need for a
different stack as for C compiler a recursive function call and a normal function call make no difference.

 73 votes -- Arjun Suresh (330k points)

4.9.3 Programming In C: GATE CSE 2002 | Question: 2.18 top☝ ☛ https://gateoverflow.in/848

 Answer is (B).

All modern programming languages are CSL. Because they contain two features which cannot be handled by PDA.

The features are:

variable declared before use and


matching formal and actual parameters of functions.

 59 votes -- Sachin Mittal (15.8k points)

4.9.4 Programming In C: GATE CSE 2002 | Question: 2.8 top☝ ☛ https://gateoverflow.in/838

 The answer is (B).

In C, arrays are always stored in the row-major form.

Formula to evaluate 2-D array's location is:


loc(a[i][j]) = BA + [(i − lb1 ) × NC + (j − lb2 )] × c

Where,

BA - Base Address
NC - no. of columns
c - memory size allocated to data type of array a[lb1 … ub1 ][lb2 … ub2 ]

Here, BA = 0, NC = 100, c = 1, a[0 … 99][0 … 99] , so lb1 = 0, lb2 = 0

loc(a[40][50]) = 0 + [(40 − 0) × 100 + (50 − 0)] × 1


= 0 + [4000 + 50] × 1 = 4050 .
 41 votes -- Kalpna Bhargav (2.5k points)

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 503

4.9.5 Programming In C: GATE CSE 2004 | Question: 33 top☝ ☛ https://gateoverflow.in/1030

 Here,

p[0] = s[length] = '\0'; //compiler puts a '\0' at the end of all string literals

Now, for any string function in C, it checks till the first '\0' to identify the end of string. So, since the first char is '\0', printf
%s, will print empty string. If we use printf("%s", p+1); we will get option (C) with some possible garbage until some
memory location happens to contain "\0". For the given code, answer is (D).
 40 votes -- Arjun Suresh (330k points)

4.9.6 Programming In C: GATE CSE 2005 | Question: 1, ISRO2017-55 top☝ ☛ https://gateoverflow.in/1343


A. A function that takes an integer pointer as argument and returns an integer ⇒ int f(int∗)
B. A function that takes an integer as argument and returns an integer pointer ⇒ int ∗ f(int)
C. A pointer to a function that takes an integer pointer as argument and returns an integer ⇒

int (*f) (int * );

So, answer is C.
 43 votes -- Akash Kanase (36k points)

4.9.7 Programming In C: GATE CSE 2005 | Question: 32 top☝ ☛ https://gateoverflow.in/1368

 Answer is (D).

When a function is called without being defined, C compiler assumes it to return " int" but here foo is returning " double"
and hence the compiler will throw type mis-match error.

From C99 on ward, implicit declaration of functions is not even allowed.


 59 votes -- Aditi Dan (4k points)

4.9.8 Programming In C: GATE CSE 2008 | Question: 18 top☝ ☛ https://gateoverflow.in/416

 Using option (A) : x = 3, y = 4, z = 2


a = (3 > 4)? No
therefore don't evaluate the first part and check second part ((y > z)?y : z)
(4 > 2)? Yes
a = value of y = 4
Answer is (A) x = 3, y = 4, z = 2
 26 votes -- Keith Kr (4.5k points)

4.9.9 Programming In C: GATE CSE 2008 | Question: 61 top☝ ☛ https://gateoverflow.in/484

 Here, we are using the ' =' operator which has less priority than ' ! =' operator. So (c = getchar()) has to be in
brackets and after reversing the string we use function putchar(c) for printing the character.
So, option (D) is the right answer.
 27 votes -- Kalpna Bhargav (2.5k points)

4.9.10 Programming In C: GATE CSE 2012 | Question: 3 top☝ ☛ https://gateoverflow.in/35

 There is a `space` in between the `\` and `n`. ( see-Q-no.-3)

case 'A' : printf ("Choice A\ n"); ^

So, output of the given program is:


Choice A nChoice BNo Choice

© Copyright GATE Overflow. Some rights reserved.


504 4 Programming and DS: Programming (108)

Which includes:
'n'

And there is no new line or spaces between outputs. Hence, there is no option matching.

http://stackoverflow.com/questions/33694700/im-missing-something
References

 33 votes -- Arjun Suresh (330k points)

4.9.11 Programming In C: GATE CSE 2012 | Question: 48 top☝ ☛ https://gateoverflow.in/2176

 main
a=1
prtFun()
a=2
b=1
a = a + ++b = 2 + 2 = 4
b=2
printf → 4 2
back to main
a = a + 1 → 1 + 1 → 2 (local static a is taken)
prtFun()
a = 4 // previous value in the function is retained because of static
b=1
a = a + ++b = 4 + 2 = 6
b=2
printf → 6 2
back to main
a=2
b = 0 (initial value of global b. in prtFun local b is only updated)
printf → 2 0

The answer is C.
 56 votes -- Sankaranarayanan P.N (8.5k points)

4.9.12 Programming In C: GATE CSE 2012 | Question: 49 top☝ ☛ https://gateoverflow.in/43314

 main
a=1

prtFun()
a=2
b=1
a = a + ++b = 2 + 2 = 4
b=2
printf → 4 2
back to main
a=a+1→1+1→2

prtFun()
a = 2 //previous a is lost
b=1
a = a + ++b = 2 + 2 = 4
b=2
printf → 4 2

back to main

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 505

a = 2b = 0 (initial value of global b. in prtFun local b is only updated)


printf → 2 0

Answer is D.
 29 votes -- Sankaranarayanan P.N (8.5k points)

4.9.13 Programming In C: GATE CSE 2014 Set 2 | Question: 11 top☝ ☛ https://gateoverflow.in/1965

 Answer is (B).
In c, ∗ and / have the same precedence and are left associative.

Evaluation of n ∗ (n − 1) ∗ (n − 2) might exceed the unsigned int range.


So, (A) and (D) are eliminated.
n ∗ (n − 1) is always divisible by 2.(Gives an integer value). Where as it is not always divisible by 3.(You don't always get
an integer..truncation possible, less accuracy)
(C) eliminated.

In option (B)
n ∗ (n − 1)/2 gives an integer value.
This integer value multiplied by (n − 2) again gives an integer value.
Which when divided by 3 gives an integer value(Sets p correctly).

Reason : n ∗ (n − 1) ∗ (n − 2) is the multiplication of 3 consecutive numbers. which is divisible by 2 as well as 3.


Hence, (n ∗ (n − 1)/2 ∗ (n − 2)) is divisible by 3.
 193 votes -- Srinath Jayachandran (2.9k points)

4.9.14 Programming In C: GATE CSE 2014 Set 2 | Question: 42 top☝ ☛ https://gateoverflow.in/2008

 There is no updation for i and j in the function. so if we call function with j = 50 the recursive call will be
continued infinitely. There is no terminating condition for recursion. hence answer D
 38 votes -- Sankaranarayanan P.N (8.5k points)

4.9.15 Programming In C: GATE CSE 2015 Set 1 | Question: 11 top☝ ☛ https://gateoverflow.in/8185


void f1 ( int a, int b) { //This code is call by value
// hence no effect of actual values when run.
int c;
c = a;
a = b;
b = c;
}
void f2 ( int * a, int * b) { //*a= address of b
//and *b = address of c
int c; //int c = garbage
c = * a; //c = value at address a = 5;
*a = *b; //*a = Exchange original
// variable value of c to b = b= 6
*b = c; //*b = c = 5;
}
int main () {
int a = 4, b = 5, c = 6;
f1 ( a, b); This has no effect on actual values
// of a ,b since Call by value.
f2 (&b, &c); Here change will be happen.
At this point int a = 4, b = 6, c = 5;
printf ("%d", c - a - b); = (5-4)-6 = 1-6 = -5
}

 14 votes -- Anu007 (14.4k points)

Here, f1 will not change any values bcz it is call by value but f2 is call by reference and it swaps values of b and c and
changes are also reflected in main function. So, 5 − 4 − 6 = −5 is the answer.
 34 votes -- target gate (111 points)

© Copyright GATE Overflow. Some rights reserved.


506 4 Programming and DS: Programming (108)

4.9.16 Programming In C: GATE CSE 2015 Set 1 | Question: 35 top☝ ☛ https://gateoverflow.in/8283

 Address of x is 2000.
x being a 2 D array,

x + 3 = x + 3∗ sizeof its inner dimension

= 2000 + 3 ∗ 3 ∗ 4 (as inner dimension is 3 integers of size 4)

= 2000 + 36 = 2036 .

∗(x + 3) returns the value at address 2036. But since x is 2 − D array, one ∗ will just return the 1 D array which is the
starting address of it, which is 2036 only.

(x + 2) = 2000 + 2 ∗ 3 ∗ 4 = 2024
∗(x + 2) + 3 = 2024 + 3 ∗ 4 = 2036 (The ∗ changes the data type from 2D to 1D and hence +3 will add 3 ∗ 4 and not
3 ∗ 3 ∗ 4)

So, A.
 138 votes -- Arjun Suresh (330k points)

4.9.17 Programming In C: GATE CSE 2015 Set 2 | Question: 15 top☝ ☛ https://gateoverflow.in/8086

 Answer D as priority of ! = is greater than that of && in C. The execution happens as:

if ((*a) && (*a != ' '))

So, the if breaks either when ∗a = 0 (not ' 0' but ASCII 0 or null character '\0'), or when ∗a =' '.
So, the recursive call goes like
'A' - 'B' - 'C' - 'D' -' ' (breaks) and then starts outputting
DCBA
 46 votes -- Vikrant Singh (11.2k points)

4.9.18 Programming In C: GATE CSE 2015 Set 3 | Question: 48 top☝ ☛ https://gateoverflow.in/8557

 j=2 * 3 / 4 + 2.0 / 5 + 8 / 5;

j = (((2 ∗ 3)/4) + (2.0/5)) + (8/5) ; //As associativity of +, ∗ and / are from left to right and + has less precedence than
∗ and /.
j = ((6/4) + 0.4) + 1); //2.0 is double value and hence 5 is implicitly typecast to double and we get 0.4. But 8 and 5 are
integers and hence 8/5 gives 1 and not 1.6
j = (1 + 0.4) + 1; // 6/4 also gives 1 as both are integers
j = 1.4 + 1; //1 + 0.4 gives 1.4 as 1 will be implicitly typecast to 1.4
j = 2.4; // since j is integer when we assign 2.4 to it, it will be implicitly typecast to int.
So, j = 2;
k− = − − j;
This makes j = 1 and k = −1.
The variables j and k have values 1 and −1 respectively before the for loop. Inside the for loop, the variable i is initialized
to 0 and the loop runs from 0 to 4.
i = 0, k = −1, i + k = −1, default case is executed, printf count = 1
i = 1, k = −1, i + k = 0 , default case is executed, printf count = 2
i = 2, k = −1, i + k = 1 , case 2, case 3 and default case is executed, printf count = 5
i = 3, k = −1, i + k = 2 , case 2, case 3 and default case is executed, printf count = 8
i = 4, k = −1, i + k = 3 , case 3 and default case is executed, printf count = 10
i = 5 , loop exits and the control returns to main
Answer is 10.
 106 votes -- Shyam Singh (1.3k points)

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 507

4.9.19 Programming In C: GATE CSE 2015 Set 3 | Question: 54 top☝ ☛ https://gateoverflow.in/8563

 The variable x is initialized to 1. First and only call to f1() returns 26. First call to f2() returns 51. First and only
call to f3() returns 100. Second call to f2() returns 52 (The value of local static variable x in f2() retains its
previous value 51 and is incremented by 1).

x = 1 + 26 + 51 + 100 + 52 = 230

Answer: 230
 52 votes -- Shyam Singh (1.3k points)

4.9.20 Programming In C: GATE CSE 2016 Set 1 | Question: 12 top☝ ☛ https://gateoverflow.in/39638


A. f(s, ∗s) - 1st argument is short whereas the function expects an int. But in C language short gets implicitly
converted to int during a function call and so this won’t be a type error. But second argument is a pointer (can be 64 bits
on a x64 machine) where as the function expects a short (can be even 16 bits). So this will generate a type error. So,
WRONG.
B. i = f(i, s) - return type is not void. So, WRONG.
C. f(i, ∗s) - 1st argument is int, second is again syntax error. So, WRONG
D. f(i, ∗p) - Both the arguments and return type match. p is a pointer to short, so ∗p is value of short. So, D is ANSWER.

 70 votes -- Abhilash Panicker (7.6k points)

4.9.21 Programming In C: GATE CSE 2016 Set 1 | Question: 34 top☝ ☛ https://gateoverflow.in/39704

 Answer is (D).
Hint : Given in the question itself that we start comparing the contents of an array from a[0] and a[n − 1]
(converging from both side) then condition must be till both meet at a point and that point will be a = b .
Hence loop condition should be a! = b.
Option C fails for n = 2, p = [1, 2].
 45 votes -- sukanyac (131 points)

4.9.22 Programming In C: GATE CSE 2017 Set 1 | Question: 53 top☝ ☛ https://gateoverflow.in/118473

 (strlen(s) − strlen(t)) = 3 − 5 = −2

But in C, when we do operation with two unsigned integers, result is also unsigned. (strlen returns size_t which is
unsigned in most systems). So, this result "−2" is treated as unsigned and its value is INT_MAX − 2 (not sure about all
systems, but at least on systems using 2's complement representation). Now, the comparison is between this large number
and another unsigned number c which is 0. So, the comparison return TRUE here.

Even if 'c' is declared as " int", while doing an operation with an unsigned int, it gets promoted to unsigned int and we get the
same result.

Hence (strlen(s) − strlen(t)) > 0 will return 1 on execution thus the conditional operator will return the true statement
which is strlen(abc) = 3.

Ans should be 3.
 99 votes -- Arnabi Bej (5.8k points)

4.9.23 Programming In C: GATE CSE 2017 Set 1 | Question: 55 top☝ ☛ https://gateoverflow.in/118442


// inside total()

while(v) {
count += v&1; \\ check the lowest bit of v
v >>= 1; \\ or v = v >> 1 : right shift the bit pattern of v
}

© Copyright GATE Overflow. Some rights reserved.


508 4 Programming and DS: Programming (108)

This piece of code will count the no of set bits in v.

In the main function, i values goes from 5 to 1, So there will be 5 calls to total().
Each call to total(i) counts the no of set bits in i. But the count is a static variable,
So, total(i) = Total no of set bits in all i ≤ 5 .

5
x = ∑ [ total (i)] = 2 + 3 + 5 + 6 + 7 = 23
i=1

 51 votes -- Debashish Deka (40.7k points)

4.9.24 Programming In C: GATE CSE 2017 Set 2 | Question: 2 top☝ ☛ https://gateoverflow.in/118171

 static char var = A variable located in data section of memory


m = malloc(10); m = null; Here, free(m) is missing: So, a lost memory which cannot be freed
char ∗ P tr[10]; Sequence of 10 memory locations to store addresses
register int var1; Request to allocate a CPU register to store data
Answer is A.
 27 votes -- Prashant Singh (47.1k points)

4.9.25 Programming In C: GATE CSE 2017 Set 2 | Question: 54 top☝ ☛ https://gateoverflow.in/118272


m
m = 10; 10
n m
n = ++m; 11 11
n1 m
n1 = m++; 11 12
n
n --; 10
n1
-- n1; 10
n
n -= n1; 0 (∵ n = n − n1 = 10 − 10 = 0)

So,
printf("%d"", n);

prints "0".
Hence, answer is 0.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 509

 29 votes -- Arnabi Bej (5.8k points)

4.9.26 Programming In C: GATE CSE 2018 | Question: 32 top☝ ☛ https://gateoverflow.in/204106


unsigned long int fun(unsigned long int n) {
unsigned long int i, j=0, sum = 0;
for( i=n; i>1; i=i/2) j++;
for( ; j>1; j=j/2) sum++;
return sum;
}

First for loop will make j = 40


Next for loop will divide j value (which is 40 now) by 2 each time until j ≤ 1.

j loop starts:
j = 40 and sum =1,
j = 20 and sum=2,
j = 10 and sum=3,
j = 5 and sum=4,
j = 2 and sum=5,
j=1 break

So, Sum = 5
Correct Answer: B
 34 votes -- Digvijay (44.9k points)

4.9.27 Programming In C: GATE CSE 2019 | Question: 27 top☝ ☛ https://gateoverflow.in/302821

 Basic Points :-

1. after every expression statement in the for loop there is a sequence point
2. After return value copied, there is a sequence point.

for loop execution :- for(e1;e2;e3)


on first iteration, expression1 executed ( generally termed as initialization expression. )
next expression2 executed ( generally termed as condition check expression, if it evaluate to non-zero then only, for loop
body executed, otherwise for loop terminates.)
after first iteration, expression3 executed ( generally termed as increment expression. ), after that e2 evaluates and process
continues !
for(r(); r(); r())
{
printf("%d",r());
}
before main starts the execution num initialized with 7 ( note that it is stored under static memory due to it is static number. )
on first iteration :- r() ⟹ return 7 but num changed to 6.
r() ⟹ return 6 but num changed to 5. ⟹ condition evaluate to true ⟹ for loop body executes !
printf("%d",r()); ⟹ return 5 but num changed to 4. ⟹ print 5 on the screen.
r() ⟹ return 4 but num changed to 3.
r() ⟹ return 3 but num changed to 2. ⟹ condition evaluate to true ⟹ for loop body executes !
printf("%d",r()); ⟹ return 2 but num changed to 1. ⟹ print 2 on the screen.
r() ⟹ return 1 but num changed to 0.
r() ⟹ return 0 but num changed to −1. ⟹ condition evaluate to false ⟹ for loop over !
Hence option B : 52
 60 votes -- Shaik Masthan (50.4k points)

© Copyright GATE Overflow. Some rights reserved.


510 4 Programming and DS: Programming (108)

4.9.28 Programming In C: GATE CSE 2019 | Question: 52 top☝ ☛ https://gateoverflow.in/302796

 i = 2.0, j = 1.0

while ( ji > 0.0625)

j=1
2
j = 1 > 0.0625
i

j = j + j, 1st PRINT

j=2
2
j = 2 > 0.0625
i

j = j + j, 2nd PRINT

j=4
2
j = 4 > 0.0625
i

j = j + j, 3rd PRINT

j=8
2
j = 8 > 0.0625
i

j = j + j, 4th PRINT

j = 16
2
j = 16 > 0.0625
i

j = j + j, 5th PRINT

j = 32
2
j = 32 = 0.0625
i

Break

Total 5 times sum will be printed.


 25 votes -- Digvijay (44.9k points)

4.9.29 Programming In C: GATE CSE 2019 | Question: 53 top☝ ☛ https://gateoverflow.in/302795

 sum = 0, ∗b = a + 4 i.e.pointing to 10

sum = sum + (∗b − i) − ∗(b − i)

i=0
sum = 0 + (10 − 0) − (10) = 0

i=1
sum = 0 + (10 − 1) − (8) = 1

i=2
sum = 1 + (10 − 2) − (6) = 3

i=3
sum = 3 + (10 − 3) − (4) = 6

i=4
sum = 6 + (10 − 4) − (2) = 10
 23 votes -- Digvijay (44.9k points)

4.9.30 Programming In C: GATE CSE 2020 | Question: 46 top☝ ☛ https://gateoverflow.in/333185

 This illustration of function calling and values may help

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 511

Fig : Tracing by tree method

Now f1(5), if we observe it increments ‘i’, n times so f1(5) will return 5.


Similarly, f1(4) will increment ‘i’ 4 times but ‘i’ being static (just one memory location for entire program run instead of
different memory location across function calls), it′ll resume from its previous value of 5. So, f1(4) returns 9 [5 + 4]
By the same logic f1(3) will return 12 [9 + 3],
f1(2) will return 14 [12 + 2],
f1(1) will return 15 [14 + 1].
∴ Return value i = 55 and hence 55 is the output of f2(5).
 10 votes -- Asim Siddiqui (2.2k points)

4.9.31 Programming In C: GATE CSE 2021 Set 1 | Question: 37 top☝ ☛ https://gateoverflow.in/357414


for (j=-3; j<=3; j++)
{
if (( j >= 0) && (i++))
count = count + j;
}

From the above loop code we can see that the loop iterates 7 times for j ∈ {−3, −2, −1, 0, 1, 2, 3}.
Now, we have an “if” condition and inside it we have a logical AND operator (&&). In C language we have the following
short-circuit rule for binary logical operators

1. The second operand of logical OR operator || is ignored if the first operand is non zero.
2. The second operand of logical AND operator (&&) is ignored if the first operand is 0.

So, for j ∈ {−3, −2, −1} the first operand of || operator (j >= 0) will be 0, and hence the second operand (i++) will
be ignored.
For j ∈ {0, 1, 2, 3} the first operand of || operator (j >= 0) will be 1, and hence the second operand (i++) will get
evaluated 4 times and final value of i = 4.

© Copyright GATE Overflow. Some rights reserved.


512 4 Programming and DS: Programming (108)

Initial value of i = 0.
The postincrement operator i++, returns the original value of i and then increments i. So, when the first time i++ happens,
the second operator of logical AND operator is 0 and hence the “if” condition fails. So, count = count +j happens
only for j ∈ {1, 2, 3} and we get count = 0 + 1 + 2 + 3 = 6.
After the loop, we have count = count + i , which makes count = 6 + 4 = 10.
So, correct option: B.
Reference: https://gateoverflow.in/62409/what-is-the-output
References

 1 votes -- gatecse (62.6k points)

4.9.32 Programming In C: GATE IT 2004 | Question: 59 top☝ ☛ https://gateoverflow.in/3702

 funcf(x) + funcg(x)

funcf or funcg can be executed first as whether the first operand or the second operand to '+' operator is first executed is
not defined in C language and it depends on the compiler implementation. But here the order does not matter as both the
operands are not affecting each other and '+' is commutative. Lets assume funcf is executed first. It calls funcg - so even if
the order of call is reversed, result will be same.
In first call of funcg, y becomes 11 and it returns 5 + 11 = 16 .
In second call of funcg, y becomes 12 and it returns 5 + 12 = 17 .
So, in main y is incremented by 16 + 17 = 33 to become 10 + 33 = 43 . (Choice A)
In the second iteration y will be incremented by 18 + 19 = 37 to give 43 + 37 = 80 .
 40 votes -- Arjun Suresh (330k points)

4.9.33 Programming In C: GATE IT 2004 | Question: 60 top☝ ☛ https://gateoverflow.in/3703

 getchar() - reads a single character at a time from the stdin.


putchar(c) - writes a character specified by the argument to stdout.
As
getchar() and
putchar() both are needed to read the string and print its reverse and only option D contains both the function. D is
the answer. :P
Now coming to the code.
wrt_it(void) is calling itself recursively. when \n is encountered putchar() gets executed and prints the last character and
then the function returns to its previous call and prints last 2nd character and so on.
 19 votes -- Soumya Jain (12.5k points)

4.9.34 Programming In C: GATE IT 2005 | Question: 58 top☝ ☛ https://gateoverflow.in/3819

 Answer is (B)
For some ' i' if we find that difference of (A[j] − A[i] < S) we increment ' j' to make this difference wider so that it becomes
equal to S .
If at times difference becomes greater than S we know that it wont reduce further for same ' i' and so we increment the ' i'.
We do it for each ' i' if not found in previous iteration. until i = n
 43 votes -- Sandeep_Uniyal (6.5k points)

4.9.35 Programming In C: GATE IT 2006 | Question: 51 top☝ ☛ https://gateoverflow.in/3594

 a = {a1, a2, a3};


printf("%d,", a[0][2]);

a[0] is a1. So, this will print a1[2] = 8;


printf("%d,", *a[2]);

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 513

a[2] is a3. So, this will print ∗a3 = a3[0] = −12([] has greater precedence than ∗)
printf("%d,", *++a[0]);

a[0] which is a1 is incremented. a1 is a pointer to int (base address of an integer array) and so increment means adding
sizeof(int) and hence a1 now points to the second element in the array. So, ∗ + +a[0] prints second element of a1 which
is 7 and now a1 starts from 7.
printf("%d,", *(++a)[0]);

+ + a will increment a, which being a pointer (In C, an array when passed to a function becomes a pointer) to pointer (to
int) will add sizeof(pointer) to a. So, a now contains {a2, a3} and a[0] will be a2 and ∗a2 will be the first element in a2
which is 23
printf("%d\n", a[-1][+1]);

a[−1] will subtract a size of pointer from the base address of a. Normally this results in invalid memory access, but since we
have incremented a previously, a[−1] is valid and will point to a1. So, a[−1][+1] will be a1[1] which has the value 8.
(a1 was incremented in 3rd printf and hence starts from 7 and not 6. +1 is same as 1, just given to create confusion)
Correct Answer: A
 108 votes -- Arjun Suresh (330k points)

4.9.36 Programming In C: GATE IT 2007 | Question: 31 top☝ ☛ https://gateoverflow.in/3464

 Answer is C.

i A[i] for → if --- satisfied? maxsum sum


- - - 0 0
0 A[0] = 2 Yes (i == 0) 0 2
1 A[1] = −2 Yes (a[i] < 0) 2 0
2 A[2] = −1 Yes (a[i] < 0) (for → if → if --- not satisfied) 0
3 A[3] = 3 No (else executed) (for → if → if --- not satisfied) 3
4 A[4] = 4 No (else executed) (for → if → if --- not satisfied) 7
5 A[5] = 2 Yes (a[i] < a[i − 1]) 7 2

[End of for loop]


If (sum (i.e., 2) > maxsum (i.e., 7)) // No
maxsum = sum; // Not Executed
printf will output maxsum = 7
 31 votes -- MKT (141 points)

The algorithm is finding the maximum sum of the monotonically increasing continuous sequence of positive numbers in the
array. So, output would be 3 + 4 = 7.
 24 votes -- Arjun Suresh (330k points)

4.10 Programming Paradigms (2) top☝

4.10.1 Programming Paradigms: GATE CSE 2004 | Question: 1 top☝ ☛ https://gateoverflow.in/998

The goal of structured programming is to:

A. have well indented programs


B. be able to infer the flow of control from the compiled code
C. be able to infer the flow of control from the program text
D. avoid the use of GOTO statements

gate2004-cse programming easy programming-paradigms

Answer ☟

4.10.2 Programming Paradigms: GATE CSE 2004 | Question: 90 top☝ ☛ https://gateoverflow.in/1084

Choose the best matching between the programming styles in Group 1 and their characteristics in Group 2.

© Copyright GATE Overflow. Some rights reserved.


514 4 Programming and DS: Programming (108)

Group 1 Group 2
P. Functional 1. Common-based, procedural
Q. Logic 2. Imperative, abstract data types
R. Object-oriented 3. Side-effect free, declarative, expression evaluations
S. Imperative 4. Declarative, clausal representation, theorem proving

A. P −2 Q−3 R−4 S−1


B. P −4 Q−3 R−2 S−1
C. P −3 Q−4 R−1 S−2
D. P −3 Q−4 R−2 S−1

gate2004-cse programming normal programming-paradigms

Answer ☟

Answers: Programming Paradigms

4.10.1 Programming Paradigms: GATE CSE 2004 | Question: 1 top☝ ☛ https://gateoverflow.in/998

 Answer is (C). The goal of structured programming is to able to infer the flow of control from the program text . It
means user can execute the code according to his requirement. C and Pascal are good example of structured
programming. In structured programming control passes one instruction to another instruction in sequential manner.

Avoiding the use of GOTO statements is not the goal of structured programming, it (avoiding the use of GOTO) is one of the
requirements for a program to be structured.
 35 votes -- Kalpna Bhargav (2.5k points)

4.10.2 Programming Paradigms: GATE CSE 2004 | Question: 90 top☝ ☛ https://gateoverflow.in/1084

 Answer: (D) P-3 Q-4 R-2 S-1

Group 1 Group 2
P. Functional 3. Side-effect free, declarative, expression evaluations
Q. Logic 4. Declarative, clausal representation, theorem proving
R. Object-oriented 2. Imperative, abstract data types
S. Imperative 1. Common-based, procedural

Explanation:
P: Functional Programming is declarative in nature, involves expression evaluation, & side effect free.
Q: Logic is also declarative but involves theorem proving.
R: Object-oriented is an imperative statement based & have abstract (general) data types.
S: Imperative The programs are made giving commands & follows definite procedure & sequence
Ref: https://www.geeksforgeeks.org/gate-gate-cs-2004-question-90/
References

 19 votes -- Siddharth Mahapatra (1.2k points)

4.11 Recursion (15) top☝

4.11.1 Recursion: GATE CSE 1991 | Question: 01,x top☝ ☛ https://gateoverflow.in/507

Consider the following recursive definition of fib:


fib(n) := if n = 0 then 1
else if n = 1 then 1
else fib(n-1) + fib(n-2)

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 515

The number of times fib is called (including the first call) for evaluation of fib(7) is___________.

gate1991 programming recursion normal numerical-answers

Answer ☟

4.11.2 Recursion: GATE CSE 1994 | Question: 21 top☝ ☛ https://gateoverflow.in/2517

Consider the following recursive function:


function fib (n:integer);integer;
begin
if (n=0) or (n=1) then fib := 1
else fib := fib(n-1) + fib(n-2)
end;

The above function is run on a computer with a stack of 64 bytes. Assuming that only return address and parameter are passed
on the stack, and that an integer value and an address takes 2 bytes each, estimate the maximum value of n for which the stack
will not overflow. Give reasons for your answer.

gate1994 programming recursion normal descriptive

Answer ☟

4.11.3 Recursion: GATE CSE 2000 | Question: 16 top☝ ☛ https://gateoverflow.in/687

A recursive program to compute Fibonacci numbers is shown below. Assume you are also given an array f[0 … m]
with all elements initialized to 0.
fib(n) {
if (n > M) error ();
if (n == 0) return 1;
if (n == 1)return 1;
if (▭)________________________(1)
return ▭__________________(2)
t = fib(n - 1) + fib(n - 2);
▭_____________________________(3)
return t;
}

A. Fill in the boxes with expressions/statement to make fib() store and reuse computed Fibonacci values. Write the box
number and the corresponding contents in your answer book.
B. What is the time complexity of the resulting program when computing fib(n)?

gate2000-cse algorithms normal descriptive recursion

Answer ☟

4.11.4 Recursion: GATE CSE 2001 | Question: 13 top☝ ☛ https://gateoverflow.in/754

Consider the following C program:


void abc(char*s)
{
if(s[0]=='\0')return;
abc(s+1);
abc(s+1);
printf("%c",s[0]);
}

main()
{
abc("123");
}

A. What will be the output of the program?


B. If abc(s) is called with a null-terminated string s of length n characters (not counting the null ('\0') character), how many
characters will be printed by abc(s)?

gate2001-cse programming recursion normal descriptive

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


516 4 Programming and DS: Programming (108)

4.11.5 Recursion: GATE CSE 2002 | Question: 11 top☝ ☛ https://gateoverflow.in/864

The following recursive function in C is a solution to the Towers of Hanoi problem.


void move(int n, char A, char B, char C) {
if (......................) {
move (.............................);
printf("Move disk %d from pole %c to pole %c\n", n, A, C);
move (.....................);
}
}

Fill in the dotted parts of the solution.

gate2002-cse programming recursion descriptive

Answer ☟

4.11.6 Recursion: GATE CSE 2004 | Question: 31, ISRO2008-40 top☝ ☛ https://gateoverflow.in/1028

Consider the following C function:


int f(int n)
{
static int i = 1;
if(n >= 5) return n;
n = n+i;
i++;
return f(n);
}

The value returned by f(1) is:

A. 5
B. 6
C. 7
D. 8

gate2004-cse programming programming-in-c recursion easy isro2008

Answer ☟

4.11.7 Recursion: GATE CSE 2005 | Question: 81b top☝ ☛ https://gateoverflow.in/82146

double foo(int n)
{
int i;
double sum;
if(n == 0)
{
return 1.0;
}
else
{
sum = 0.0;
for(i = 0; i < n; i++)
{
sum += foo(i);
}
return sum;
}

Suppose we modify the above function foo() and stores the value of foo(i) 0 ≤ i < n, as and when they are computed. With
this modification the time complexity for function foo() is significantly reduced. The space complexity of the modified
function would be:

A. O(1)
B. O(n)
C. O(n2 )
D. n!

gate2005-cse programming recursion normal

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 517

Answer ☟

4.11.8 Recursion: GATE CSE 2007 | Question: 42 top☝ ☛ https://gateoverflow.in/1240

Consider the following C function:


int f(int n)
{
static int r = 0;
if (n <= 0) return 1;
if (n > 3)
{ r = n;
return f(n-2) + 2;
}
return f(n-1) + r;
}

What is the value of f(5)?

A. 5
B. 7
C. 9
D. 18

gate2007-cse programming recursion normal

Answer ☟

4.11.9 Recursion: GATE CSE 2014 Set 2 | Question: 40 top☝ ☛ https://gateoverflow.in/2000

Consider the following function.


double f(double x){
if( abs(x*x - 3) < 0.01)
return x;
else
return f(x/2 + 1.5/x);
}

Give a value q (to 2 decimals) such that f(q) will return q:_____.

gate2014-cse-set2 programming recursion numerical-answers normal

Answer ☟

4.11.10 Recursion: GATE CSE 2016 Set 1 | Question: 35 top☝ ☛ https://gateoverflow.in/39730

What will be the output of the following C program?


void count (int n) {
static int d=1;

printf ("%d",n);
printf ("%d",d);
d++;
if (n>1) count (n-1);
printf ("%d",d);

void main(){
count (3);
}

A. 312213444
B. 312111222
C. 3122134
D. 3121112

gate2016-cse-set1 programming-in-c recursion normal

Answer ☟

© Copyright GATE Overflow. Some rights reserved.


518 4 Programming and DS: Programming (108)

4.11.11 Recursion: GATE CSE 2016 Set 2 | Question: 37 top☝ ☛ https://gateoverflow.in/39602

Consider the following program:


int f (int * p, int n)
{
if (n <= 1) return 0;
else return max (f (p+1, n-1), p[0] - p[1]);
}
int main ()
{
int a[] = {3, 5, 2, 6, 4};
print f(" %d", f(a, 5));
}

Note: max(x, y) returns the maximum of x and y.


The value printed by this program is ________.

gate2016-cse-set2 programming-in-c normal numerical-answers recursion

Answer ☟

4.11.12 Recursion: GATE CSE 2017 Set 1 | Question: 35 top☝ ☛ https://gateoverflow.in/118317

Consider the following two functions.


void fun1(int n) {
if(n == 0) return;
printf("%d", n);
fun2(n - 2);
printf("%d", n);
}
void fun2(int n) {
if(n == 0) return;
printf("%d", n);
fun1(++n);
printf("%d", n);
}

The output printed when fun1(5) is called is

A. 53423122233445
B. 53423120112233
C. 53423122132435
D. 53423120213243

gate2017-cse-set1 programming normal tricky recursion

Answer ☟

4.11.13 Recursion: GATE CSE 2017 Set 1 | Question: 36 top☝ ☛ https://gateoverflow.in/118319

Consider the C functions foo and bar given below:


int foo(int val) {
int x=0;
while(val > 0) {
x = x + foo(val--);
}
return val;
}

int bar(int val) {


int x = 0;
while(val > 0) {
x= x + bar(val-1);
}
return val;
}

Invocations of foo(3) and bar(3) will result in:

A. Return of 6 and 6 respectively.


B. Infinite loop and abnormal termination respectively.
C. Abnormal termination and infinite loop respectively.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 519

D. Both terminating abnormally.

gate2017-cse-set1 programming-in-c programming normal recursion

Answer ☟

4.11.14 Recursion: GATE CSE 2018 | Question: 21 top☝ ☛ https://gateoverflow.in/204095

Consider the following C program:


#include<stdio.h>

int counter=0;

int calc (int a, int b) {


int c;
counter++;
if(b==3) return (a*a*a);
else {
c = calc(a, b/3);
return (c*c*c);
}
}

int main() {
calc(4, 81);
printf("%d", counter);
}

The output of this program is ______.

gate2018-cse programming-in-c numerical-answers recursion programming

Answer ☟

4.11.15 Recursion: GATE IT 2007 | Question: 27 top☝ ☛ https://gateoverflow.in/3460

The function f is defined as follows:


int f (int n) {
if (n <= 1) return 1;
else if (n % 2 == 0) return f(n/2);
else return f(3n - 1);
}

Assuming that arbitrarily large integers can be passed as a parameter to the function, consider the following statements.

i. The function f terminates for finitely many different values of n ≥ 1 .


ii. The function f terminates for infinitely many different values of n ≥ 1 .
iii. The function f does not terminate for finitely many different values of n ≥ 1 .
iv. The function f does not terminate for infinitely many different values of n ≥ 1 .

Which one of the following options is true of the above?

A. i and iii
B. i and iv
C. ii and iii
D. ii and iv

gate2007-it programming recursion normal

Answer ☟

Answers: Recursion

4.11.1 Recursion: GATE CSE 1991 | Question: 01,x top☝ ☛ https://gateoverflow.in/507

 The recurrence relation for the number of calls is

T(n) = T(n − 1) + T(n − 2) + 1

where 1 is for the current called function.

© Copyright GATE Overflow. Some rights reserved.


520 4 Programming and DS: Programming (108)

T(0) = T(1) = 1 (for fib(0) and fib(1), there are no recursive calls and only current function call is there).
T(2) = 3
T(3) = 5
T(4) = 9
T(5) = 15
T(6) = 25
T(7) = 41

Answer: 41
 48 votes -- Arjun Suresh (330k points)

4.11.2 Recursion: GATE CSE 1994 | Question: 21 top☝ ☛ https://gateoverflow.in/2517

 Size of an activation record = 2 + 2 = 4 bytes.

So, no. of possible activation records which can be live at a time = 64/4 = 16 .

So, we can have 16 function calls live at a time (recursion depth = 16), meaning the maximum value for n without stack
overflow is 16 (calls from 1 − 16). For n = 17 , stack will overflow.

This is different from the total no. of recursive calls which will be as follows:

n No. of calls
1 1
2 3
3 5
4 9
5 15
6 25

 50 votes -- Arjun Suresh (330k points)

4.11.3 Recursion: GATE CSE 2000 | Question: 16 top☝ ☛ https://gateoverflow.in/687

 Array f is used to store the fib() values calculated in order to save repeated calls. Since n = 0 and n = 1 are
special cases we can store fib(2) to f[0], fib(3) to f[1] and so on. The missing code completed would be:

if (f[n - 2] != 0){
return f[n-2];
}
t = fib(n-1) + fib(n-2);
f[n-2] = t;
return t;

In this code, fib(i) will do a recursion only once as once fib(i) is calculated it is stored in array. So, the time complexity for
fib(n) would be Θ(n).
PS: We can also store fib(n) in f(n), the above code just saves 2 elements' space in the array.
 33 votes -- Arjun Suresh (330k points)

4.11.4 Recursion: GATE CSE 2001 | Question: 13 top☝ ☛ https://gateoverflow.in/754

 Answer (A) : 332 332 1


Answer (B) : 2n − 1
Q. (A) O/p :
3323321

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 521

(B) : T(n) = 2T(n − 1) + 1; n > 0


= 0; n = 0 [Since for length zero string no character will be printed]
After solving it by substitution,
T(n) = 2T(n − 1) + 1
= 2(2T(n − 2) + 1) + 1
= 22 T(n − 2) + 2 + 1
= 22 (2T(n − 3) + 1) + 2 + 1
= 23 T(n − 3) + 22 + 2 + 1
Finally, it will expand like
T(n) = 2n T(n − n) + 2n−1 + 2n−2 + … + 22 + 2 + 1
= 2n T(0) + 2n−1 + 2n−2 + … + 22 + 2 + 1
1.(2n −1)
= (2−1)
= 2n − 1
 34 votes -- jayendra (6.7k points)

4.11.5 Recursion: GATE CSE 2002 | Question: 11 top☝ ☛ https://gateoverflow.in/864


void move(int n, char A, char B, char C) {
if (n > 0) {
move (n-1, A, C, B);
printf("Move disk %d from pole %c to pole %c\n", n, A, C);
move (n-1, B, A, C);
}
}

 25 votes -- minal (13.1k points)

4.11.6 Recursion: GATE CSE 2004 | Question: 31, ISRO2008-40 top☝ ☛ https://gateoverflow.in/1028

 Answer is 7. As,

f(1) : n = 2, i = 2

f(2) : n = 4, i = 3

f(4) : n = 7, i = 4

f(7) : print(n) ⇒ 7 <ans>


 34 votes -- sumit kumar singh dixit (1.6k points)

4.11.7 Recursion: GATE CSE 2005 | Question: 81b top☝ ☛ https://gateoverflow.in/82146

 Given program:

#include <stdio.h>
double foo(int n) {
int i;
double sum;
if(n == 0) {
return 1.0;

© Copyright GATE Overflow. Some rights reserved.


522 4 Programming and DS: Programming (108)

}
else {
sum = 0.0;
for(i = 0; i < n; i++) {
sum += foo(i);
}
return sum;
}
}

int main() {
double a = foo(5);
printf("%.2f\n",a);
}

And here is the present situation :

Here we can see that, we have lots of overlapping subproblems. Too many function calls.

1. No of function calls = 2n
2. stack depth used = O(n)

Therefore space is linear and time is exponential.


If we take a small number say 4, then we would have 8.0 as answer, or we can see that foo(n) = 2n−1
and

1. stack depth used = 5.


2. No of function calls = 24 = 16 .

Now, using one-dimensional ( 1D) table we can reduce the no of function calls and depth of stack space used as well.
Here is what we want to achieve:

We are reusing already computed foo(x) values. For this purpose, we will be using one 1D array of doubles of size n.
Here is what we are going to do:

1. First, check in the 1D table for the required call value.


2. If correct value found: do not call recursive functions

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 523

3. If not, then only attempt for loop recursive calls

Here is the code:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define UNUSED 0.5
double *memo_table;
double foo(int n) {
int i;
double sum;
if(memo_table[n] != UNUSED) {
return memo_table[n];
}else {
sum = 0.0;
for(i=0;i<n;i++) {
sum += foo(i);
}
return memo_table[n] = sum;
}
}
int main() {
int n,i;
scanf("%d",&n);
memo_table = malloc((1+n)*sizeof(double));
for(i=0;i<=n;i++) memo_table[i] = UNUSED;
// base case
memo_table[0] = 1.0;
double a = foo(n);
printf("%lf\n",a);
free(memo_table);
}

Improvements over given program:

1. Stack space because of function calls reduced to two level only.


2. Extra space used for the 1D array = O(n)
3. More importantly, Time is reduced to O(n2 ). (Exponential to Quadratic !! )

Overall space complexity = stack + extra = O(1) + O(n) = O(n)


Answer is B.
 49 votes -- Debashish Deka (40.7k points)

4.11.8 Recursion: GATE CSE 2007 | Question: 42 top☝ ☛ https://gateoverflow.in/1240

 The answer is D.

f(5) = 18.

f(3) + 2 = 16 + 2 = 18

f(2) + 5 = 11 + 5 = 16

f(1) + 5 = 6 + 5 = 11

f(0) + 5 = 1 + 5 = 6

Consider from last to first. Since it is recursive function.


 31 votes -- Gate Keeda (15.9k points)

4.11.9 Recursion: GATE CSE 2014 Set 2 | Question: 40 top☝ ☛ https://gateoverflow.in/2000

 (We can directly go to the "if" part to get one answer, but we need to solve "else" part too to get all possible
answers which though is not asked in question)
Solving the else part:
3 x2 +3
x
2 + 2x = 2x

2 +3

© Copyright GATE Overflow. Some rights reserved.


524 4 Programming and DS: Programming (108)

x2 +3
So, the new value of x will be 2x and we need it equal to x.
x2 +3
2x =x ⟹ x2 +3= 2x2 ⟹ x2 = 3 ⟹ x = 1.732

Now solving the if part.


abs(x*x - 3) < 0.01

So, x2 − 3 < 0.01 and − (x2 − 3) < 0.01 ⟹ x2 < 3.01 and x2 > 2.99 ⟹ x < 1.735 and x > 1.729
Corrected to 2 decimal places answer should be 1.73 or 1.74.
 78 votes -- Arjun Suresh (330k points)

4.11.10 Recursion: GATE CSE 2016 Set 1 | Question: 35 top☝ ☛ https://gateoverflow.in/39730

 Here, d is Static, so the value of d will persists between the function calls.

1. count(3) will print the value of n and d and increments d and call count(2) ⇒ prints 3 1.
2. count(2) will print the value of n and d and increments d and call count(1) ⇒ prints 2 2.
3. count(1) will print the value of n and d and increments d ⇒ prints 1 3.

Now, it will return and prints the final incremented value of d which is 4, three times.
So, option (A) is correct = 3 1 2 2 1 3 4 4 4
 54 votes -- Monanshi Jain (7k points)

4.11.11 Recursion: GATE CSE 2016 Set 2 | Question: 37 top☝ ☛ https://gateoverflow.in/39602

 f(a, 5)

p , n = 5. 3 5 2 6 4
max(f(p + 1, 5 − 1), 3 − 5) = max(f(p + 1, 4), −2)
p , n = 4. 5 2 6 4
max(max(f(p + 1, 4 − 1), 5 − 2), −2) = max(max(f(p + 1, 3), 3), −2)
p , n = 3. 2 6 4
max(max(max(f(p + 1, 3 − 1), 2 − 6), 3), −2) = max(max(max(f(p + 1, 2), −4), 3), −2)
p , n = 2. 6 4
max(max(max(max(f(p + 1), 1), 2), −4), 3), −2)
n = 1 , return 0

max(max(max(max(0, 2), −4), 3), −2)


= max(max(max(2, −4), 3), −2)
= max(max(2, 3), −2)
= max(3, −2)
=3
 55 votes -- Praveen Saini (41.9k points)

4.11.12 Recursion: GATE CSE 2017 Set 1 | Question: 35 top☝ ☛ https://gateoverflow.in/118317

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 525

Unroll recursion up to a point where we can distinguish the given options and choose the correct one!
Options B and D are eliminated.
A is the answer.

 77 votes -- Debashish Deka (40.7k points)

4.11.13 Recursion: GATE CSE 2017 Set 1 | Question: 36 top☝ ☛ https://gateoverflow.in/118319

 Answer should be C.
Consider foo
Initially val = 3
foo(val − −)
is equivalent to

1. foo(val)
2. val = val − 1

So,

1. foo(3)
2. val = 2

foo(3) calls foo(3) which in turn calls foo(3) this goes on


So, here we can see that foo(3) is called infinite number of times which causes memory overflow and abrupt termination
and one more thing to observe is infinite loop is not there since the val is decremented in the first iteration.
Consider bar.
Here, we can see the val is not decrementing in the loop
So,

1. bar(3) will call bar(2)


2. bar(2) will call bar(1)
3. bar(1) will call bar(0) → Here, bar(0) return 0
4. bar(1) will call bar(0)
5. bar(1) will call bar(0)

This will go on so here there is a problem of infinite loop but not abrupt termination since it does not cause memory
overflow.
 81 votes -- (points)

© Copyright GATE Overflow. Some rights reserved.


526 4 Programming and DS: Programming (108)

4.11.14 Recursion: GATE CSE 2018 | Question: 21 top☝ ☛ https://gateoverflow.in/204095


int main() {
calc(4, 81);
printf("%d", counter);
}

printf("%d", counter);
So we need only counter value.

Each function increments counter value by 1. Goal is to find the number of function calls.
Squence of function calls:
calc(4, 81) ---> calc(4, 27) ---> calc(4, 9) ---> calc(4, 3) ---> return

4 function calls.

counter = 4

 34 votes -- Digvijay (44.9k points)

4.11.15 Recursion: GATE IT 2007 | Question: 27 top☝ ☛ https://gateoverflow.in/3460

 The function terminates for all powers of 2 (which is infinite), hence (i) is false and (ii) is TRUE.
Let n = 5.
Now, recursive calls will go like 5 − 14 − 7 − 20 − 10 − 5−
And this goes into infinite recursion. And if we multiply 5 with any power of 2, also result will be infinite recursion. Since,
there are infinite powers of 2 possible, there are infinite recursions possible (even considering this case only). So, (iv) is
TRUE and (iii) is false.
So, correct answer is (D).
 55 votes -- Arjun Suresh (330k points)

4.12 Structures (4) top☝

4.12.1 Structures: GATE CSE 2000 | Question: 1.11 top☝ ☛ https://gateoverflow.in/634

The following C declarations:


struct node {
int i:
float j;
};
struct node *s[10];

define s to be:

A. An array, each element of which is a pointer to a structure of type node


B. A structure of 2 fields, each field being a pointer to an array of 10 elements
C. A structure of 3 fields: an integer, a float, and an array of 10 elements
D. An array, each element of which is a structure of type node

gate2000-cse programming programming-in-c easy structures

Answer ☟

4.12.2 Structures: GATE CSE 2018 | Question: 2 top☝ ☛ https://gateoverflow.in/204076

Consider the following C program:


#include<stdio.h>
struct Ournode{
char x, y, z;
};
int main() {
struct Ournode p={'1', '0', 'a'+2};
struct Ournode *q=&p;
printf("%c, %c", *((char*)q+1), *((char*)q+2));
return 0;
}

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 527

The output of this program is:

A. 0, c
B. 0, a+2
C. '0', 'a+2'
D. '0', 'c'

gate2018-cse programming-in-c programming structures pointers normal

Answer ☟

4.12.3 Structures: GATE IT 2004 | Question: 61 top☝ ☛ https://gateoverflow.in/3704

Consider the following C program:


#include <stdio.h>
typedef struct {
char *a;
char *b;
} t;
void f1 (t s);
void f2 (t *p);
main()
{
static t s = {"A", "B"};
printf ("%s %s\n", s.a, s.b);
f1(s);
printf ("%s %s\n", s.a, s.b);
f2(&s);
}
void f1 (t s)
{
s.a = "U";
s.b = "V";
printf ("%s %s\n", s.a, s.b);
return;
}
void f2(t *p)
{
p -> a = "V";
p -> b = "W";
printf("%s %s\n", p -> a, p -> b);
return;
}

What is the output generated by the program ?

A. A B
UV
V W
V W
B. A B
UV
AB
V W
C. A B
UV
UV
V W
D. A B
UV
V W
UV

gate2004-it programming programming-in-c normal structures

Answer ☟

4.12.4 Structures: GATE IT 2006 | Question: 49 top☝ ☛ https://gateoverflow.in/3592

Which one of the choices given below would be printed when the following program is executed ?
#include <stdio.h>
struct test {
int i;

© Copyright GATE Overflow. Some rights reserved.


528 4 Programming and DS: Programming (108)

char *c;
}st[] = {5, "become", 4, "better", 6, "jungle", 8, "ancestor", 7, "brother"};
main ()
{
struct test *p = st;
p += 1;
++p -> c;
printf("%s,", p++ -> c);
printf("%c,", *++p -> c);
printf("%d,", p[0].i);
printf("%s \n", p -> c);
}

A. jungle, n, 8, nclastor
B. etter, u, 6, ungle
C. cetter, k, 6, jungle
D. etter, u, 8, ncestor

gate2006-it programming programming-in-c normal structures

Answer ☟

Answers: Structures

4.12.1 Structures: GATE CSE 2000 | Question: 1.11 top☝ ☛ https://gateoverflow.in/634

 Correct Option: A
[] has greater precedence than ∗ in C. So, s becomes an array of pointers.
 49 votes -- gatecse (62.6k points)

4.12.2 Structures: GATE CSE 2018 | Question: 2 top☝ ☛ https://gateoverflow.in/204076

 char x ='a' +2
i.e. x =='c'

So, p ={'1','0','c'}

∗((char∗)q + 1) == p[1]
∗((char∗)q + 2) == p[2]
printf("%c, %c", *((char*)q+1), *((char*)q+2));

Output: 0, c
Correct Answer: A
 38 votes -- Digvijay (44.9k points)

4.12.3 Structures: GATE IT 2004 | Question: 61 top☝ ☛ https://gateoverflow.in/3704

 First print A B

f1 is call by value the changes applciable only for local

from f1 U V is printed

back in main A B is printed

then in f2 V W is printed

Hence, answer is (B).


 33 votes -- Sankaranarayanan P.N (8.5k points)

4.12.4 Structures: GATE IT 2006 | Question: 49 top☝ ☛ https://gateoverflow.in/3592

 code :

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 529

#include <stdio.h>

struct test {
int i;
char *c;
}st[] = {5, "become", 4, "better", 6, "jungle", 8, "ancestor", 7, "brother"};

int main () {
//printf("size = %d\n",sizeof(struct test) );
struct test *p = st;
p += 1;
++p->c; // ++(p->c)
printf("%s,", p++->c); // (p++)->c
printf("%c,", *++p->c); // *(++(p->c))
printf("%d,", p[0].i);
printf("%s \n", p->c);
}

We will assume few things:

Size of integer 4 Bytes.


Size of a pointer 4 Bytes.

Neglecting any alignment issues with the storage of this structure we will have 8 Bytes per structure.
And one precedence rule we need to use:

Initial situation :

struct test *p = st;

p += 1;
We know that if ptr is a pointer then, ptr + x = ptr + x*sizeof(*ptr);

© Copyright GATE Overflow. Some rights reserved.


530 4 Programming and DS: Programming (108)

++p->c;

printf("%s,", p++->c); // (p++)->c

printf("%c,", *++p->c); // *(++(p->c))

printf("%d,", p[0].i);

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 531

printf("%s \n", p->c);

Correct Answer: B
References

 316 votes -- Debashish Deka (40.7k points)

4.13 Type Checking (1) top☝

4.13.1 Type Checking: GATE CSE 2003 | Question: 24 top☝ ☛ https://gateoverflow.in/914

Which of the following statements is FALSE?

A. In statically typed languages, each variable in a program has a fixed type


B. In un-typed languages, values do not have any types
C. In dynamically typed languages, variables have no types
D. In all statically typed languages, each variable in a program is associated with values of only a single type during the
execution of the program

gate2003-cse programming normal type-checking

Answer ☟

Answers: Type Checking

4.13.1 Type Checking: GATE CSE 2003 | Question: 24 top☝ ☛ https://gateoverflow.in/914

 Answer is (C). In dynamically typed languages variables do have type- just that it is inferred during runtime.

 23 votes -- Arjun Suresh (330k points)

4.14 Union (1) top☝

4.14.1 Union: GATE CSE 2000 | Question: 1.17, ISRO2015-79 top☝ ☛ https://gateoverflow.in/640

Consider the following C declaration:


struct (
short x[5];
union {
float y;
long z;
} u;
)t;

Assume that the objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory
requirement for variable t, ignoring alignment consideration, is:

© Copyright GATE Overflow. Some rights reserved.


532 4 Programming and DS: Programming (108)

A. 22 bytes
B. 14 bytes
C. 18 bytes
D. 10 bytes

gate2000-cse programming programming-in-c easy isro2015 union

Answer ☟

Answers: Union

4.14.1 Union: GATE CSE 2000 | Question: 1.17, ISRO2015-79 top☝ ☛ https://gateoverflow.in/640

 Correct Option: C

Here, structure creates the memory for 'array and union', but union only creates the memory for only ' long z' which is the
largest size data type inside it.

Hence,

short × [5] = 5 ∗ 2 = 10 bytes [ shorts take 2 bytes]

long z = 8 bytes

So, (10 + 8) = 18 bytes


 53 votes -- Kalpna Bhargav (2.5k points)

4.15 Variable Binding (1) top☝

4.15.1 Variable Binding: GATE IT 2007 | Question: 34, UGCNET-Dec2012-III: 52 top☝ ☛ https://gateoverflow.in/3467

Consider the program below in a hypothetical programming language which allows global variables and a choice of
static or dynamic scoping.
int i;
program main()
{
i = 10;
call f();
}

procedure f()
{
int i = 20;
call g ();
}
procedure g()
{
print i;
}

Let x be the value printed under static scoping and y be the value printed under dynamic scoping. Then, x and y are:

A. x = 10, y = 20
B. x = 20, y = 10
C. x = 10, y = 10
D. x = 20, y = 20

gate2007-it programming variable-binding normal ugcnetdec2012iii

Answer ☟

Answers: Variable Binding

4.15.1 Variable Binding: GATE IT 2007 | Question: 34, UGCNET-Dec2012-III: 52 top☝ ☛ https://gateoverflow.in/3467

 In static scoping, the scope of an identifier is determined by its location in the code, and since that doesn't change,
the scope doesn't either. In dynamic scoping, the scope is determined by the sequence of calls that has led to the use of
an identifier, and since that can be different each time that use is reached, is dynamic.

© Copyright GATE Overflow. Some rights reserved.


4 Programming and DS: Programming (108) 533

So, here:
Option A must be the answer.
As, under static scoping : x = 10(global i)
under dynamic scoping : y = 20( according to the sequence of calls,i.e 20)
 20 votes -- sumit kumar singh dixit (1.6k points)

Answer Keys
4.1.1 A 4.2.1 C 4.2.2 C 4.2.3 C 4.2.4 2
4.2.5 6 4.2.6 19 4.2.7 C 4.2.8 C 4.2.9 B
4.2.10 C 4.2.11 B 4.3.1 A 4.3.2 A 4.4.1 N/A
4.4.2 C 4.4.3 3 4.4.4 B 4.5.1 N/A 4.5.2 N/A
4.5.3 N/A 4.5.4 N/A 4.5.5 A 4.5.6 B 4.5.7 C
4.5.8 C 4.6.1 N/A 4.6.2 C 4.6.3 B 4.6.4 D
4.6.5 B 4.6.6 D 4.6.7 6561 4.6.8 2016 4.6.9 30
4.6.10 A 4.6.11 D 4.6.12 C 4.7.1 D 4.7.2 D
4.7.3 A 4.7.4 A 4.7.5 C 4.7.6 D 4.7.7 140
4.7.8 D 4.7.9 D 4.8.1 B 4.9.1 A 4.9.2 B
4.9.3 B 4.9.4 B 4.9.5 D 4.9.6 C 4.9.7 D
4.9.8 A 4.9.9 D 4.9.10 C 4.9.11 C 4.9.12 D
4.9.13 B 4.9.14 D 4.9.15 -5 4.9.16 A 4.9.17 D
4.9.18 10 4.9.19 230 4.9.20 D 4.9.21 D 4.9.22 3
4.9.23 23 4.9.24 A 4.9.25 0 4.9.26 B 4.9.27 B
4.9.28 5 4.9.29 10 4.9.30 55 4.9.31 B 4.9.32 A
4.9.33 D 4.9.34 B 4.9.35 A 4.9.36 C 4.10.1 C
4.10.2 D 4.11.1 41 4.11.2 16 4.11.3 N/A 4.11.4 N/A
4.11.5 N/A 4.11.6 C 4.11.7 B 4.11.8 D 4.11.9 1.72 : 1.74
4.11.10 A 4.11.11 3 4.11.12 A 4.11.13 C 4.11.14 4
4.11.15 D 4.12.1 A 4.12.2 A 4.12.3 B 4.12.4 B
4.13.1 C 4.14.1 C 4.15.1 A

© Copyright GATE Overflow. Some rights reserved.

You might also like