Algorithm & Data Structures
Algorithm & Data Structures
Table of Contents
Table of Contents 1
Contributors 3
1 Algorithms (327) 4
1.1 Algorithm Design (8) 4
1.2 Algorithm Design Techniques (6) 5
1.3 Asymptotic Notations (20) 7
1.4 Dynamic Programming (12) 10
1.5 Graph Algorithms (48) 13
1.6 Graph Connectivity (1) 24
1.7 Greedy Algorithm (7) 24
1.8 Hashing (1) 26
1.9 Huffman Code (3) 26
1.10 Identify Function (38) 27
1.11 Minimum Maximum (4) 38
1.12 Minimum Spanning Trees (3) 38
1.13 P Np Npc Nph (12) 39
1.14 Quicksort (2) 42
1.15 Recurrence (37) 42
1.16 Searching (8) 50
1.17 Shortest Path (1) 52
1.18 Sorting (52) 52
1.19 Spanning Tree (31) 61
1.20 Time Complexity (33) 68
2 Compiler Design (186) 76
2.1 Abstract Syntax Tree (1) 76
2.2 Assembler (7) 76
2.3 Code Optimization (4) 77
2.4 Compilation Phases (8) 78
2.5 Expression Evaluation (2) 80
2.6 Grammar (41) 80
2.7 Infix Postfix (1) 89
2.8 Intermediate Code (8) 90
2.9 Left Recursion (1) 91
2.10 Lexical Analysis (6) 92
2.11 Linking (3) 93
2.12 Live Variable (1) 93
2.13 Macros (4) 94
2.14 Parameter Passing (13) 94
2.15 Parsing (48) 98
2.16 Register Allocation (2) 109
2.17 Runtime Environments (18) 110
2.18 Static Single Assignment (2) 113
2.19 Syntax Directed Translation (9) 114
2.20 Target Code Generation (4) 116
2.21 Variable Scope (2) 117
2.22 Viable Prefix (1) 118
3 Programming and DS: DS (212) 119
3.1 Abstract Data Type (1) 119
3.2 Arrays (13) 119
3.3 Binary Search Tree (29) 122
3.4 Binary Tree (56) 128
3.5 Graph Search (1) 138
3.6 Graphs (6) 139
3.7 Hashing (17) 140
3.8 Heap (25) 143
3.9 Infix Postfix (2) 148
3.10 Linked Lists (19) 148
Contributors
User , Answers User Added User Done
Arjun Suresh 7484, 215 Kathleen Bankson 447 kenzou 323
Praveen Saini 2352, 67 Jotheeswari 187 Milicevic3306 259
Gate Keeda 1449, 60 makhdoom ghaya 146 Naveen Kumar 134
Akash Kanase 935, 39 Ishrat Jahan 122 Arjun Suresh 96
Vikrant Singh 650, 17 Arjun Suresh 98 Lakshman Patel 52
Amar Vashishth 613, 21 gatecse 35 Shikha Mallick 51
Prashant Singh 601, 29 Rucha Shelke 30 Pooja Khatri 33
Bhagirathi Nayak 572, 21 Sandeep Singh 25 Krithiga2101 29
Rajarshi Sarkar 556, 28 Akash Kanase 24 Akash Dinkar 28
gatecse 555, 12 Madhav kumar 11 Ajay kumar soni 14
Pragy Agarwal 551, 17 khush tak 8 Subarna Das 10
Rajesh Pradhan 534, 21 Puja Mishra 7
Debashish Deka 515, 9 Manu Thakur 6
Digvijay 511, 27 srestha 6
Sankaranarayanan P.N 461, 20 Manoja Rajalakshmi 4
Pooja Palod 435, 18 Aravindakshan
Kalpna Bhargav 434, 11 Jotheeswari 4
Abhilash Panicker 288, 6
Ankit Rokde 282, 10
Umang Raman 276, 15
Manu Thakur 269, 10
Ahwan Mishra 265, 10
Sachin Mittal 260, 8
Anurag Semwal 258, 8
Monanshi Jain 230, 8
Mithlesh Upadhyay 228, 7
jayendra 220, 9
minal 215, 7
Himanshu Agarwal 210, 7
Anoop Sonkar 204, 6
srestha 204, 16
Sandeep_Uniyal 186, 7
Pc 175, 6
suraj 172, 6
sriv_shubham 170, 5
Aditi Dan 168, 5
ryan sequeira 160, 3
Srinath Jayachandran 157, 2
Keith Kr 155, 6
1 Algorithms (327)
Searching, Sorting, Hashing, Asymptotic worst case time and Space complexity, Algorithm design techniques: Greedy,
Dynamic programming, and Divide‐and‐conquer, Graph search, Minimum spanning trees, Shortest paths.
Mark Distribution in Previous GATE
Year 2019 2018 2017-1 2017-2 2016-1 2016-2 Minimum Average Maximum
1 Mark Count 2 0 2 2 3 3 0 2 3
2 Marks Count 2 4 2 3 2 3 2 2.7 4
Total Marks 6 8 6 8 7 9 6 7.3 9
Let T be a Depth First Tree of a undirected graph G. An array P indexed by the vertices of G is given. P [V ] is the
parent of vertex V , in T . Parent of the root is the root itself.
Give a method for finding and printing the cycle formed if the edge (u, v) of G not in T (i.e., e ∈ G − T ) is now added to T .
Time taken by your method must be proportional to the length of the cycle.
Describe the algorithm in a PASCAL (C) – like language. Assume that the variables have been suitably declared.
An array A contains n integers in locations A[0], A[1], … A[n − 1]. It is required to shift the elements of the array
cyclically to the left by K places, where 1 ≤ K ≤ n − 1 . An incomplete algorithm for doing this in linear time,
without using another array is given below. Complete the algorithm by filling in the blanks. Assume all variables are suitably
declared.
min:=n;
i=0;
while _____ do
begin
temp:=A[i];
j:=i;
while ____ do
begin
A[j]:=____;
j:=(j+K) mod n;
if j<min then
min:=j;
end;
A[(n+i-K)mod n]:=____;
i:=______;
end;
An element in an array X is called a leader if it is greater than all elements to the right of it in X . The best algorithm to
find all leaders in an array
Given two arrays of numbers a1 , . . . , an and b1 , . . . , bn where each number is 0 or 1, the fastest algorithm to find the
largest span (i, j) such that ai + ai+1 + ⋯ + aj = bi + bi+1 + ⋯ + bj or report that there is not such span,
There are 5 bags labeled 1 to 5. All the coins in a given bag have the same weight. Some bags have coins of weight 10
gm, others have coins of weight 11 gm. I pick 1, 2, 4, 8, 16 coins respectively from bags 1 to 5 Their total weight
comes out to 323 gm. Then the product of the labels of the bags having 11 gm coins is ___.
gate2014-1 algorithms numerical-answers normal algorithm-design
Consider a sequence of 14 elements: A = [−5, −10, 6, 3, −1, −2, 13, 4, −9, −1, 4, 12, −3, 0] . The sequence sum
S(i, j) = Σjk=i A[k]. Determine the maximum of S(i, j), where 0 ≤ i ≤ j < 14 . (Divide and conquer approach may
be used.)
Subsequence : A subsequence is a sequence that can be derived from another sequence by deleting some or no
Answer: elements without changing the order of the remaining elements.
___________
gate2019 numerical-answers algorithms algorithm-design
You are given ten rings numbered from 1 to 10, and three pegs labeled A, B, and C . Initially all the rings are on peg
A, arranged from top to bottom in ascending order of their numbers. The goal is to move all the rings to peg B in the
minimum number of moves obeying the following constraints:
Asha and Lata play a game in which Lata first thinks of a natural number between 1 and 1000. Asha must find out that
number by asking Lata questions, but Lata can only reply by saying “Yes” or “no”. Assume that Lata always tells the
truth. What is the least number of questions that Asha needs to ask within which she can always find out the number Lata has
thought of?
Consider the following problem. Given n positive integers a1 , a2 … an , it is required to partition them in to two parts
A and B such that
Consider a greedy algorithm for solving this problem. The numbers are ordered so that a1 ≥ a2 ≥ … an , and at ith step, ai is
placed in that part whose sum in smaller at that step. Give an example with n = 5 for which the solution produced by the
greedy algorithm is not optimal.
A. A-2 B-4 C-1 D-3 B. A-3 B-4 C-1 D-2 C. A-3 B-4 C-2 D-1 D. A-4 B-1 C-2 D-3
Given below are some algorithms, and some algorithm design paradigms.
Match the above algorithms on the left to the corresponding design paradigm they follow.
A. 1-i, 2-iii, 3-i, 4-v B. 1-iii, 2-iii, 3-i, 4-v
C. 1-iii, 2-ii, 3-i, 4-iv D. 1-iii, 2-ii, 3-i, 4-v
gate2015-2 algorithms easy algorithm-design-techniques
Match the algorithms to the design paradigms they are based on.
g2 (n) = {
n for 0 ≤ n ≤ 100
n3 for n > 100
Which of the following is true?
A. g1 (n) is O(g2 (n)) B. g1 (n) is O(n3 )
C. g2 (n) is O(g1 (n)) D. g2 (n) is O(n)
gate1994 algorithms asymptotic-notations normal
f(n) = 3n√n
g(n) = 2√nlog2 n
h(n) = n!
Let f(n) = n2 log n and g(n) = n(log n)10 be two positive functions of n. Which of the following statements is
correct?
A. f(n) = O(g(n)) and g(n) ≠ O(f(n)) B. g(n) = O(f(n)) and f(n) ≠ O(g(n))
C. f(n) ≠ O(g(n)) and g(n) ≠ O(f(n)) D. f(n) = O(g(n)) and g(n) = O(f(n))
Let f(n), g(n) and h(n) be functions defined for positive integers such that
f(n) = O(g(n)), g(n) ≠ O(f(n)), g(n) = O(h(n)), and h(n) = O(g(n)).
Which one of the following statements is FALSE?
A. f(n) + g(n) = O(h(n) + h(n)) B. f(n) = O(h(n))
C. h(n) ≠ O(f(n)) D. f(n)h(n) ≠ O(g(n)h(n))
gate2004-it algorithms asymptotic-notations normal
f(n) = 2n
g(n) = n!
h(n) = nlog n
Which of the following statements about the asymptotic behavior of f(n), g(n) and h(n) is true?
A. n 1/3 B. en
C. n 7/4 D. n log9 n
E. 1.0000001 n
A. a, d, c, e, b B. d, a, c, e, b
C. a, c, d, e, b D. a, c, d, b, e
gate2008-it algorithms asymptotic-notations normal
Which of the given options provides the increasing order of asymptotic complexity of functions f1 , f2 , f3 and f4 ?
f1 (n) = 2n
f2 (n) = n3/2
f3 (n) = n log2 n
f4 (n) = nlog2 n
A. f3 , f2 , f4 , f1 B. f3 , f2 , f1 , f4
C. f2 , f3 , f1 , f4 D. f2 , f3 , f4 , f1
gate2011 algorithms asymptotic-notations normal
Let W(n) and A(n) denote respectively, the worst case and average case running time of an algorithm executed on an
input of size n. Which of the following is ALWAYS TRUE?
A. A(n) = Ω(W (n)) B. A(n) = Θ(W (n))
C. A(n) = O(W (n)) D. A(n) = o(W (n))
gate2012 algorithms easy asymptotic-notations
n
Consider the equality ∑i3 = X and the following choices for X :
i=0
I. Θ(n4 )
II. Θ(n5 )
III. O(n5 )
IV. Ω(n3 )
Let f(n) = n and g(n) = n(1+sin n) , where n is a positive integer. Which of the following statements is/are correct?
I. f(n) = O(g(n))
II. f(n) = Ω(g(n))
10, √−
n , n, log2 n , 100 .
n
The CORRECT arrangement of the above functions in increasing order of asymptotic complexity is:
− −
A. log2 n , 100
n , 10, √n , n B. 100
n , 10, log2 n , √n , n
− −
C. 10, 100
n , √n , log2 n , n D. 100
n , log2 n , 10, √n , n
gate2017-1 algorithms asymptotic-notations normal
tifr2016 asymptotic-notations
Which of the following functions asymptotically grows the fastest as n goes to infinity?
A. (log log n)! B. (log log n)log n
C. (log log n)log log log n
D. (log n)log log n
E. 2√log log n
tifr2017 algorithms asymptotic-notations
Which of the following statements is TRUE for all sufficiently large integers n ?
√log log n √log log n
A. 22 < 2√log n < n B. 2√log n < n < 22
√log log n √log log n
√log n
C. n < 2 < 22 D. n < 22 < 2√log n
√log log n
E. 2√log n < 22 <n
tifr2018 asymptotic-notations
A. B.
C. D.
E.
tifr2019 algorithms asymptotic-notations
The subset-sum problem is defined as follows. Given a set of positive integers, , and
positive integer , is there a subset of whose elements sum to ? A dynamic program for solving this problem
uses a Boolean array, , with rows and columns. , is TRUE, if and
only if there is a subset of whose elements sum to .
Which of the following is valid for , and ?
A.
B.
C.
D.
The subset-sum problem is defined as follows. Given a set of positive integers, , and
positive integer , is there a subset of whose elements sum to ? A dynamic program for solving this problem
uses a Boolean array, , with rows and columns. , is TRUE, if and
only if there is a subset of whose elements sum to .
Which entry of the array , if TRUE, implies that there is a subset whose elements sum to ?
A. B. C. D.
gate2008 algorithms normal dynamic-programming
A sub-sequence of a given sequence is just the given sequence with some elements (possibly none or all) left out. We
are given two sequences and of lengths and , respectively with indexes of and starting from .
We wish to find the length of the longest common sub-sequence (LCS) of and as , where an incomplete
recursive definition for the function to compute the length of the LCS of and is given below:
l(i,j) = 0, if either i = 0 or j = 0
= expr1, if i,j > 0 and X[i-1] = Y[j-1]
= expr2, if i,j > 0 and X[i-1] ≠ Y[j-1]
A sub-sequence of a given sequence is just the given sequence with some elements (possibly none or all) left out. We
are given two sequences and of lengths and , respectively with indexes of and starting from .
We wish to find the length of the longest common sub-sequence (LCS) of and as , where an incomplete
recursive definition for the function to compute the length of the LCS of and is given below:
, if either or
if and
if and
The value of could be obtained by dynamic programming based on the correct recursive definition of of the form
given above, using an array , where and , such that .
Which one of the following statements would be TRUE regarding the dynamic programming solution for the recursive
definition of ?
A. B.
C. D.
gate2010 algorithms dynamic-programming normal
An algorithm to find the length of the longest monotonically increasing sequence of numbers in an array
is given below.
Let , denote the length of the longest monotonically increasing sequence starting at index in the array.
Initialize .
For all such that
A. B. C. D.
gate2011 algorithms dynamic-programming normal
Consider two strings ="qpqrr" and ="pqprqrp". Let be the length of the longest common subsequence (not
necessarily contiguous) between and and let be the number of such longest common subsequences between
and . Then ___.
Suppose you want to move from to on the number line. In each step, you either move right by a unit distance or
you take a shortcut. A shortcut is simply a pre-specified pair of integers . Given a shortcut , if you
are at position on the number line, you may directly move to . Suppose denotes the smallest number of steps needed to
move from to . Suppose further that there is at most shortcut involving any number, and in particular, from there is a
shortcut to . Let and be such that . Then the value of the product is _____.
A. Greedy paradigm.
B. Divide-and-conquer paradigm.
C. Dynamic Programming paradigm.
D. Neither Greedy nor Divide-and-Conquer nor Dynamic Programming paradigm.
Assume that multiplying a matrix of dimension with another matrix of dimension requires
scalar multiplications. Computing the product of matrices can be done by parenthesizing in
different ways. Define as an explicitly computed pair for a given paranthesization if they are directly multiplied. Fr
example, in the matrix multiplication chain using parenthesization and
are only explicitly computed pairs.
Consider a matrix multiplication chain , where matrices and are of dimensions
and , respectively. In the parenthesization of that minimizes the total
number of scalar multiplications, the explicitly computed pairs is/are Explicitly computed pairs is ( F3, F4)
A. and only B. only
C. only D. and only
gate2018 algorithms dynamic-programming
A. Optimal binary search tree construction can be performed efficiently using dynamic programming
B. Breadth-first search cannot be used to find connected components of a graph
C. Given the prefix and postfix walks over a binary tree, the binary tree cannot be uniquely constructed.
D. Depth-first search can be used to find connected components of a graph
An independent set in a graph is a subset of vertices such that no two vertices in the subset are connected by an edge.
An incomplete scheme for a greedy algorithm to find a maximum independent set in a tree is given below:
V: Set of all vertices in the tree;
I := ϕ
while V ≠ ϕ do
begin
select a vertex u ∊ V such that
_______;
V := V - {u};
if u is such that
________then I := I ∪ {u}
end;
Output(I);
a. Output the sequence of vertices identified by the Dijkstra’s algorithm for single source shortest path when the algorithm is
started at node
b. Write down sequence of vertices in the shortest path from to
c. What is the cost of the shortest path from to ?
Which one of the following algorithm design techniques is used in finding all pairs of shortest distances in a graph?
A. Dynamic programming B. Backtracking
C. Greedy D. Divide and Conquer
gate1998 algorithms graph-algorithms easy isro2008
is:
A. B.
C. D.
gate2000 algorithms easy graph-algorithms
Consider an undirected, unweighted graph . Let a breadth-first traversal of be done starting from a node . Let
and be the lengths of the shortest paths from to and respectively in . If is visited before
during the breadth-first traversal, which of the following statements is correct?
A. B.
C. D. None of the above
gate2001 algorithms graph-algorithms normal
Fill in the blanks in the following template of an algorithm to compute all pairs shortest path lengths in a directed graph
with adjacency matrix . equals if there is an edge in from to , and otherwise. Your aim in
filling in the blanks is to ensure that the algorithm is correct.
INITIALIZATION: For i = 1 ... n
{For j = 1 ... n
{ if a[i,j] = 0 then P[i,j] =_______ else P[i,j] =_______;}
}
}
}
a. Copy the complete line containing the blanks in the Initialization step and fill in the blanks.
b. Copy the complete line containing the blanks in the Algorithm step and fill in the blanks.
c. Fill in the blank: The running time of the Algorithm is (___).
I. abeghf
II. abfehg
III. abfhge
IV. afghbe
A. I, II and IV only B. I and IV only C. II, III and IV only D. I, III and IV only
gate2003 algorithms graph-algorithms normal
A single-source shortest path algorithm is executed on the weighted graph with an arbitrary vertex of as the
source. Which of the following can always be inferred from the path costs computed?
for i=1 to n
for j=1 to n
for k=1 to n
A[j,k] = max(A[j,k], A[j,i] + A[i,k]);
Which of the following statements is necessarily true for all and after termination of the above algorithm?
A.
B. If then has a Hamiltonian cycle
C. If there exists a path from to , contains the longest path length from to
D. If there exists a path from to , every simple path from to contains at most edges
Suppose we run Dijkstra’s single source shortest path algorithm on the following edge-weighted directed graph with
vertex as the source.
In what order do the nodes get included into the set of vertices for which the shortest path distances are finalized?
A. B. C. D.
gate2004 algorithms graph-algorithms normal
Let and be connected graphs on the same vertex set with more than two vertices. If
is not a connected graph, then the graph
Using Prim's algorithm to construct a minimum spanning tree starting with node A, which one of the following sequences of
edges represents a possible order in which the edges would be added to construct the minimum spanning tree?
A.
B.
C.
D.
Let be an undirected graph with positive edge weights. Dijkstra’s single source shortest path algorithm can
be implemented using the binary heap data structure with time complexity:
A. B.
C. D.
gate2005 algorithms graph-algorithms normal
Let and be two vertices in a undirected graph having distinct positive edge weights. Let be a
partition of such that and . Consider the edge having the minimum weight amongst all those edges
that have one vertex in and one vertex in .
The edge must definitely belong to:
A. the minimum weighted spanning tree of B. the weighted shortest path from to
C. each path from to D. the weighted longest path from to
gate2005 algorithms graph-algorithms normal
Let and be two vertices in a undirected graph having distinct positive edge weights. Let be a
partition of such that and . Consider the edge having the minimum weight amongst all those edges
that have one vertex in and one vertex in .
Let the weight of an edge denote the congestion on that edge. The congestion on a path is defined to be the maximum of the
congestions on the edges of the path. We wish to find the path from to having minimum congestion. Which of the
following paths is always such a path of minimum congestion?
A. a path from to in the minimum weighted spanning tree B. a weighted shortest path from to
C. an Euler walk from to D. a Hamiltonian path from to
gate2005 algorithms graph-algorithms normal
In a depth-first traversal of a graph with vertices, edges are marked as tree edges. The number of connected
components in is
A. B. C. D.
gate2005-it algorithms graph-algorithms normal
In the following table, the left column contains the names of standard graph algorithms and the right column contains
the time complexities of the algorithms. Match each algorithm with its time complexity.
A. B.
C. D.
gate2005-it algorithms graph-algorithms normal
A sink in a directed graph is a vertex i such that there is an edge from every vertex to and there is no edge from
to any other vertex. A directed graph with vertices is represented by its adjacency matrix , where if
there is an edge directed from vertex to and otherwise. The following algorithm determines whether there is a sink in the
graph .
i = 0;
do {
j = i + 1;
while ((j < n) && E1) j++;
if (j < n) E2;
} while (j < n);
flag = 1;
for (j = 0; j < n; j++)
if ((j! = i) && E3) flag = 0;
if (flag) printf("Sink exists");
else printf ("Sink does not exist");
A sink in a directed graph is a vertex i such that there is an edge from every vertex to and there is no edge from
to any other vertex. A directed graph with vertices is represented by its adjacency matrix , where if
there is an edge directed from vertex to and otherwise. The following algorithm determines whether there is a sink in the
graph .
i = 0;
do {
j = i + 1;
while ((j < n) && E1) j++;
if (j < n) E2;
} while (j < n);
flag = 1;
for (j = 0; j < n; j++)
if ((j! = i) && E3) flag = 0;
if (flag) printf("Sink exists") ;
else printf ("Sink does not exist");
To implement Dijkstra’s shortest path algorithm on unweighted graphs so that it runs in linear time, the data structure
to be used is:
Let be a depth first search tree in an undirected graph . Vertices and are leaves of this tree . The degrees of
both and in are at least . which one of the following statements is true?
Which of the following is the correct decomposition of the directed graph given below into its strongly connected
components?
A.
B.
C.
D.
Consider the depth-first-search of an undirected graph with vertices , , and . Let discovery time represent
the time instant when the vertex is first visited, and finish time represent the time instant when the vertex is
last visited. Given that
In an unweighted, undirected connected graph, the shortest path from a node to every other node is computed most
efficiently, in terms of time complexity, by
A. Dijkstra’s algorithm starting from . B. Warshall’s algorithm.
C. Performing a DFS starting from . D. Performing a BFS starting from .
gate2007 algorithms graph-algorithms easy
A. B. C. D.
gate2007 algorithms graph-algorithms
A depth-first search is performed on a directed acyclic graph. Let denote the time at which vertex is visited for
the first time and the time at which the DFS call to the vertex terminates. Which of the following statements is
always TRUE for all edges in the graph ?
A. B.
C. D.
gate2007-it algorithms graph-algorithms normal
Consider a weighted, undirected graph with positive edge weights and let be an edge in the graph. It is known that
the shortest path from the source vertex to has weight 53 and the shortest path from to has weight 65. Which
one of the following statements is always TRUE?
A. Weight B. Weight
C. Weight D. Weight
gate2007-it algorithms graph-algorithms normal ugcnetjune2012iii
The Breadth First Search algorithm has been implemented using the queue data structure. One possible order of visiting
the nodes of the following graph is:
A. B. C. D.
gate2008 normal algorithms graph-algorithms
Dijkstra's single source shortest path algorithm when run from vertex in the above graph, computes the correct shortest path
distance to
A. only vertex B. only vertices
C. only vertices D. all the vertices
gate2008 algorithms graph-algorithms normal
The most efficient algorithm for finding the number of connected components in an undirected graph on vertices and
edges has time complexity
A. B. C. D.
gate2008 algorithms graph-algorithms time-complexity normal
Consider the following sequence of nodes for the undirected graph given below:
1.
2.
3.
4.
A Depth First Search (DFS) is started at node . The nodes are listed in the order they are first visited. Which of the above
is/are possible output(s)?
Which of the following statement(s) is/are correct regarding Bellman-Ford shortest path algorithm?
P: Always finds a negative weighted cycle, if one exists.
Q: Finds whether any negative weighted cycle is reachable from the source.
Consider the directed graph shown in the figure below. There are multiple shortest paths between vertices and .
Which one will be reported by Dijkstra’s shortest path algorithm? Assume that, in any iteration, the shortest path to a
vertex is updated only when a strictly shorter path to is discovered.
A. B. C. D.
gate2012 algorithms graph-algorithms normal
What is the time complexity of Bellman-Ford single-source shortest path algorithm on a complete graph of n vertices?
A. B.
C. D.
gate2013 algorithms graph-algorithms normal
Let be a graph with vertices and [Link] is the tightest upper bound on the running time of Depth First
Search on , when is represented as an adjacency matrix?
A. B. C. D.
Consider the tree arcs of a BFS traversal from a source node in an unweighted, connected, undirected graph. The
tree formed by the tree arcs is a data structure for computing
Suppose depth first search is executed on the graph below starting at some unknown vertex. Assume that a recursive
call to visit a vertex is made only after first checking that the vertex has not been visited earlier. Then the maximum
possible recursion depth (including the initial call) is _________.
Let be a simple undirected graph, and be a particular vertex in it called the source. For , let
denote the shortest distance in from to . A breadth first search (BFS) is performed starting at . Let be the
resultant BFS tree. If is an edge of that is not in , then which one of the following CANNOT be the value of
?
A. B. C. D.
gate2015-1 algorithms graph-algorithms normal
The number of different topological orderings of the vertices of the graph is _____________.
Breadth First Search (BFS) is started on a binary tree beginning from the root vertex. There is a vertex at a distance
four from the root. If is the vertex in this BFS traversal, then the maximum possible value of is __________
gate2016-2 algorithms graph-algorithms normal numerical-answers
In an adjacency list representation of an undirected simple graph , each edge has two adjacency list
entries: in the adjacency list of , and in the adjacency list of . These are called twins of each other. A twin
pointer is a pointer from an adjacency list entry to its twin. If and , and the memory size is not a constraint,
what is the time complexity of the most efficient algorithm to set the twin pointer in each entry in each adjacency list?
A. B.
C. D.
gate2016-2 algorithms graph-algorithms normal
Let be connected, undirected, edge-weighted graph. The weights of the edges in are positive and
distinct. Consider the following statements:
The Breadth First Search (BFS) algorithm has been implemented using the queue data structure. Which one of the
following is a possible order of visiting the nodes in the graph below?
A. B. C. D.
gate2017-2 algorithms graph-algorithms
Let be an undirected graph. Consider a depth-first traversal of , and let be the resulting depth-first search tree.
Let be a vertex in and let be the first new (unvisited) vertex visited after visiting in the traversal. Which of the
following statement is always true?
Given a weighted directed graph with vertices where edge weights are integers (positive, zero, or negative),
determining whether there are paths of arbitrarily large weight can be performed in time
A. B. but not
C. but not D. but not
E. but not
tifr2013 algorithms graph-algorithms
Suppose a depth-first traversal of this graph is performed, assuming that whenever there is a choice, the vertex earlier in the
alphabetical order is to be chosen. Suppose the number of tree edges is , the number of back edges is and the number of
cross edges is . Then
a. , , and . b. , , and .
c. , , and . d. , , and .
e. , , and .
tifr2014 algorithms graph-algorithms
Let be a graph with 100! vertices, with each vertex labelled by a distinct permutation of the numbers
There is an edge between vertices and if and only if the label of can be obtained by swapping two adjacent
numbers in the label of . Let denote the degree of a vertex in , and denote the number of connected components in .
Then, = ____
gate2018 algorithms graph-algorithms graph-connectivity numerical-answers
The minimum number of record movements required to merge five files A (with records), B (with records), C
(with records), D (with records) and E (with records) is:
A. B. C. D.
gate1999 algorithms normal greedy-algorithm
The following are the starting and ending times of activities and respectively in chronological
order: . Here, denotes the starting time and denotes the ending
time of activity X. We need to schedule the activities in a set of rooms available to us. An activity can be scheduled in a room
only if the room is reserved for the activity for its entire duration. What is the minimum number of rooms required?
A. B. C. D.
gate2003 algorithms normal greedy-algorithm
We are given tasks . The execution of each task requires one unit of time. We can execute one task at a
time. Each task has a profit and a deadline . Profit is earned if the task is completed before the end of the
unit of time.
Are all tasks completed in the schedule that gives maximum profit?
A. All tasks are completed B. and are left out
C. and are left out D. and are left out
gate2005 algorithms greedy-algorithm process-schedule normal
We are given tasks . The execution of each task requires one unit of time. We can execute one task at a
time. Each task has a profit and a deadline . Profit is earned if the task is completed before the end of the
unit of time.
A. B. C. D.
gate2005 algorithms greedy-algorithm process-schedule normal
The characters to have the set of frequencies based on the first Fibonacci numbers as follows
, , , , , , ,
A Huffman code is used to represent the characters. What is the sequence of characters corresponding to the following code?
A. B. C. D.
gate2006-it algorithms greedy-algorithm normal
Consider the weights and values of items listed below. Note that there is only one unit of each item.
The task is to pick a subset of these items such that their total weight is no more than Kgs and their total value is
maximized. Moreover, no item may be split. The total value of items picked by an optimal algorithm is denoted by .A
greedy algorithm sorts the items by their value-to-weight ratios in descending order and packs them greedily, starting from the
first item in the ordered list. The total value of items picked by the greedy algorithm is denoted by .
i. What is the worst-case timing complexity of inserting elements into such a table?
ii. For what type of instance does this hashing scheme take the worst-case time for insertion?
A language uses an alphabet of six letters, . The relative frequency of use of each letter of the alphabet
in the language is as given below:
Design a prefix binary code for the language which would minimize the average length of the encoded words of the language.
descriptive gate1989 algorithms huffman-code
What is the average length of the Huffman code for the letters ?
A. B. C. D.
gate2007 algorithms greedy-algorithm normal huffman-code
A message is made up entirely of characters from the set . The table of probabilities for each of
the characters is shown below:
If a message of characters over is encoded using Huffman coding, then the expected length of the encoded message in
bits is ______.
gate2017-2 huffman-code numerical-answers algorithms
What is the output produced by the following program, when the input is "HTGATE"
Function what (s:string): string;
var n:integer;
begin
n = [Link]
if n <= 1
then what := s
else what :=contact (what (substring (s, 2, n)), s.C [1])
end;
Note
i. type string=record
length:integer;
C:array[1..100] of char
end
ii. Substring (s, i, j): this yields the string made up of the through characters in s; for appropriately defined in and .
iii. Contact : this function yields a string of length length + - length obtained by concatenating with such
that precedes .
The following program computes values of a mathematical function . Determine the form of .
main ()
{
int m, n; float x, y, t;
scanf ("%f%d", &x, &n);
t = 1; y = 0; m = 1;
do
{
t *= (-x/m);
y += t;
} while (m++ < n);
printf ("The value of y is %f", y);
}
Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Consider the following Pascal function:
Function X(M:integer):integer;
Var i:integer;
Begin
i := 0;
while i*i < M
do i:= i+1
X := i
end
A. B.
C. D.
E. None of the above
gate1991 algorithms easy identify-function
In the following Pascal program segment, what is the value of X after the execution of the program segment?
X := -10; Y := 20;
If X > Y then if X < 0 then X := abs(X) else X := 2*X;
A. B. C. D. None
gate1995 algorithms identify-function easy
Assume that and are non-zero positive integers. What does the following Pascal program segment do?
while X <> Y do
if X > Y then
X := X - Y
else
Y := Y - X;
write(X);
A. Computes the LCM of two numbers B. Divides the larger number by the smaller number
C. Computes the GCD of two numbers D. None of the above
gate1995 algorithms identify-function normal
a. Consider the following Pascal function where and are non-zero positive integers. What is the value of ?
function GET(A,B:integer): integer;
begin
if B=0 then
GET:= 1
else if A < B then
GET:= 0
else
GET:= GET(A-1, B) + GET(A-1, B-1)
end;
b. The Pascal procedure given for computing the transpose of an matrix of integers has an error. Find
the error and correct it. Assume that the following declaration are made in the main program
const
MAXSIZE=20;
type
INTARR=array [1..MAXSIZE,1..MAXSIZE] of integer;
Procedure TRANSPOSE (var A: INTARR; N : integer);
var
I, J, TMP: integer;
begin
for I:=1 to N – 1 do
for J:=1 to N do
begin
TMP:= A[I, J];
A[I, J]:= A[J, I];
A[J, I]:= TMP
end
end;
What value would the following function return for the input ?
Function fun (x:integer):integer;
Begin
If x > 100 then fun = x – 10
Else fun = fun(fun (x+11))
End;
A. B. C. D.
gate1998 algorithms recursion identify-function normal
Suppose you are given an array and a procedure reverse which reverses the order of elements in
between positions and (both inclusive). What does the following sequence do, where :
reverse (s, 1, k);
reverse (s, k+1, n);
reverse (s, 1, n);
A. B. C. D.
gate2003 algorithms identify-function normal
In the following program fragment, , , and TwoLog_n are integer variables, and is an array of integers. The
variable is initialized to an integer , and TwoLog_n is initialized to the value of
for (k = 3; k <= n; k++)
A[k] = 0;
for (k = 2; k <= TwoLog_n; k++)
for (j = k+1; j <= n; j++)
A[j] = A[j] || (j%k);
for (j = 3; j <= n; j++)
if (!A[j]) printf("%d", j);
x = m;
y = 1;
While (x-y > ϵ)
{
x = (x+y)/2;
y = m/x;
}
print(x);
A. B. C. D.
gate2004 algorithms identify-function normal
int main() {
int a = 2048, sum = 0;
foo(a, sum);
printf("%d\n", sum);
}
int main () {
printf("%d", f(20, 1));
return 0;
}
A. B. C. D.
gate2005-it algorithms identify-function normal
Consider the following algorithm in which , , and are Boolean arrays of size :
algorithm zzz(x[], y[], z[]) {
int i;
for(i=0; i<n; ++i)
z[i] = (x[i] ∧ ~y[i]) ∨ (~x[i] ∧ y[i]);
}
A. B. C. D.
gate2006 algorithms identify-function normal
Consider the following C-function in which and are two sorted integer arrays and be another
integer array,
void xyz(int a[], int b [], int c []){
int i,j,k;
i=j=k=0;
while ((i<n) && (j<m))
if (a[i] < b[j]) c[k++] = a[i++];
else c[k++] = b[j++];
}
Which of the following condition(s) hold(s) after the termination of the while loop?
i. and if
ii. and if
The following function computes the value of correctly for all legal values and ( and )
int func(int m, int n)
{
if (E) return 1;
else return(func(m -1, n) + func(m - 1, n - 1));
}
In the above function, which of the following is the correct expression for E?
A. B. &&
C. D. &&
gate2006-it algorithms identify-function normal
A. B. C. D.
gate2008-it algorithms recursion identify-function normal
void f (int n)
{
if (n <= 1) {
printf ("%d", n);
}
else {
f (n/2);
printf ("%d", n%2);
}
}
Which of the following implementations will produce the same output for as the above code?
P1 P2
void f (int n)
{
void f (int n)
if (n <=1) {
{
printf ("%d", n);
if (n/2) {
}
f(n/2);
else {
}
printf ("%d", n%2);
printf ("%d", n%2);
f (n/2);
}
}
}
int main() {
int x = 15;
printf("%d/n", fun(5, &x));
return 0;
}
A. B. C. D.
gate2009 algorithms recursion identify-function normal
int main()
{
int a[] = (12, 7, 13, 4, 11, 6);
printf("%d", f(a, 6));
return 0;
}
A. B. C. D.
gate2010 algorithms recursion identify-function normal
A. B. C. D.
gate2011 algorithms recursion identify-function normal
A. B. C. D.
gate2011 algorithms recursion identify-function normal
int i, j, k=0;
for (i=n/2; i<=n; i++)
for (j=2; j<=n; j=j*2)
k = k + n/2;
return (k);
A. B.
C. D.
gate2013 algorithms identify-function normal
Consider the following C function in which size is the number of elements in the array E:
int MyX(int *E, unsigned int size)
{
int Y = 0;
int Z;
int i, j, k;
Let be the square matrix of size . Consider the following pseudocode. What is the expected output?
C=100;
for i=1 to n do
for j=1 to n do
{
Temp = A[i][j]+C;
A[i][j] = A[j][i];
A[j][i] = Temp -C;
}
for i=1 to n do
for j=1 to n do
output (A[i][j]);
Which one of the following most closely approximates the return value of the function fun1?
A. B. C. D.
gate2015-1 algorithms normal identify-function
Suppose is an array of length , where all the entries are from the set . For any positive
integers , consider the following pseudocode.
DOSOMETHING (c, a, n)
for
do
if c[i]=1
then
return z
If , then the output of DOSOMETHING( c, a, n) is _______.
Which one of the following will happen when the function convert is called with any positive integer as argument?
Consider the following program operating on four variables , and two constants and .
x, y, u, v:= X, Y, Y, X;
While (x ≠ y)
do
if (x > y) then x, v := x - y, v + u;
else if (y > x) then y, u:= y - x, u + v;
od;
print ((x + y) / 2); print ((u + v) / 2);
A. The program prints and the first prime larger than both and .
B. The program prints followed by .
C. The program prints followed by .
D. The program prints followed by .
E. The program does none of the above.
while ( n ! = 0 )
n = n & ( n-1 )
count = count + 1
return count
Here is meant to be an unsigned integer. The operator & considers its arguments in binary and computes their bit wise
. For example, & gives , because the binary (say 8-bit) representation of is and the binary
representation of is , and the bit-wise of these binary strings is , which is the binary
representation of . What does the function return?
Consider the following game. There is a list of distinct numbers. At any round, a player arbitrarily chooses two
numbers from the list and generates a new number by subtracting the smaller number from the larger one. The
numbers and are put back in the list. If the number is non-zero and is not yet in the list, is added to the list. The player
is allowed to play as many rounds as the player wants. The score of a player at the end is the size of the final list.
Suppose at the beginning of the game the list contains the following numbers: and . What is the score of
the best player for this game?
A. B. C. D. E.
tifr2014 algorithms identify-function
Which of the following statements about the contents of matrix at the end of this program must be TRUE?
C. all elements above the diagonal have their values decreased by and all the values below have their values increased by
The minimum number of comparisons required to find the minimum and the maximum of numbers is ________
Given a set of distinct numbers, we would like to determine both the smallest and the largest number. Which of the
following statements is TRUE?
Consider the problem of computing the minimum of a set of distinct numbers. We choose a permutation uniformly at
random (i.e., each of the n! permutations of is chosen with probability and we inspect the numbers
in the order given by this permutation. We maintain a variable MIN that holds the minimum value seen so far. MIN is
initialized to and if we see a value smaller than MIN during our inspection, then MIN is updated. For example, in the
inspection given by the following sequence, MIN is updated four times.
A. B. C. D. E.
tifr2014 algorithms minimum-maximum
Given a set of distinct numbers, we would like to determine the smallest three numbers in this set using comparisons.
Which of the following statements is TRUE?
Choose a value for that will maximize the number of minimum weight spanning trees (MWSTs) of . The number of
MWSTs of for this value of is ____.
Let and let be a simple, connected, undirected graph with the same number of vertices and edges. Each
edge of has a distinct real weight associated with it. Let be the minimum weight spanning tree of Which of the
following statements is NOT ALWAYS TRUE ?
How many distinct minimum weight spanning trees does the following undirected, weighted graph have ?
Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Which of the following problems is not -hard?
a. Hamiltonian circuit problem b. The Knapsack problem
c. Finding bi-connected components of a d. The graph coloring problem
graph
gate1992 p-np-npc-nph algorithms
Ram and Shyam have been asked to show that a certain problem is NP-complete. Ram shows a polynomial time
reduction from the -SAT problem to , and Shyam shows a polynomial time reduction from to -SAT. Which of
the following can be inferred from these reductions?
A. is NP-hard but not NP-complete B. is in NP, but is not NP-complete
C. is NP-complete D. is neither NP-hard, nor in NP
gate2003 algorithms p-np-npc-nph normal
Let S be an NP-complete problem and Q and R be two other problems not known to be in NP. Q is polynomial time
reducible to S and S is polynomial-time reducible to R. Which one of the following statements is true?
A. R is NP-complete B. R is NP-hard
C. Q is NP-complete D. Q is NP-hard
gate2006 algorithms p-np-npc-nph normal isrodec2017
The subset-sum problem is defined as follows: Given a set of positive integers and a positive integer , determine
whether there is a subset of whose elements sum to . An algorithm solves this problem in time. Which
of the following statements is false?
A. solves the subset-sum problem in polynomial time when the input is encoded in unary
B. solves the subset-sum problem in polynomial time when the input is encoded in binary
C. The subset sum problem belongs to the class NP
D. The subset sum problem is NP-hard
A.
B. Every problem in is polynomial time reducible to .
C. Every problem in is polynomial time reducible to .
D. The Hamilton cycle problem is polynomial time reducible to .
E. and .
Given an integer , consider the problem of determining if there exist integers such that . Call
this the forward problem. The reverse problem is: given and , compute (mod b). Note that the input length for the
forward problem is , while the input length for the reverse problem is . Which of the
following statements is TRUE?
a. Both the forward and reverse problems can be solved in time polynomial in the lengths of their respective inputs.
b. The forward problem can be solved in polynomial time, however the reverse problem is -hard.
c. The reverse problem can be solved in polynomial time, however the forward problem is -hard.
d. Both the forward and reverse problem are -hard.
e. None of the above.
This question concerns the classes and If you are familiar with them, you may skip the definitions and go
directly to the question.
Let be a set. We say that is in if there is some algorithm which given input decides if is in or not in time bounded
by a polynomial in the length of For example, the set of all connected graphs is in because there is an algorithm which,
given a graph graph, can decide if it is connected or not in time roughly proportional to the number of edges of the graph.
The class is a superset of class It contains those sets that have membership witnesses that can be verified in polynomial
time. For example, the set of composite numbers is in To see this take the witness for a composite number to be one of its
divisors. Then the verification process consists of performing just one division using two reasonable size numbers. Similarly,
the set of those graphs that have a Hamilton cycle, i.e. a cycle containing all the vertices of the graph, is in in To verify
that the graph has a Hamilton cycle we just check if the witnessing sequence of vertices indeed a cycle of the graph that passes
through all the vertices of the graph. This can be done in time that is polynomial in the size of the graph.
More precisely, if is a set in consisting of elements of the form then the set
is in N P .
Let be a graph. is said to have perfect matching if there is a subset of the edges of so that
Let be the set of all graphs that have a perfect matching. Let be the set of graphs that do not have a
perfect matching. Let be the number of components of that have an odd number of vertices.
Tutte’s Theorem: if and only if for all subsets of the number of components in (the graph formed
by deleting the vertices in with an odd number of vertices is at most That is,
A. B.
C. D.
E. none of the above
tifr2012 algorithms p-np-npc-nph
A multivariate polynomial in variables with integer coefficients has a binary root if it is possible to assign each
variable either 0 or 1, so that the polynomial evaluates to 0. For example, the multivariate polynomial
has the binary root . Then determining whether a multivariate polynomial, given as the
sum of monimials, has a binary root:
A. is trivial: every polynomial has a B. can be done in polynomial time
binary root
C. is NP-hard, but not in NP D. is in NP, but not in P and not NP-hard
E. is both in NP and NP-hard
tifr2017 algorithms p-np-npc-nph
Which of the above statements is/are TRUE? Choose from the following options.
A. Only i and ii B. Only ii and iv C. Only ii, iii, and iv D. Only i, ii and iv E. All of them
tifr2017 algorithms p-np-npc-nph
A formula is said to be a -CF-formula if it is a conjunction (i.e., an AND) of clauses, and each clause has at most
literals. Analogously, a formula is said to be a -DF-formula if it is a disjunction (i.e., an OR) of clauses of at most
literals each.
Define the languages -CF-SAT and -DF-SAT as follows:
Which of the following best represents our current knowledge of these languages ?
An array of distinct elements is to be sorted using quicksort. Assume that the pivot element is chosen uniformly at
random. The probability that the pivot element gets placed in the worst possible location in the first round of
partitioning (rounded off to decimal places) is ________
gate2019 numerical-answers algorithms quicksort probability
Consider the recursive quicksort algorithm with "random pivoting". That is, in each recursive call, a pivot is chosen
uniformly at random from the sub-array being [Link] this randomized algorithm is applied to an array of size
all whose elements are distinct, what is the probability that the smallest and the largest elements in the array are compared
during a run of the algorithm ?
A. B. C. D. E.
Express in terms of the harmonic number , where satisfies the recurrence relation,
, for and
Let be the number of times the ‘if…then…’ statement gets executed when the algorithm is run with value . Set up the
recurrence relation by defining in terms of . Solve for .
The recurrence relation that arises in relation with the complexity of binary search is:
A. B.
C. D.
gate1994 algorithms recurrence easy isro2017
Use the recurrence relation to answer the following questions. Assume that are
positive integers. Write only the answers without any explanation.
A. B.
C. D.
gate1999 algorithms recurrence asymptotic-notations normal
A. B. C. D.
gate2002 algorithms recurrence normal
A. B. C. D.
gate2002 algorithms recurrence normal
for all
The value of for is
A. B.
C. D.
gate2003 algorithms time-complexity recurrence difficult
A. B. C. D.
gate2004 algorithms recurrence time-complexity normal isro2015
evaluates to
A. B. C. D.
gate2004 algorithms recurrence normal
Consider a list of recursive algorithms and a list of recurrence relations as shown below. Each recurrence relation
corresponds to exactly one algorithm and is used to derive the time complexity of the algorithm.
Which of the following is the correct match between the algorithms and their recurrence relations?
A. B.
C. D.
gate2004-it algorithms recurrence normal
Suppose ,
Which one of the following is FALSE?
A. B.
C. D.
gate2005 algorithms asymptotic-notations recurrence normal
Let denote the number of binary strings of length that contain no consecutive 0s.
Which of the following recurrences does satisfy?
A. B.
C. D.
Let denote the number of binary strings of length that contain no consecutive 0s.
The value of is
A. B. C. D.
gate2008 algorithms recurrence normal
Which one of the following represents the time complexity of the algorithm?
A. B.
C. D.
gate2009 algorithms recurrence time-complexity normal
The recurrence relation capturing the optimal execution time of the problem with discs is
A. B.
C. D.
gate2012 algorithms easy recurrence
Which one of the following correctly determines the solution of the recurrence relation with ?
A. B. C. D.
gate2014-2 algorithms recurrence normal
Which one of the following is the recurrence equation for the worst case time complexity of the quick sort algorithm for
sorting ( 2) numbers? In the recurrence equations given in the options below, is a constant.
A. B.
C. D.
gate2015-1 algorithms recurrence sorting easy
Let a represent the number of bit strings of length n containing two consecutive s. What is the recurrence relation for
?
A. B.
C. D.
gate2015-1 algorithms recurrence normal
If function is being called in then how many times will the function be invoked before returning to the
?
A. B. C. D.
gate2015-3 algorithms recurrence normal
The given diagram shows the flowchart for a recursive function . Assume that all statements, except for the
recursive calls, have time complexity. If the worst case time complexity of this function is , then the least
possible value (accurate up to two decimal positions) of is ________.
Flow chart for Recursive Function .
A. B.
C. D.
gate2017-2 algorithms recurrence
a. is when . b. is when .
c. is when . d. is when .
e. is when .
tifr2014 algorithms recurrence
a. is .
b. is but not .
c. is but not .
d. is but not .
e. is but not .
Let be the function with two arguments (both nonnegative integral powers of 2) defined by the following
reccurence:
;
.
What is ?
A. B.
C. D.
E. if , otherwise
tifr2017 algorithms recurrence
Which of the following functions, given by there recurrence, grows the fastest asymptotically ?
Consider the following program that attempts to locate an element in an array using binary search. Assume
. The program is erroneous. Under what conditions does the program fail?
var i,j,k: integer; x: integer;
a: array; [1..N] of integer;
begin i:= 1; j:= n;
repeat
k:(i+j) div 2;
if a[k] < x then i:= k
else j:= k
until (a[k] = x) or (i >= j);
if (a[k] = x) then
writeln ('x is in the array')
else
writeln ('x is not in the array')
end;
The average number of key comparisons required for a successful search for sequential search on items is
Consider the following algorithm for searching for a given number in an unsorted array having distinct
values:
Assuming that is present in , what is the expected number of comparisons made by the algorithm before it terminates?
A. B. C. D.
gate2002 searching normal
Consider the following C program that attempts to locate an element in an array using binary search. The
program is erroneous.
f (int Y[10] , int x) {
int u, j, k;
i= 0; j = 9;
do {
k = (i+ j) / 2;
if( Y[k] < x) i = k;else j = k;
} while (Y[k] != x) && (i < j)) ;
if(Y[k] == x) printf(" x is in the array ") ;
else printf(" x is not in the array ") ;
}
A. is and
B. is and
C. is and
D. is and and is even
Consider the following C program that attempts to locate an element in an array using binary search. The
program is erroneous.
f (int Y[10] , int x) {
int u, j, k;
i= 0; j = 9;
do {
k = (i+ j) / 2;
if( Y[k] < x) i = k;else j = k;
} while (Y[k] != x) && (i < j)) ;
if(Y[k] == x) printf(" x is in the array ") ;
else printf(" x is not in the array ") ;
}
Let be an array of numbers consisting of a sequence of 's followed by a sequence of 's. The problem is to find
the smallest index such that is by probing the minimum number of locations in . The worst case number of
probes performed by an optimal algorithm is ____________.
A. Sort the array using quick-sort and then use binary search.
B. Merge the sorted lists and perform binary search.
C. Perform a single binary search on the entire array.
D. Perform separate binary searches on the odd positions and the even positions.
E. Search sequentially from the end of the array.
tifr2010 searching
Consider the following three version of the binary search program. Assume that the elements of type can be
compared with each other; also assume that the array is sorted.
i, j, k : integer;
a : array [1....N] of T;
x : T;
Program 1 : i := 1; j := N;
repeat
k := (i + j) div 2;
if a[k] < x then i := k else j := k
until (a[k] = x) or (i > j)
Program 2 : i := 1; j := N;
repeat
k := (i + j) div 2;
if x < a[k] then j := k - 1;
if a[k] < x then i := k + 1;
until i > j
Program 3 := i := 1; j := N
repeat
k := (i + j) div 2;
if x < a[k] then j := k else i := k + 1
until i > j
A binary search program is called correct provided it terminates with whenever such an element exists, or it
terminates with if there exists no array element with value . Which of the following statements is correct?
Let be a DIRECTED graph, where each edge has a positive weight and all vertices can be
reached from vertex For each vertex let be the length of the shortest path from to Let be
a new weighted graph with the same vertices and edges, but with the edge weight of every edge changed to
Let be a path from to a vertex and let and
Let be a quicksort program to sort numbers in ascending order. Let and be the time taken by the program for
the inputs and , respectively. Which of the following holds?
A. B.
C. D.
gate1987 algorithms sorting
i. Sort the input file using QUICKSORT by correctly positioning the first element of the file/subfile. Show the subfiles
obtained at all intermediate steps. Use square brackets to demarcate subfiles.
ii. Sort the input file using 2-way- MERGESORT showing all major intermediate steps. Use square brackets to demarcate
subfiles.
The minimum number of comparisons required to sort elements is ____ minimum number of comparison= (log n!)
gate1991 normal algorithms sorting
Give an optimal algorithm in pseudo-code for sorting a sequence of numbers which has only distinct numbers ( is
not known a Priori). Give a brief analysis for the time-complexity of your algorithm.
gate1991 sorting time-complexity algorithms difficult
Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Assume that the last element of the set is used as partition element in Quicksort. If distinct elements from the set
are to be sorted, give an input for which Quicksort takes maximum time.
For merging two sorted lists of sizes and into a sorted list of size , we require comparisons of
A. B. C. D.
Use Bubble sort to arrange the sequence in ascending order. Give the sequence at the end of each of the first five passes.
gate1995 algorithms sorting easy
end
Quick-sort is run on two inputs shown below to sort in ascending order taking first element as pivot
i.
ii.
Let and be the number of comparisons made for the inputs (i) and (ii) respectively. Then,
A. B.
C. D. we cannot say anything for arbitrary
gate1996 algorithms sorting normal
A. B.
C. D.
gate1998 algorithms sorting easy
A. it takes time
B. it maintains the relative order of occurrence of non-distinct elements
C. it uses divide and conquer paradigm
D. it takes space
If one uses straight two-way merge sort algorithm to sort the following elements in ascending order:
then the order of these elements after second pass of the algorithm is:
A.
B.
C.
D.
Let be an matrix such that the elements in each row and each column are arranged in ascending order. Draw a
decision tree, which finds st, nd and rd smallest elements in minimum number of comparisons.
An array contains four occurrences of , five occurrences of , and three occurrences of in any order. The array is to
be sorted using swap operations (elements that are swapped need to be adjacent).
a. What is the minimum number of swaps needed to sort such an array in the worst case?
b. Give an ordering of elements in the above array so that the minimum number of swaps needed to sort the array is
maximum.
Randomized quicksort is an extension of quicksort where the pivot is chosen randomly. What is the worst case
complexity of sorting n numbers using Randomized quicksort?
A. B. C. D.
gate2001 algorithms sorting time-complexity easy
The unusual implementation of Insertion Sort to sort an array uses linear search to identify the position where
an element is to be inserted into the already sorted part of the array. If, instead, we use binary search to identify the
position, the worst case running time will
A. remain B. become
C. become D. become
gate2003 algorithms sorting time-complexity normal
A. B. C. D.
gate2003 algorithms sorting normal
A. B.
C. D.
gate2003 algorithms sorting normal
The tightest lower bound on the number of comparisons, in the worst case, for comparison-based sorting is of the order
of
A. B. C. D.
gate2004 algorithms sorting asymptotic-notations easy
Suppose there are sorted lists of elements each. The time complexity of producing a sorted list of
all these elements is: (Hint:Use a heap data structure)
A. B.
C. D.
Let and be two sorted arrays containing integers each, in non-decreasing order. Let be a sorted array containing
integers obtained by merging the two arrays and . Assuming the arrays are indexed starting from , consider the
following four statements
I.
II.
III.
IV.
A. only I and II B. only I and IV C. only II and III D. only III and IV
gate2005-it algorithms sorting normal
Which one of the following in place sorting algorithms needs the minimum number of swaps?
The median of elements can be found in time. Which one of the following is correct about the complexity of
quick sort, in which median is selected as pivot?
A. B.
C. D.
gate2006 algorithms sorting easy
Which of the following sorting algorithms has the lowest worse-case complexity?
Consider the Quicksort algorithm. Suppose there is a procedure for finding a pivot element which splits the list into two
sub-lists each of which contains at least one-fifth of the elements. Let be the number of comparisons required to
sort elements. Then
A. B.
C. D.
gate2008 algorithms sorting easy
If we use Radix Sort to sort integers in the range , for some which is independent of , the time
taken would be?
A. B. C. D.
gate2008-it algorithms sorting normal
What is the number of swaps required to sort elements using selection sort, in the worst case?
A. B.
C. D.
gate2009 algorithms sorting easy
In quick-sort, for sorting elements, the smallest element is selected as pivot using an time algorithm.
What is the worst case time complexity of the quick sort?
A. B.
C. D.
gate2009 algorithms sorting normal
A list of strings, each of length , is sorted into lexicographic order using the merge-sort algorithm. The worst case
running time of this computation is
A. B. C. D.
gate2012 algorithms sorting normal
The number of elements that can be sorted in time using heap sort is
A. B.
C. D.
gate2013 algorithms sorting normal
Which one of the following is the tightest upper bound that represents the number of swaps required to sort numbers
using selection sort?
A. ) B. ) C. ) D. )
gate2013 algorithms sorting easy
Let be quicksort program to sort numbers in ascending order using the first element as the pivot. Let and be the
number of comparisons made by P for the inputs and respectively. Which one of the following
holds?
A. B. C. D.
gate2014-1 algorithms sorting easy
Suppose are sorted sequences having lengths respectively. They are to be merged into
a single sequence by merging together two sequences at a time. The number of comparisons that will be needed in the
worst case by the optimal algorithm for doing this is ____.
gate2014-2 algorithms sorting normal numerical-answers
You have an array of elements. Suppose you implement quicksort by always choosing the central element of the
array as the pivot. Then the tightest upper bound for the worst case performance is
A. B. C. D.
gate2014-3 algorithms sorting easy
Suppose you are provided with the following function declaration in the C programming language.
int partition(int a[], int n);
The function treats the first element of as a pivot and rearranges the array so that all elements less than or equal to the pivot
is in the left part of the array, and all elements greater than the pivot is in the right part. In addition, it moves the pivot so that
the pivot is the last element of the left part. The return value is the number of elements in the left part.
The following partially given function in the C programming language is used to find the smallest element in an array
of size using the partition function. We assume .
int kth_smallest (int a[], int n, int k)
{
int left_end = partition (a, n);
if (left_end+1==k) {
return a[left_end];
}
if (left_end+1 > k) {
return kth_smallest (___________);
} else {
return kth_smallest (___________);
}
}
Assume that a mergesort algorithm in the worst case takes seconds for an input of size . Which of the following
most closely approximates the maximum input size of a problem that can be solved in minutes?
A. B. C. D.
gate2015-3 algorithms sorting
The worst case running times of Insertion sort , Merge sort and Quick sort, respectively are:
A. , and
B. , and
C. , and
D. , and
Assume that the algorithms considered here sort the input sequences in ascending order. If the input is already in the
ascending order, which of the following are TRUE?
Suppose you are given numbers and you sort them in descending order as follows:
First find the maximum. Remove this element from the list and find the maximum of the remaining elements, remove
this element, and so on, until all elements are exhausted. How many comparisons does this method require in the worst case?
A. Linear in . B. but not better.
C. D. Same as heap sort.
E. but not better.
tifr2010 algorithms time-complexity sorting
Consider the Insertion Sort procedure given below, which sorts an array of size in ascending order:
begin
for xindex:= 2 to n do
x := L [xindex];
j:= xindex - 1;
while j > 0 and L[j] > x do
L[j + 1]:= L[j];
j:= j - 1;
end {while}
L [j + 1]:=X;
end{for}
end
It is known that insertion sort makes at most comparisons. Which of the following is true?
Let be a set of numbers. Consider the problem of storing the elements of in an array
such that the following min-heap property is maintained for all . (Note that is the
largest integer that is at most ). Which of the following statements is TRUE?
Given a set of distinct numbers, we would like to determine the smallest and the second smallest using
comparisons. Which of the following statements is TRUE?
The first cells of an array contain positive integers sorted in decreasing order, and the remaining cells all
contain 0. Then, given an integer , in how many comparisons can one find the position of in ?
An array contains integers. We wish to sort in ascending order. We are told that initially no element of is
more than a distance away from its final position in the sorted list. Assume that and are large and is much
smaller than . Which of the following is true for the worst case complexity of sorting ?
A. can be sorted with constant comparison but not with fewer comparisons.
B. cannot be sorted with less than constant comparisons.
C. can be sorted with constant comparisons.
D. can be sorted with constant comparisons but not with fewer comparisons.
E. can be sorted with constant comparisons but not fewer.
Consider the quick sort algorithm on a set of numbers, where in every recursive subroutine of the algorithm, the
algorithm chooses the median of that set as the pivot. Then which of the following statements is TRUE?
Suppose processors are connected in a linear array as shown below. Each processor has a number. The processors
need to exchange numbers so that the numbers eventually appear in ascending order (the processor should have the
minimum value and the the processor should have the maximum value).
The algorithm to be employed is the following. Odd numbered processors and even numbered processors are activated alternate
steps; assume that in the first step all the even numbered processors are activated. When a processor is activated, the number it
holds is compared with the number held by its right-hand neighbour (if one exists) and the smaller of the two numbers is
retained by the activated processor and the bigger stored in its right hand neighbour.
How long does it take for the processors to sort the values? At first look, it appears that each step will take O(n) time and
total n steps will be required in worst case so n∗n=O(n^2) but
A. steps B. steps twist here is that at any step All the even numbered (or odd
C. steps D. steps numbered) processors are working(Comparing it's value with
E. The algorithm is not guaranteed to sort its right neighbour and swapping values if required)
tifr2013 algorithms sorting
simultaneously. So at each step, a constant amount of time
(O(1)) is required. so T.C will be n∗O(1)=O(n) only.
1.18.52 Sorting: TIFR2017-B-7 [Link]
An array of distinct elements is said to be un-sorted if for every index such that , either
, or . What is the time-complexity of the fastest
algorithm that takes as input a sorted array with distinct elements, and un-sorts ?
Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Kruskal’s algorithm for finding a minimum spanning tree of a weighted graph with vertices and edges has the time
complexity of:
A. B. C. D. E.
gate1991 algorithms spanning-tree
Complexity of Kruskal’s algorithm for finding the minimum spanning tree of an undirected graph containing vertices
and edges if the edges are sorted is _______
gate1992 spanning-tree algorithms time-complexity easy
How many minimum spanning trees does the following graph have? Draw them. (Weights are assigned to edges).
A complete, undirected, weighted graph is given on the vertex for any fixed ‘n’. Draw the
minimum spanning tree of if
Consider a graph whose vertices are points in the plane with integer co-ordinates such that and
, where is an integer. Two vertices and are adjacent iff
. The weight of an edge
A. What is the weight of a minimum weight-spanning tree in this graph? Write only the answer without any explanations.
B. What is the weight of a maximum weight-spanning tree in this graph? Write only the answer without any explanations.
Let be an undirected connected graph with distinct edge weights. Let be the edge with maximum weight and
the edge with minimum weight. Which of the following statements is false?
Consider a weighted undirected graph with vertex set and edge set
. The
third value in each tuple represents the weight of the edge specified in the tuple.
A. B. C. D.
gate2003 algorithms spanning-tree normal
An undirected graph has nodes. its adjacency matrix is given by an square matrix whose (i) diagonal
elements are 0’s and (ii) non-diagonal elements are 1’s. Which one of the following is TRUE?
Let be a weighted undirected graph and e be an edge with maximum weight in . Suppose there is a minimum
weight spanning tree in containing the edge . Which of the following statements is always TRUE?
Consider a weighted complete graph on the vertex set such that the weight of the edge is
. The weight of a minimum spanning tree of is:
A. B. C. D.
Which one of the following cannot be the sequence of edges added, in that order, to a minimum spanning tree using Kruskal’s
algorithm?
A. B.
C. D.
gate2006 algorithms graph-algorithms spanning-tree normal
Let be the minimum weight among all edge weights in an undirected connected graph. Let be a specific edge of
weight . Which of the following is FALSE?
For the undirected, weighted graph given below, which of the following sequences of edges represents a correct
execution of Prim's algorithm to construct a Minimum Spanning Tree?
A.
B.
C.
D.
Which one of the following is NOT the sequence of edges added to the minimum spanning tree using Kruskal’s algorithm?
A.
B.
C.
D.
Consider a complete undirected graph with vertex set . Entry in the matrix below is the weight of
the edge
What is the minimum possible weight of a spanning tree in this graph such that vertex 0 is a leaf node in the tree ?
A. B. C. D.
gate2010 algorithms spanning-tree normal
Consider a complete undirected graph with vertex set . Entry in the matrix below is the weight of
the edge
What is the minimum possible weight of a path from vertex to vertex in this graph such that contains at most edges?
A. B. C. D.
gate2010 normal algorithms spanning-tree
An undirected graph contains nodes named . Two nodes are connected if and
only if . Each edge is assigned a weight . A sample graph with is shown below.
What will be the cost of the minimum spanning tree (MST) of such a graph with nodes?
A. B. C. D.
gate2011 algorithms graph-algorithms spanning-tree normal
An undirected graph contains nodes named . Two nodes are connected if and
only if . Each edge is assigned a weight . A sample graph with is shown below.
The length of the path from to in the MST of previous question with is
A. B. C. D.
gate2011 algorithms graph-algorithms spanning-tree normal
Let be a weighted graph with edge weights greater than one and be the graph constructed by squaring the weights
of edges in . Let and be the minimum spanning trees of and , respectively, with total weights and .
Which of the following statements is TRUE?
A. with total weight B. with total weight
C. but total weight D. None of the above
gate2012 algorithms spanning-tree normal marks-to-all
The number of distinct minimum spanning trees for the weighted graph below is _____
The graph shown below has edges with distinct integer edge weights. The minimum spanning tree ( MST) is of
weight and contains the edges: . The edge weights of only those edges
which are in the MST are given in the figure shown below. The minimum possible sum of weights of all edges of this graph
is_______________.
Let be a connected undirected graph of vertices and edges. The weight of a minimum spanning tree of is
. When the weight of each edge of is increased by five, the weight of a minimum spanning tree becomes ______.
gate2015-3 algorithms spanning-tree easy numerical-answers
Let be a weighted connected undirected graph with distinct positive edge weights. If every edge weight is increased
by the same value, then which of the following statements is/are TRUE?
Let be a complete undirected graph on vertices, having edges with weights being and . The
maximum possible weight that a minimum weight spanning tree of can have is __________
gate2016-1 algorithms spanning-tree normal numerical-answers
is an undirected simple graph in which each edge has a distinct weight, and is a particular edge of .
Which of the following statements about the minimum spanning trees of is/are TRUE?
1. Every MST includes lightest weight always.
I. If is the lightest edge of some cycle in , then every MST of includes .
II. If is the heaviest edge of some cycle in , then every MST of excludes . 2. Some of the MST includes or some of the MST
excludes the heaviest weight.
A. I only. B. II only. C. Both I and II. D. Neither I nor II.
gate2016-1 algorithms spanning-tree normal
Let be a connected simple graph (no self-loops or parallel edges) on vertices, with distinct edge weights. Let
be an ordering of the edges in decreasing order of weight. Which of the following statements is FALSE?
In a connected weighted graph with vertices, all the edges have distinct positive integer weights. Then, the maximum
number of minimum weight spanning trees in the graph is
a. b.
Consider the following undirected graph with some edge costs missing.
Suppose the wavy edges form a Minimum Cost Spanning Tree for . Then, which of the following inequalities NEED NOT
hold?
a. cost . b. cost .
c. cost . d. cost .
e. cost .
tifr2014 algorithms graph-algorithms spanning-tree
L et be an undirected connected simple (i.e., no parallel edges or self-loops) graph with the weight
function on its edge set. Let , where . Suppose
is a minimum spanning tree of . Which of the following statements is FALSE?
Consider the following undirected connected graph with weights on its edges as given in the figure below. A
minimum spanning tree is a spanning tree of least weight and a maximum spanning tree is one with largest weight. A
second best minimum spanning tree whose weight is the smallest among all spanning trees that are not minimum spanning
trees in .
Which of the following statements is TRUE in the above graph? (Note that all the edge weights are distinct in the above graph)
A. There is more than one minimum spanning tree and similarly, there is more than one maximum spanning tree here.
B. There is a unique minimum spanning tree, however there is more than one maximum spanning tree here.
C. There is more than one minimum spanning tree, however there is a unique maximum spanning tree here.
D. There is more than one minimum spanning tree and similarly, there is more than one second-best minimum spanning tree
here.
E. There is unique minimum spanning tree, however there is more than one second-best minimum spanning tree here.
Given below is the sketch of a program that represents the path in a two-person game tree by the sequence of active
procedure calls at any time. The program assumes that the payoffs are real number in a limited range; that the constant
INF is larger than any positive payoff and its negation is smaller than any negative payoff and that there is a function “payoff”
and that computes the payoff for any board that is a leaf. The type “boardtype” has been suitably declared to represent board
positions. It is player-1’s move if mode = MAX and player-2’s move if mode=MIN. The type modetype =(MAX, MIN). The
functions “min” and “max” find the minimum and maximum of two real numbers.
function search(B: boardtype; mode: modetype): real;
var
C:boardtype; {a child of board B}
value:real;
begin
if B is a leaf then
return (payoff(B))
else
begin
if mode = MAX then value :=-INF
else
value:INF;
for each child C of board B do
if mode = MAX then
value:=max (value, search (C, MIN))
else
value:=min(value, search(C, MAX))
return(value)
end
end; (search)
Comment on the working principle of the above program. Suggest a possible mechanism for reducing the amount of search.
A. B. C. D. E.
gate1993 algorithms time-complexity easy
Suppose we want to arrange the numbers stored in any array such that all negative values occur before all positive
ones. Minimum number of exchanges required in the worst case is
Arrays, Stacks, Queues, Linked lists, Trees, Binary search trees, Binary heaps, Graphs.
The following Pascal program segments finds the largest number in a two-dimensional integer array
using a single loop. Fill up the boxes to complete the program and write against
in your answer book Assume that max is a variable to store the largest value and 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
end
In a compact single dimensional array representation for lower triangular matrices (i.e all the elements above the
diagonal are zero) of size , 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 element of the lower triangular matrix in this new representation is:
A. B. C. D.
gate1994 data-structure arrays normal
An array contains positive integers in the locations . The following program fragment
prints the length of a shortest sequence of consecutive elements of , such that the sum of their
values is , a given positive number. It prints ‘ ’ 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.
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 , what is the address of the element ?
A. B. C. D.
A. B. C. D.
gate2000 data-structure arrays easy
Suppose you are given arrays and both uninitialized, that is, each location may contain an
arbitrary value), and a variable count, initialized to . Consider the following procedures and :
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;
}
C. Show that if has not been called for some , then regardless of what contains, will return false.
A program reads in integers in the range representing the scores of students. It then prints the
frequency of each score above . What would be the best way for to store the frequencies?
A. An array of numbers B. An array of numbers
C. An array of numbers D. A dynamically allocated array of numbers
gate2005 data-structure arrays easy
The procedure given below is required to find and replace certain characters inside an input character string supplied in
array . The characters to be replaced are supplied in array , while their respective replacement characters are
supplied in array . Array has a fixed length of five characters, while arrays and 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];
}
1.
2.
3.
4.
The tester now tests the program on all input strings of length five consisting of characters ‘ ’, ‘ ’, ‘ ’, ‘ ’ and ‘ ’ 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?
The procedure given below is required to find and replace certain characters inside an input character string supplied in
array . The characters to be replaced are supplied in array , while their respective replacement characters are
supplied in array . Array has a fixed length of five characters, while arrays and 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];
}
1.
2.
3.
4.
If array is made to hold the string “ ”, which of the above four test cases will be successful in exposing the flaw in this
procedure?
Consider the C function given below. Assume that the array contains 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;
}
A Young tableau is a 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.
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 ) to be shifted, to
remove from the given Young tableau is _____.
gate2015-2 databases arrays normal numerical-answers
The number of nodes in the left subtree and right subtree of the root respectively is
A. B. C. D.
gate1996 data-structure binary-search-tree normal
A binary search tree is used to locate the number . Which of the following probe sequences are possible and which
are not? Explain.
A. Insert the following keys one by one into a binary search tree in the order specified.
Suppose the numbers 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.
B.
C.
D.
A. B. C. D.
gate2003 normal binary-search-tree
A data structure is required for storing a set of integers such that each of the following operations can be done in
time, where is the number of elements 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 so all operations done in O(log n)
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
The following numbers are inserted into an empty binary search tree in the given order: . What is
the height of the binary search tree (the height is the maximum distance of a leaf node from the root)?
A. B. C. D.
gate2004 data-structure binary-search-tree easy isro2009
A program takes as input a balanced binary search tree with leaf nodes and computes the value of a function for
each node . If the cost of computing is:
The numbers are inserted in a binary search tree in some order. In the resulting tree, the right subtree of the
root contains nodes. The first number to be inserted in the tree must be
A. B. C. D.
gate2005-it data-structure normal binary-search-tree
A binary search tree contains the numbers When the tree is traversed in pre-order and the values in
each node printed out, the sequence of values obtained is If the tree is traversed in post-order, the
sequence obtained would be
A. B.
C. D.
gate2005-it data-structure binary-search-tree normal
Suppose that we have numbers between and in a binary search tree and want to search for the number . Which
of the following sequences CANNOT be the sequence of nodes examined?
A. B.
C. D.
gate2006-it data-structure binary-search-tree normal
When searching for the key value in a binary search tree, nodes containing the key values
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 ?
A. B. C. D.
7! / 3!4!
gate2007-it data-structure binary-search-tree normal
You are given the postorder traversal, , of a binary search tree on the elements . You have to determine
the unique binary search tree that has as its postorder traversal. What is the time complexity of the most efficient
algorithm for doing this?
A. B.
C. D. None of the above, as the tree cannot be uniquely determined
gate2008 data-structure binary-search-tree normal
A. The cost of searching an AVL tree is but that of a binary search tree is
B. The cost of searching an AVL tree is but that of a complete binary tree is
C. The cost of searching a binary search tree is but that of an AVL tree is
D. The cost of searching an AVL tree is but that of a binary search tree is
A Binary Search Tree (BST) stores values in the range to . Consider the following sequence of keys.
I.
II.
III.
IV.
Suppose the BST has been unsuccessfully searched for key . 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-structure binary-search-tree normal
A Binary Search Tree (BST) stores values in the range to . Consider the following sequence of keys.
I.
II.
III.
IV.
A. B. C. D.
gate2008-it data-structure binary-search-tree normal
What is the maximum height of any AVL-tree with nodes? Assume that the height of a tree with a single node is .
A. B. C. D.
gate2009 data-structure binary-search-tree normal isrodec2017
The worst case running time to search for an element in a balanced binary search tree with elements is
A. B.
C. D.
gate2012 data-structure normal binary-search-tree
The preorder traversal sequence of a binary search tree is . Which one of the
following is the postorder traversal sequence of the same tree?
A. B.
C. D.
gate2013 data-structure binary-search-tree normal
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 nodes?
A. B. C. D.
gate2013 data-structure easy binary-search-tree
Suppose we have a balanced binary search tree holding numbers. We are given two numbers and and wish to
sum up all the numbers in that lie between and . Suppose there are such numbers in . If the tightest upper
bound on the time to compute the sum is , the value of is ______.
Which of the following is/are correct in order traversal sequence(s) of binary search tree(s)?
I.
II.
III.
IV.
What are the worst-case complexities of insertion and deletion of a key in a binary search tree?
While inserting the elements in an empty binary search tree (BST) in the sequence shown, the
element in the lowest level is
A. B. C. D.
gate2015-3 data-structure binary-search-tree easy
The number of ways in which the numbers can be inserted in an empty binary search tree, such that
the resulting tree has height , is _________. 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
Note: The height of a tree with a single node is . same for all levels up to 6 giving 2^{6}=64 possible ways.
Let be a binary search tree with nodes. The minimum and maximum possible heights of are:
Note: The height of a tree with a single node is .
A. and respectively. B. and respectively.
C. and respectively. D. and respectively.
gate2017-1 data-structure binary-search-tree easy
The pre-order traversal of a binary search tree is given by . Then the post-order
traversal of this tree is
A.
B.
C.
D.
Suppose there is a balanced binary search tree with nodes, where at each node, in addition to the key, we store the
number of elements in the sub tree rooted at that node.
Now, given two elements and , such that , we want to find the number of elements in the tree that lie between and
, that is, . This can be done with (choose the best solution).
tifr2010 binary-search-tree
It is possible to construct a binary tree uniquely whose pre-order and post-order traversals are given?
gate1987 binary-tree data-structure normal
If the number of leaves in a tree is not a power of 2, then the tree is not a binary tree.
gate1987 data-structure binary-tree
KLNMPRQST
NLKPRMSQT
Define the height of a binary tree or subtree and also define a height-balanced (AVL) tree.
gate1988 normal descriptive data-structure binary-tree
Mark the balance factor of each on the tree given on the below figure and state whether it is height-balanced.
Consider the tree given in the below figure, insert 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.
A. always. B. always.
C. Equal to always. D. for some special trees.
gate1990 normal data-structure binary-tree
The weighted external path length of the binary tree in figure is ______
If the binary tree in figure is traversed in inorder, then the order in which the nodes will be visited is ______
Give different steps for deleting the node with key so that the structure is preserved.
Outline a procedure in Pseudo-code to delete an arbitrary node from such a binary tree with nodes that preserves the
structures. What is the worst-case-time-complexity of your procedure?
Prove by the principal of mathematical induction that for any binary tree, in which every non-leaf node has -
descendants, the number of leaves in the tree is one more than the number of non-leaf nodes.
gate1993 data-structure binary-tree normal
A rooted tree with nodes has its nodes numbered to in pre-order. When the tree is traversed in post-order, the
nodes are visited in the order .
Reconstruct the original tree from this information, that is, find the parent of each node, and show the tree diagrammatically.
gate1994 data-structure binary-tree normal
A. B. C. D.
gate1995 data-structure binary-tree normal
What is the number of binary trees with nodes which when traversed in post-order give the sequence Draw
all these binary trees.
gate1995 data-structure binary-tree normal
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. B. C. D.
gate1996 data-structure binary-tree normal
Which of the following sequences denotes the post order traversal sequence of the below tree?
A. B.
C. D.
gate1996 data-structure binary-tree easy
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 . 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 contains at least nodes.
B. In a size-balanced binary tree of height , how many nodes are at distance from the root? Write only the answer
without any explanations.
A binary search tree contains the value . The tree is traversed in pre-order and the values are printed
out. Which of the following sequences is a valid output?
A. B.
C. D.
gate1997 data-structure binary-tree normal
Draw the binary tree with node labels for which the inorder and postorder traversals result in the
following sequences:
Inorder:
Postorder:
gate1998 data-structure binary-tree descriptive
Consider the following nested representation of binary trees: indicates and are the left and
right subtrees, respectively, of node . Note that and may be , or further nested. Which of the following
represents a valid binary tree?
A. B.
C. D.
gate2000 data-structure binary-tree easy
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 data-structure binary-tree normal
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. B. C. D.
gate2002 data-structure binary-tree normal
Draw all binary trees having exactly three nodes labeled and on which preorder traversal gives the sequence
.
gate2002 data-structure binary-tree easy descriptive
Consider the label sequences obtained by the following pairs of traversals on a labeled binary tree. Which of these pairs
identify a tree uniquely?
The value returned by the function 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 D. The height of the tree
tree
gate2004 data-structure binary-tree normal
Which one of the following binary trees has its inorder and preorder traversals as and , respectively?
B.
A. C. D.
Postorder traversal of a given binary search tree, produces the following sequence of keys
Which one of the following sequences of keys can be the result of an in-order traversal of the tree ?
A.
B.
C.
D.
In a binary tree, for every node the difference between the number of nodes in the left and right subtrees is at most . If
the height of the tree is , then the minimum number of nodes in the tree is
A. B. C. D.
gate2005-it data-structure binary-tree normal
A scheme for storing binary trees in an array is as follows. Indexing of starts at instead of . the root is stored at
. For a node stored at , the left child, if any, is stored in and the right child, if any, in . To be
able to store any binary tree on n vertices the minimum size of should be
A. B. C. D.
gate2006 data-structure binary-tree normal
An array of distinct integers is interpreted as a complete binary tree. The index of the first element of the array is
. The index of the parent of element , is?
A. B.
C. D.
An array of n distinct integers is interpreted as a complete binary tree. The index of the first element of the array is
. If the root node is at level , the level of element , , is
A. B.
C. D.
gate2006-it data-structure binary-tree normal
In a binary tree, the number of internal nodes of degree is , and the number of internal nodes of degree is . The
number of leaf nodes in the binary tree is
A. B. C. D.
gate2006-it data-structure binary-tree normal
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 is:
A. B. C. D.
The maximum number of binary trees that can be formed with three unlabeled nodes is:
A. B. C. D.
gate2007 data-structure binary-tree normal
Consider the following C program segment where represents a node in a binary tree:
struct CellNode {
struct CellNode *leftChild;
int element;
struct CellNode *rightChild;
};
The value returned by when a pointer to the root of a binary tree is passed as its argument is:
A. the number of nodes in the tree 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 data-structure binary-tree normal
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.
II.
III.
A binary tree with nodes has , and nodes of degree one, two and three respectively. The degree of a
node is defined as the number of its neighbours.
can be expressed as
A. B.
C. D.
gate2008-it data-structure binary-tree normal
A binary tree with nodes has , and 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 of degree two in the tree, add an edge between the two neighbours of
and then remove from the tree. How many edges will remain at the end of the process?
A. B.
C. D.
gate2008-it data-structure binary-tree normal
In a binary tree with 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. B. C. D.
gate2010 data-structure binary-tree normal
We are given a set of distinct elements and an unlabeled binary tree with nodes. In how many ways can we
populate the tree with the given set so that it becomes a binary search tree?
A. B. C. D.
gate2011 binary-tree normal
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
A. B1: ; B2:
B. B1: ; B2:
C. B1: ; B2:
D. B1: ; B2:
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 nodes is . Then the value of is __________.
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 are
A. and , respectively B. and , respectively
C. and , respectively D. and , respectively
gate2015-1 data-structure binary-tree easy
A binary tree T has leaves. The number of nodes in T having two children is ______.
gate2015-2 data-structure binary-tree normal numerical-answers
Consider a binary tree T that has leaf nodes. Then the number of nodes in T that have exactly two children are
______.
gate2015-3 data-structure binary-tree normal numerical-answers
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.
B.
C.
D.
The postorder traversal of a binary tree is . The inorder traversal of the same tree is
. 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 _____
gate2018 data-structure binary-tree numerical-answers
Let be a full binary tree with leaves. (A full binary tree has every level full.) Suppose two leaves and of are
chosen uniformly and independently at random. The expected value of the distance between and in (ie., the
number of edges in the unique path between and ) is (rounded off to decimal places) _________.
So, expected path length
gate2019 numerical-answers data-structure binary-tree
=0×864+2×864+4×1664+6×3264=27264=4.25
3.4.52 Binary Tree: TIFR2012-B-16 [Link]
Consider a complete binary tree of height , where each edge is one Ohm resistor. Suppose all the leaves of the tree are
tied together. Approximately how much is the effective resistance from the root to this bunch of leaves for very large
?
a. Exponential in . b. Cubic in .
c. Linear in . d. Logarithmic in .
e. Of the order square root of .
tifr2012 binary-tree
Given a binary tree of the following form and having nodes, the height of the tree is
a. b.
c. d.
e. None of the above.
tifr2013 binary-tree data-structure
Let be a rooted binary tree whose vertices are labelled with symbols . Suppose the in-order
(visit left subtree, visit root, visit right subtree) and post-order (visit left subtree, visit right subtree, visit root) traversals
of produce the following sequences.
in-order:
post-order:
How many leaves does the tree have?
a. THREE. b. FOUR.
c. FIVE. d. SIX.
e. Cannot be determined uniquely from
the given information.
tifr2014 binary-tree data-structure easy
On the right, the nine nodes of the tree have been assigned numbers from the set so that for every node, the
numbers in its left subtree and right subtree lie in disjoint intervals (that is, all numbers in one subtree are less than all numbers
in the other subtree). How many such assignments are possible? Hint: Fix a value for the root and ask what values can then
appear in its left and right subtrees.
A. B. C. D. E.
tifr2015 binary-tree permutation-and-combination
Consider the following implementation of a binary tree data strucrure. The operator denotes list-concatenation.
That is,
struct TreeNode:
int value
TreeNode leftChild
TreeNode rightChild
function preOrder(T):
if T == null:
return []
else:
return [[Link]] + preOrder([Link]) + preOrder([Link])
function inOrder(T):
if T == null:
return []
else:
return inOrder([Link]) + [[Link]] + inOrder([Link])
function postOrder(T):
if T == null:
return []
else:
return postOrder([Link]) + postOrder([Link]) + [[Link]]
For some T the functions inOrder(T) and preOrder(T) return the following:
A.
B.
C.
D.
E.
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.
How many edges can there be in a forest with components having vertices in all?
gate1992 data-structure graphs easy
Let be the graph with vertices numbered to . Two vertices and are adjacent if or
. The number of connected components in is
A. B. C. D.
gate1997 data-structure normal graphs
is a graph on vertices and edges. The edges of can be partitioned into two edge-disjoint spanning trees.
Which of the following is NOT true for ?
A. For every subset of vertices, the induced subgraph has at most edges.
B. The minimum cut in has at least edges.
C. There are at least edge-disjoint paths between every pair of vertices.
D. There are at least vertex-disjoint paths between every pair of vertices.
What is the size of the smallest MIS (Maximal Independent Set) of a chain of nine nodes?
A. B. C. D.
gate2008-it data-structure normal graphs
Let be a directed graph where is the set of vertices and the set of edges. Then which one of the
following graphs has the same strongly connected components as ?
A. = where
B. = where
C. = where there is a path of length from to in
D. = where is the set of vertices in which are not isolated
Consider the weighted undirected graph with vertices, where the weight of edge is given by the entry in
the matrix .
W=
The largest possible integer value of , for which at least one shortest path between some pair of vertices will contain the edge
with weight is ___________.
gate2016-1 data-structure graphs normal numerical-answers
A hash table with ten buckets with one slot per bucket is shown in the following figure. The symbols to 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. B. C. D.
hashing isro2015 gate1989 data-structure normal
An advantage of chained hash table (external hashing) over the open addressing scheme is
A. Worst case complexity of search operations is less B. Space used is less
C. Deletion is easier D. None of the above
gate1996 data-structure hashing normal
Consider a hash table with 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 . The hash table is initially
empty and distinct values are inserted in the table.
A. What is the probability that bucket number is empty after the insertion?
B. What is the probability that no collision has occurred in any of the insertions?
C. What is the probability that the first collision occurs at the insertion?
Given the following input and the hash function mod , which
of the following statements are true?
A hash table contains buckets and uses linear probing to resolve collisions. The key values are integers and the hash
function used is key % . If the values are inserted in the table, in what location would the key
value be inserted?
A. B. C. D.
gate2005-it data-structure hashing easy
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-structure hashing normal
Consider a hash table of size seven, with starting index zero, and a hash function . Assuming the
hash table is initially empty, which of the following is the contents of the table when the sequence is inserted
into the table using closed hashing? Note that − denotes an empty location in the table.
A. , −, −, −, −, −, B. , −, −, −,
C. , −, −, −, −, −, D. , −, −, −,
gate2007 data-structure hashing easy
Consider a hash function that distributes keys uniformly. The hash table size is . After hashing of how many keys
will the probability that any new key hashed collides with an existing one exceed .
A. B. C. D.
gate2007-it data-structure hashing probability normal
Consider a hash table of size that uses open addressing with linear probing. Let be the hash
function used. A sequence of records with keys
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. B. C. D.
gate2008-it data-structure hashing normal
The keys and are inserted into an initially empty hash table of length using open
addressing with hash function and linear probing. What is the resultant hash table?
A. B. C. D.
A hash table of length uses open addressing with hash function , and linear probing. After
inserting values into an empty hash table, the table is shown as below
Which one of the following choices gives a possible order in which the key values could have been inserted in the table?
A. B.
C. D.
gate2010 data-structure hashing normal
A hash table of length uses open addressing with hash function , and linear probing. After
inserting values into an empty hash table, the table is shown as below
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. B. C. D.
data-structure hashing normal gate2010
Consider a hash table with slots. The hash function is . The collisions are resolved by chaining.
The following keys are inserted in the order: . The maximum, minimum, and average
chain lengths in the hash table, respectively, are
Consider a hash table with slots. Collisions are resolved using chaining. Assuming simple uniform hashing, what
is the probability that the first slots are unfilled after the first insertions?
A. B.
C. D.
gate2014-3 data-structure hashing probability normal
Which one of the following hash functions on integers will distribute keys most uniformly over buckets numbered
to for ranging from to ?
A. B.
C. D.
gate2015-2 data-structure hashing normal
Given that hash table with slots that stores elements, the load factor for is _________.
gate2015-3 data-structure hashing normal numerical-answers
The minimum number of interchanges needed to convert the array into a max-heap is
A. B. C. D.
gate1996 data-structure heap easy
A. In binary tree, a full node is defined to be a node with 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:
. Show the result after the deletion of the root of this heap.
Consider any array representation of an element binary heap where the elements are stored from index to index
of the array. For the element stored at index of the array , the index of the parent is
A. B. C. D.
gate2001 data-structure heap easy
In a min-heap with elements with the smallest element at the root, the smallest element can be found in time
A. B.
C. D.
gate2003 data-structure heap
The elements are inserted one by one in the given order into a maxHeap. The resultant
maxHeap is
A.
B.
C. D.
gate2004 data-structure heap normal
An array of integers of size can be converted into a heap by adjusting the heaps rooted at each internal node of the
complete binary tree starting at the node , and doing this adjustment up to the root node (root node is at
index ) in the order , , ....., . The time required to construct a heap in this manner is
By using Build Heap method we can create
A. B. C. D. heap from complete binary tree.
gate2004-it data-structure heap normal
which will take O(n).
3.8.8 Heap: GATE2005-34 [Link]
A priority queue is implemented as a Max-Heap. Initially, it has elements. The level-order traversal of the heap is:
. Two new elements and are inserted into the heap in that order. The level-order traversal of the heap
after the insertion of the elements is:
A. B.
C. D.
gate2005 data-structure heap normal
In a binary max heap containing numbers, the smallest element can be found in time
A. B.
C. D.
gate2006 data-structure heap easy
A -ary max heap is like a binary max heap, but instead of children, nodes have children. A -ary heap can be represented
by an array as follows: The root is stored in the first location, , nodes in the next level, from left to right, is stored from
to . The nodes from the second level of the tree from left to right are stored from location onward. An item can be
inserted into a -ary heap containing items by placing in the location 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 -ary max heap?
A. B.
C. D.
A -ary max heap is like a binary max heap, but instead of children, nodes have children. A -ary heap can be represented
by an array as follows: The root is stored in the first location, , nodes in the next level, from left to right, is stored from
to . The nodes from the second level of the tree from left to right are stored from location onward. An item can be
inserted into a -ary heap containing items by placing in the location and pushing it up the tree to satisfy the heap
property.
77. Suppose the elements and are inserted, in that order, into the valid -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. B.
C. D.
gate2006 data-structure heap normal
An array of distinct integers is interpreted as a complete binary tree. The index of the first element of the array is
. 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. B. C. D.
gate2006-it data-structure heap easy
A. B.
C. D.
gate2009 data-structure heap normal
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?
B.
A.
C. D.
gate2011 data-structure heap easy
A priority queue is implemented as a Max-Heap. Initially, it has elements. The level-order traversal of the heap is:
. Two new elements and are inserted into the heap in that order. The level-order traversal of the heap
after the insertion of the elements is:
A. B.
C. D.
gate2014-2 data-structure heap normal
Now consider that a value is inserted into this heap. After insertion, the new heap is
A. B.
C. D.
gate2015-1 data-structure heap easy
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. B.
C. D.
gate2015-2 data-structure heap normal
A. B. C. D.
gate2015-3 data-structure heap normal
An operator for a binary heap data structure is to be designed to delete the item in the -th node. Assume
that the heap is implemented in an array and refers to the -th index of the array. If the heap tree has depth (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. B. but not
C. but not D. but not
gate2016-1 data-structure heap normal
A complete binary min-heap is made by including each integer in 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 . The maximum depth at
which integer can appear is _________.
gate2016-2 data-structure heap normal numerical-answers
Suppose the nodes of the tree are randomly assigned distinct labels from , each permutation being equally likely.
What is the probability that the labels form a min-heap (i.e., every node receives the minimum label in its subtree)?
A. B. C. D. E.
tifr2014 heap
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 D. A parse tree
stack
gate1997 normal infix-postfix stack data-structure
A list of elements is commonly written as a sequence of elements enclosed in a pair of square brackets. For
example. is a list of three elements and is a nil list. Five functions are defined below:
Consider a singly linked list having nodes. The data items are stored in these nodes. Let be a
pointer to the node in which is stored. A new data item stored in node with address is to be
inserted. Give an algorithm to insert into the list to obtain a list having items in order without using
the header.
gate1993 data-structure linked-lists normal
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-structure linked-lists normal ugcnetsep2013ii
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
IV. Binary search using a linear linked list is efficient
The concatenation of two lists is to be performed on 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-structure linked-lists easy
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 ([Link] != [Link]) ----------------> (S1)
{
(*j)++;
t1 -> next = t2;
t1 = t2; -----> (S2)
}
t2 = t2 ->next;
}
t1 -> next = NULL;
return head;
}
q: = p -> next
p -> next:= q -> next
Write a constant time algorithm to insert a node with data just before the node with address of a singly linked list.
gate1999 data-structure linked-lists
In the worst case, the number of comparisons needed to search a single linked list of length for a given element is
A. B. C. D.
gate2002 easy data-structure linked-lists
A circularly linked list is used to represent a Queue. A single variable is used to access the Queue. To which node
should point such that both the operations and can be performed in constant time?
Suppose each set is represented as a linked list with elements in arbitrary order. Which of the operations among
will be the slowest?
A. only B.
C. D.
gate2004 data-structure linked-lists normal
Let be a singly linked list. Let be the pointer to an intermediate node in the list. What is the worst-case time
complexity of the best-known algorithm to delete the node from the list ?
A. B. C. D.
gate2004-it data-structure linked-lists normal ambiguous
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
in the given order. What will be the contents of the list after the function completes execution?
struct node {int value; struct node *next;);
void rearrange (struct node *list) {
struct node *p, *q;
int temp;
if (!list || !list -> next) return;
p = list; q = list -> next;
while (q) {
temp = p -> value;
p -> value = q -> value;
q -> value = temp;
p = q -> next;
q = p ? p -> next : 0;
}
}
A. B.
C. D.
gate2005-it data-structure linked-lists normal
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 in the given order. What will be the contents
of the list after function completes execution?
struct node {
int value;
struct node *next;
};
A. B.
C. D.
gate2008 data-structure linked-lists normal
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;
A. ;
B. ;
C. ;
D. ;
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: delete, insert, find, and
decrease-key. What is the time complexity of all these operations put together?
A. B. C. D.
gate2016-2 data-structure linked-lists time-complexity normal
Assuming that m and n point to valid NULL-terminated linked lists, invocation of join will
A priority queue is used to implement a stack that stores characters. PUSH (C) is implemented as INSERT
where is an appropriate integer key chosen by the implementation. POP is implemented as DELETEMIN
. For a sequence of operations, the keys chosen are in
Suggest a data structure for representing a subset of integers from to . Following operations on the set are to be
performed in constant time (independent of cardinality of ).
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-structure normal descriptive queues
A queue containing items and an empty stack 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 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.
gate1994 data-structure queues stack normal
What is the minimum number of stacks of size required to implement a queue of size ?
x=pop(S2);
}
let insert and delete operations be performed in an arbitrary order on an empty queue . Let and be the
number of push and pop operations performed respectively in the process. Which one of the following is true for all and ?
A. and
B. and
C. and
D. and
Suppose you are given an implementation of a queue of integers. The operations that can be performed on the queue
are:
Suppose a circular queue of capacity elements is implemented with an array of elements. Assume that the
insertion and deletion operations are carried out using REAR and FRONT as array index variables, respectively.
Initially, . The conditions to detect queue full and queue empty are
A. full: B. full:
empty: empty:
C. full: D. full:
empty: empty:
Consider the following operation along with Enqueue and Dequeue operations on queues, where 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 queue operations on an initially empty
queue?
A. B. C. D.
gate2013 data-structure algorithms normal queues
A queue is implemented using an array such that ENQUEUE and DEQUEUE operations are performed efficiently.
Which one of the following statements is CORRECT ( refers to the number of items in the queue) ?
Let denote a queue containing sixteen numbers and be an empty stack. returns the element at the head
of the queue without removing it from . Similarly returns the element at the top of without removing it
from . Consider the algorithm given below.
while Q is not Empty do
if S is Empty OR Top(S) ≤ Head (Q) then
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 _______.
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 time?
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 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. B.
C. D.
Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
The following sequence of operations is performed on a stack:
PUSH (10), PUSH (20), POP, PUSH (10), PUSH (20), POP, POP, POP, PUSH (20), POP
The sequence of values popped out is
A. B.
C. D.
gate1991 data-structure stack easy
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 in that order?
A. B.
C. D.
gate1994 data-structure stack normal
A. B.
C. D.
gate1995 data-structure stack easy
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 operations.
B. The following post fix expression, containing single digit operands and arithmetic operators and , is evaluated using a
stack.
Let S be a stack of size . Starting with the empty stack, suppose we push the first n natural numbers in sequence,
and then perform pop operations. Assume that Push and Pop operations take seconds each, and seconds elapse
between the end of one such stack operation and the start of the next operation. For , define the stack-life of
as the time elapsed from the end of to the start of the pop operation that removes
from S. The average stack-life of an element of this stack is
A. B. C. D.
A single array is used to implement two stacks. The two stacks grow from opposite ends of the
array. Variables and point to the location of the topmost element in each of the stacks. If the
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 is
A. B.
C. D.
gate2004 stack isro2009
The best data structure to check whether an arithmetic expression has balanced parentheses is a
A program attempts to generate as many permutations as possible of the string, ' ' by pushing the characters
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. B. C. D.
gate2004-it data-structure normal stack
A. B. C. D.
gate2005-it data-structure stack normal
The following postfix expression with single digit operands is evaluated using a stack:
Note that is the exponentiation operator. The top two elements of the stack after the first is evaluated are
A. B. C. D.
gate2007 data-structure stack normal isro2016
A. B. C. D.
gate2007-it stack normal
Suppose a stack implementation supports an instruction , which reverses the order of elements on the
stack, in addition to the and instructions. Which one of the following statements is TRUE ( with respect
to this modified stack)?
A. B. C. D.
gate2015-3 data-structure stack normal
We have an implementation that supports the following operations on a stack (in the instructions below, is the name
of the stack).
is executed?
A. B. C. D. E.
tifr2017 data-structure stack
Consider the height-balanced tree with values stored at only the leaf nodes, shown in Fig.4.
(i) Show how to merge to the tree, elements from tree shown in Fig.5 using node D of tree .
(ii) What is the time complexity of a merge operation of balanced trees and where and are of height and
respectively, assuming that rotation schemes are given. Give reasons.
Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
A tree is such that
A. B. C. D.
gate1992 trees data-structure normal
A tree is a tree in which every internal node has exactly three children. Use induction to prove that the number
of leaves in a tree with internal nodes is .
A complete -ary tree is one in which every node has or sons. If is the number of internal nodes of a complete -
ary tree, the number of leaves in it is given by
A. B. C. D.
gate1998 data-structure trees normal
A. Derive a recurrence relation for the size of the smallest AVL tree with height .
B. What is the size of the smallest AVL tree with height ?
The number of leaf nodes in a rooted tree of n nodes, with each node having or children is:
A. B. C. D.
gate2002 data-structure trees normal
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 data-structure trees easy
In a complete -ary tree, every internal node has exactly children. The number of leaves in such a tree with internal
node is:
A. B. C. D.
gate2005 data-structure trees normal
A complete tree is a tree in which each node has children or no children. Let be the number of internal
nodes and be the number of leaves in a complete tree. If and , what is the value of ?
A. B. C. D.
gate2007 data-structure trees normal
Consider the following rooted tree with the vertex labeled as the root:
The order in which the nodes are visited during an in-order traversal of the tree is
A. B. C. D.
gate2014-3 data-structure trees easy
Consider the pseudocode given below. The function takes as argument a pointer to the root of an
arbitrary tree represented by the representation. Each node of the tree is of type
.
typedef struct treeNode* treeptr;
struct treeNode
{
treeptr leftMostChild, rightSibling;
};
When the pointer to the root of a tree is passed as the argument to , the value returned by the function
corresponds to the
A. number of internal nodes in the tree. B. height of the tree.
C. number of nodes without a right D. number of leaf nodes in the tree
sibling in the tree.
gate2014-3 data-structure trees normal
Let be a tree with vertices. The sum of the degrees of all the vertices in is ________
gate2017-1 data-structure trees numerical-answers
Let be a tree of nodes. Consider the following algorithm, that constructs a sequence of leaves . Let be
some leaf of tree. Let be a leaf that is farthest from . Let be the leaf that is farthest from , and, in general, let
be a leaf of that is farthest from (if there are many choices for , pick one arbitrarily). The algorithm stops when
some is visited again. What can u say about the distance between and , as
Programming in C. Recursion.
An unrestricted use of the "go to" statement is harmful because of which of the following reason (s):
Consider the following high level programming segment. Give the contents of the memory locations for variables
and after the execution of the program segment. The values of the variables and are and ,
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;
A. B. C. D.
gate1998 programming normal identify-function
A. B. C. D.
gate2004-it programming easy identify-function
Consider the following snippet of a C program. Assume that swap exchanges the content of and :
int main () {
int array[] = {3, 5, 1, 4, 6, 2};
int done =0;
int i;
while (done==0) {
done =1;
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]);
}
(*A*)
While (remainder >= 0) do
begin (*B*)
quotient := quotient + 1;
remainder := remainder - divisor;
(*C*)
end;
(*D*)
quotient := quotient - 1;
remainder := remainder + divisor;
(*E*)
end
Below figure is the flow-chart corresponding to a program to calculate the of two integers, and respectively,
Use assertions at the cut point , and to prove that the flow-chart is correct.
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 as any sequence of statement and f as a function.
Consider the following program fragment for reversing the digits in a given integer to obtain a new integer.
Let .
int n, rev;
rev = 0;
while(n > 0) {
rev = rev * 10 + n%10;
n = n/10;
}
A.
B.
C.
D.
Consider the following pseudo code, where and 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.
B.
C.
D.
while (b != 0) {
if (b % 2 == 0) {a = a * a; b = b/2; }
else {res = res * a; b = b - 1; }
}
return res;
}
Which one of the following conditions is TRUE before every iteration of the loop?
A. B.
C. D.
gate2016-2 programming loop-invariants normal
Consider the C program fragment below which is meant to divide by using repeated subtractions. The variables ,
, and are all unsigned int.
while (r >= y) {
r=r-y;
q=q+1;
}
Which of the following conditions on the variables and before the execution of the fragment will ensure that the loop
terminated in a state satisfying the condition ?
A.
B.
C.
D.
Consider the following program for summing the entries of the array : array of integers, where is a
positive integer. (The symbol ' ' denotes 'not equal to').
var
i, s: integer;
Program
i:= 0;
s:= 0;
[*] while i <> N do
s := s + b[i];
i := i + 1;
od
Which of the following gives the invariant that holds at the beginning of each loop, that is, each time the program arrives at
point ?
A.
B.
C.
D.
E.
Invariant of the loop is a condition which is true before and after every iteration of the loop. In the above program the loop
invariant is given by
and
Which of the following is true of the program?
Consider the following psuedocode fragment, where is an integer that has been initialized.
int i=1
int j=1
while (i<10):
j=j*i
i=i+1
if (i==y):
break
end if
end while
i. or
ii. If , then
iii. If , then
Which of the above statements is/are TRUE at the end of the while loop? Choose from the following options.
A. i only B. iii only C. ii and iii only D. i, ii, and iii E. None of the above
tifr2017 programming loop-invariants
What will be the output of the following program assuming that parameter passing is
i. call by value
ii. call by reference
iii. call by copy restore
procedure P{x, y, z};
begin
y:y+1;
z: x+x
end;
begin
a:= b:= 3;
P(a+b, a, a);
Print(a)
end.
What is printed by the print statements in the program 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
}
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);
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. B. C. D.
gate2003 compiler-design normal runtime-environments parameter-passing
What is the return value of , if the value of is initialized to before the call? Note that the first parameter is
passed by reference, whereas the second parameter is passed by value.
#include<stdio.h>
void fun1(char* s1, char* s2){
char* temp;
temp = s1;
s1 = s2;
s2 = temp;
}
void fun2(char** s1, char** s2){
char* temp;
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
int main(){
Various parameter passing mechanisms have been in used in different programming languages. Which of the following
statements is true?
If both parameters to are passed by reference, what are the values of and at the end of the above program fragment ?
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. B.
C. D.
gate1999 programming normal programming-constructs
define s to be:
is:
A. B.
C. D.
gate2000 programming programming-in-c normal
Assume that the objects of the type short, float and long occupy bytes, bytes and bytes, respectively. The memory
requirement for variable , ignoring alignment consideration, is:
is:
A. B. C. D.
int *g(void)
{
int x = 10;
return (&x);
}
int *g(void)
{
int *px;
*px = 10;
return px;
}
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?
In the C language:
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.
A. B. C. D.
gate2002 programming-in-c programming easy
I.
II.
III.
IV.
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 programming programming-in-c easy
int x;
void Q(int z)
{
z+=x;
print(z);
}
A. B. C. D.
gate2003 programming programming-in-c normal
Consider the following C program which is supposed to compute the transpose of a given matrix . Note that,
there is an in the program which indicates some missing statements. Choose the correct option to replace 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
}
for (1 = 0; i < 4; ++i)
for (j = 0; j < 4; ++j)
printf ("%d", M[i][j]);
}
#include<stdio.h>
int funcf (int x);
int funcg (int y);
main ()
{
int x = 5, y = 10, count;
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. B. C. D.
gate2004-it programming programming-in-c normal
Choose the correct option to fill the and 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. is '\n'
is
B. is '\n'
is
C. is '\n'
is
D. is '\n'
is
C. D.
The above code compiled without any error or warning. If Line is deleted, the above code will show:
The following function takes two ASCII strings and determines whether one is an anagram of the other. An anagram
of a string s is a string obtained by permuting the letters in s.
int anagram (char *a, char *b) {
int count [128], j;
for (j = 0; j < 128; j++) count[j] = 0;
j = 0;
while (a[j] && b[j]) {
A;
B;
}
for (j = 0; j < 128; j++) if (count [j]) return 0;
return 1;
}
A.
B.
C.
D.
Let be an array containing integers in increasing order. The following algorithm determines whether there are two
distinct numbers in the array whose difference is a specified number .
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");
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;
}
Which one of the choices given below would be printed when the following program is executed ?
#include <stdio.h>
struct test {
int i;
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. B.
C. D.
gate2006-it programming programming-in-c normal
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);
A. B.
C. D.
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. B.
C. D.
gate2006-it programming programming-in-c normal
A. B. C. D.
gate2007-it programming programming-in-c normal
Which combination of the integer variables and makes the variable get the value in the following expression?
A. B.
C. D.
gate2008 programming programming-in-c easy
void main()
{
int c, *b, **a;
c = 4; b = &c; a = &b;
printf("%d", f(c, b, a));
A. B. C. D.
gate2008 programming programming-in-c normal
Choose the correct option to fill and 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. is
is
B. is
is
C. is
is
D. is
is
A. B. C. D.
gate2008-it programming programming-in-c normal
A. B. C. D.
gate2008-it programming programming-in-c normal
What should be the contents of the array b at the end of the program?
A.
B.
C.
D.
int main() {
f(&i, &j);
printf("%d %d\n", i,j);
return 0;
}
A. B. C. D.
gate2010 programming programming-in-c easy
A. B. C. D.
gate2011 programming programming-in-c normal
A. No Choice B. Choice A
C. Choice A D. Program gives no output as it is
Choice B No Choice erroneous
gate2012 programming easy programming-in-c
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);
}
A. B. C. D.
void prtFun(void)
{
static int a = 2; /* Line 2 */
int b = 1;
a += ++b;
printf(“ \n %d %d ”, a, b);
}
A. B. C. D.
main()
{
int i;
int*pi = &i;
scanf("%d",pi);
printf("%d\n", i+5);
}
A. Compilation fails.
Suppose and are unsigned int variables in a C program. We wish to set p to . If is large, which one of the
following statements is most likely to set p correctly?
A. B.
C. D.
gate2014-2 programming programming-in-c normal
What is the output of the following C code? Assume that the address of is (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. B.
C. D.
gate2015-1 programming programming-in-c normal
A. B. C. D.
gate2015-2 programming programming-in-c normal
Consider the following two C code segments. and are one and two dimensional arrays of size and
respectively, where . Assume that in both code segments, elements of are initialized to 0 and each
element of array is initialized to . Further assume that when stored in main memory all elements of 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];
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];
A. B. C. D.
gate2015-3 programming programming-in-c normal
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. B. C. D.
gate2016-1 programming-in-c easy
The following function computes the maximum value contained in an integer array of size .
while (__________) {
if (p[a]<= p[b]) {a = a+1;}
else {b = b-1;}
}
return p[a];
}
f (&i, j);
print f ("%d", i+j);
}
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);
}
void main() {
char *x = "abc";
char *y = "defgh";
printlength(x,y);
}
Recall that is defined in as returning a value of type , which is an unsigned int. The output of the
program is __________ .
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);
}
A. B. C. D.
gate2017-2 programming-in-c programming
Consider the following C code. Assume that unsigned long int type length is 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 is:
A. B. C. D.
gate2018 programming-in-c normal programming
Consider the following program written in pseudo-code. Assume that and are integers.
Count (x, y) {
if (y !=1 ) {
if (x !=1) {
print("*");
Count (x/2, y);
}
else {
y=y-1;
Count (1024, y);
}
}
}
The number of times that the statement is executed by the call is _____
Which one of the following values will be displayed on execution of the programs?
A. B. C. D.
gate2019 programming-in-c programming
#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 _________
If you run greet(n) for some non-negative integer n, what would it print?
A. n times "hello", followed by n+1 times B. n times "hello", followed by n times
"world" "world"
C. n times "helloworld" D. n+1 times "helloworld"
E. n times "helloworld", followed by
"world"
tifr2018 programming-in-c
Given the following pseudocode for function below, how many times is printed if we execute
void printx(int n) {
if(n==0){
printf(“x”);
}
for(int i=0;i<=n-1;++i){
printx(n-1);
}
}
A. B. C. D. E.
tifr2019 programming programming-in-c
Choose the best matching between the programming styles in Group 1 and their characteristics in Group 2.
A. B.
C. D.
gate2004 programming normal programming-paradigms
The number of times is called (including the first call) for evaluation of is___________.
The above function is run on a computer with a stack of bytes. Assuming that only return address and parameter are passed
on the stack, and that an integer value and an address takes bytes each, estimate the maximum value of for which the stack
will not overflow. Give reasons for your answer.
A. B. C. D.
gate1995 algorithms normal recursion
A recursive program to compute Fibonacci numbers is shown below. Assume you are also given an array
with all elements initialized to
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 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
main()
{
abc("123");
}
n = n+i;
i++;
return f(n);
}
A. B. C. D.
gate2004 programming programming-in-c recursion easy isro2008
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;
}
A. B. C. D.
gate2005 programming recursion normal
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 and stores the value of , as and when they are computed. With
this modification the time complexity for function is significantly reduced. The space complexity of the modified
function would be:
A. B. C. D.
gate2005 programming recursion normal
if (n <= 0) return 1;
if (n > 3)
{ r = n;
return f(n-2) + 2;
}
return f(n-1) + r;
}
A. B. C. D.
gate2007 programming recursion normal
Assuming that arbitrarily large integers can be passed as a parameter to the function, consider the following statements.
printf ("%d",n);
printf ("%d",d);
d++;
if (n>1) count (n-1);
printf ("%d",d);
void main(){
count (3);
}
A.
B.
C.
D.
A.
B.
C.
D.
int counter=0;
int main() {
calc(4, 81);
printf("%d", counter);
}
Consider the following computation rules. Parallel-outermost rule: Replace all the outermost occurrences of F (i.e., all
occurrences of F which do not occur as arguments of other F's) simultaneously. Parallel - innermost rule : Replace all
the innermost occurrences of F (i.e.,all occurrences of F with all arguments free of F's) simultaneously. Now consider the
evaluations of the recursive program over the integers.
F(x, y) <== if x = 0 then 0 else
[ F(x + 1, F(x, y)) * F(x - 1, F(x, y))]
We say that w when the evaluation of does not terminate. Computing using the parallel -
Consider the class of recursive and iterative programs. Which of the following is false?
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. B. C. D.
gate2007-it programming variable-binding normal ugcnetdec2012iii