Pds-Algo Pyqs
Pds-Algo Pyqs
Solution C
Question 2
struct node
{
int i; float j;
};
struct node *s[10];
The above C declaration define 's' to be (GATE CS
2000)
Solution A
Refer precedence table in C
Question 3
Consider the following C
declaration struct {
short
s[5];
union {
float
y;
long
z;
}u;
} t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and
8 bytes, respectively. The memory requirement for variable t, ignoring alignment
considerations, is (GATE CS 2000)
A 22 bytes
B 14 bytes
C 18 bytes
D 10 bytes
Short array s[5] will take 10 bytes as size of short is 2 bytes.
When we declare a union, memory allocated for the union is equal to memory
needed for the largest member of it, and all members share this same memory
space. Since u is a union, memory allocated to u will be max of float y(4 bytes) and
long z(8 bytes). So, total size will be 18 bytes (10 + 8).
Solution C
Question 4
#include<stdio.h> struct st
{
int x;
struct st next;
};
int main()
{
struct st temp;
temp.x = 10;
temp.next = temp;
printf("%d", temp.next.x);
return 0;
}
A. Compiler Error
B. 10
C. Runtime Error
D. Garbage Value
Solution
Solution A
Question 5
union test
{
int x;
char arr[4];
int y;
};
int main(){
union test t;
t.x = 0;
t.arr[1] = 'G';
printf("%s", t.arr);
return 0;
}
Predict the output of above program. Assume that the size of an integer is 4 bytes and
size of character is 1 byte. Also
assume that there is no alignment needed.
A.Nothing is printed
B.G
C.Garbage character followed by 'G'
D.Garbage character followed by 'G', followed by more garbage characters
E.Compiler Error
Since x and arr[4] share the same memory, when we set x
= 0, all
printf function starts from the first character and keeps printing till it finds a
Anyone of the followings can be used to declare a node for a singly linked list. If we
use the first declaration, “struct node * nodePtr;” would be used to declare pointer
to a node. If we use the second declaration, “NODEPTR nodePtr;” can be used to
declare pointer to a node.
/* First
declaration */
struct node {
int data;
struct node * nextPtr;
};
/* Second declaration
*/ typedef struct
node{
int data; NODEPTR
nextPtr;
} * NODEPTR;
A.TRUE
B.FALSE
Solution 6
int main()
{
struct {int a[2], b;} arr[] = {[0].a = {1}, [1].a = {2}, [0].b = 1, [1].b = 2};
printf("%d %d %d and",arr[0].a[0],arr[0].a[1],arr[0].b);
printf("%d %d %dn",arr[1].a[0],arr[1].a[1],arr[1].b);
return 0;
}
A. Compile error because struct type (containing two fields i.e. an array of int and an int) has
been specified along with the definition of array arr[] of this struct type.
B. Compile error because of incorrect syntax for initialization of array arr[].
C. No compile error and two elements of arr[] would be defined and initialized. Output would
be “1 0 1 and 2 0 2”.
D. No compile error and two elements of arr[] would be defined and initialized. Output would
be “1 X 1 and 2 X 2” where X is some garbage random number.
Solution 7
printf ("%d\n",
ip is an integer pointer and the initial assignment sets it to the element at array
index 4 i.e. 5.
(holds address of ar index 4)
The next statement refers to the nextinteger after it which
is 6(ip[1]=∗(ip+1))
Question 9
#include<
stdio.h >
struct
Ournode{ char
x,y,z;
};
int main(){
struct Ournode p = {'1', '0', 'a'+2};
struct Ournode *q = &p;
printf ("%c, %c", *((char*)q+1),
*((char*)q+2)); return 0;
}
The output of this program is:
A. 0, c
B. 0, a+2
C. '0', 'a+2'
D. '0', 'c'
Solution 9
'a' + 2 will be 'c', so Ournode p = {'1', '0', 'c'} and output will be
0, c.
int c;
c=a; a=b; b=c;
}
int main () {
int a = 4, b = 5, c = 6;
f1 ( a, b); This has no effect on actual values
// of a ,b since Call by value.
f2 (&b, &c); Here change will be happen.
At this point int a = 4, b = 6, c = 5;
printf ("%d", c - a - b); = (5-4)-6 = 1-6 = -5
Question 12
char c[ ] = "GATE2011";
char *p = c;
A. GATE2011
B. E2011
C. 2011
D. 01
Solution 12
= 2004
⇒
2011 string will be printed.
an integer
D.A function that takes an integer pointer as argument and returns a function
pointer
Solution 13
Solution C
Steps to read the statement:-
1: using dangling
2: using uninitialized pointers
3. lost memory
is:
A. X – 1 Y 3 Z – 2
–
B. X – 2 Y 1 Z – 3
–
C. X 3Y 2Z–1
– –
Solution 14
Answer is (D).
X;m = NULL makes the pointer point to NULL. But the memory created
using mallocis still there and but cannot be used as we don't have a link to
Integer
x;
return
0;
}
Which one of the following phases in a seven-phase C compiler will
throw an error?
A Syntax analyzer
B. Semantic analyzer
Solution 16
This question is difficult to answer from a practical point of view because most of
the C compilers (even other language compilers) do not follow the classical
ordering of compilation phases. Since this is a one-mark question ignoring the
practical implementations and going by just theory answer will be syntax error.
Because there are no lexical errors and “Integer” and “x” get read as identifiers
as shown in the following output.
int main()
{
Integer x;
return 0;
}
Now, when this stream of tokens get passed to the syntax analyser – we have an
identifier followed by another identifier
which is not valid in C syntax – so syntax error. And this must be the answer here
Now consider a typedef usage like “typedef int Integer”. Now, this can be
implemented by the compiler in multiple ways. One option is to immediately change
the token type of “Integer” from identifier to the given “type”. Otherwise the syntax
check can go with the AST generation. But if we go by the classical meaning of the
compilation phases here we are matching a string which means it is a semantic
phase.
Correct Answer: Syntax Analysis/Semantic analysis
Question 17
Consider the following C
function. int fun ( int n ) {
int x = 1, k ;
if ( n == 1) return
x ; for( k = 1 ; k < n
; ++ k )
x = x + fun( k ) * fun( n -
Solution 17
fun(5) = 1 + fun(1) * fun(4) + fun(2) * fun(3) +
fun(3) * fun(2) + fun(4) * fun(1)
= 1 + 2*[fun(1)*fun(4 + fun(2)*fun(3)]
)
Substituting fun(1) = 1
= 1 + 2*[fun(4) + fun(2)*fun(3)]
Note: If any doubt in any question post with subject & question number in EPT App.
Question 18
Consider the following program in C language:
SOLUTION D
Question
19
Consider the following program:
int f(int *p, int n)
{
if (n <= 1) return 0;
else return max(f(p+1,n-1),p[0]-p[1]);
}
int main()
{
int a[] = {3,5,2,6,4};
printf("%d", f(a,5));
}
Note: max(x,y) returns the maximum of x and y. The value printed by this
program is
A. 2
B. 3
C. 4
D. 5
Solution 19
Solution C
Assuming that the base address of array starts from 1000 and an integer
takes 4 Bytes.After the last recursive call f(1016,1) returns, in the
previous call we will have return max(0,2) and then return max(2,-4) and
then return max(2,3) and then finally return max(3,-2) = 3
Question 20
Which of the following statements are CORRECT?
Solution A
If we take look at the inner statements of first loops, we can notice that the
statements swap A[i][j] and A[j][i] for all i and j. Since the loop runs for all
elements, every element A[l][m] would be swapped twice, once for i = l and j
= m and then for i = m and j = l. Swapping twice means the matrix doesn’t
change.
Question
22
Consider the function func shown below:
int func(int num)
{
int count = 0;
while(num)
{
count++; num >>= 1;
}
return (count);
}
The value returned by func(435) is .
Solution 22
Answer is 9.
435−(110110011)
num >>=1; implies a num is shifted one bit right in every while loop
execution.While loop is executed 9 times successfully and 10th time num
is zero.
So count is incremented 9 times.
Note:
Shifting a number "1"bit position to the right will have the effect of
dividing by 2:
Question 23
=n∗(n−1)∗(n−2)/6
B =n∗(n−1)/
2∗(n−2)/3
=n∗(n−1)/3∗(n−2)/2
Solution 23
Answer: (B)
option B would always produce an integer, which means no precision loss in this
environment?
Answer:
(C)
Explanation: Heap allocation is needed for dynamic data
structures like
tree, linked list, etc.
Question 26
languages is:
A both are procedural languages
statements.
Question 27
manner.
Avoiding the use of GOTO statements is not the goal of structured programming, it
(avoiding the use of GOTO) is one of the requirements for a program to be
structured.
Question 28
Choose the best matching between the programming style in Group 1 and their
characteristics in Group 2
Group 1
P. Functional
Q.Logic
R.Object-oriented
S.Imperative
Group 2
1.Command-based, procedural
2.Imperative, abstract data types
3.Side-effect free, declaretive, expression
Evaluation 4.Declaretive, clausal representation,
theorem proving
A .P - 2 Q - 3 R - 4 S - 1
B .P - 4 Q - 3 R - 2 S - 1
C.P - 3 Q - 4 R - 1 S - 2
D .P - 3 Q - 4 R - 2 S - 1
Solution 28
Answer: (D)
type
Answer is (C).
A Do not differ
B Differ in the presence of loops
C Differ in all cases
In call by value-result, the called function is working with a copy of the passed
variables. On return, the updated values are copied back to the original
variables.
(B)
147
10 13 16
19 22 25
(C)
123
456
789
(D)
123
13 14 15
25 26 27
Solution 31
Answer: (A)
Explanation:
{{1,2,3,4,5,6,7,8,9},
{10,11,12,13,14,15,16,17,18},
{19,20,21,22,23,24,25,26,27}};
(A) Only P3
P1 : Here the function is returning address of the variable x (& x ) but the return type is
pointer to integer not address. So incorrect.
P2 : *px = 0 directly assigned a value but still px doesn’t point to any memory
location, so memory initialization or allocation should be done before. So incorrect.
P3: Correction made in P2, memory pre allocated, So correct.
Hence (C) is correct option.
Question 33
Consider the following
program Program P2
Var n:int:
procedure W (var x:int)
begin
X=X+1
Print x;
end
Procedure D
Begin var
n:int; n=3;
W(n);
End Begin \\begin
P2 n=10;
D;
end
If the language has dynamic scoping and parameters are passed by reference, what
will be printed by the program ?
Solution 33
Assuming that the main memory is byte-addressable and that array is stored starting from
…………………………………….
……………………………………..
a[99][0] ………………a[99][99]
100 bytes per row. I.e 40 X100 = 4000
1 byte per column I. e. 50 X 1 = 50
Total 4050
Question 35
The summation is for each node, if that node happens to be the root. When a node is root,
it will have
(k−1
)nodes on the left sub tree (k being any number) and
correspondingly
elements on the (n−k)
right sub tree. So, we can write
recurrence
T(k−1)∗T(n-
k)
for the number of distinct binary search trees, as the numbers on left and right sub trees form BSTs
independent
of each other and only a difference in one of the sub trees produces a difference in the tree. Hence,
answer is B.
Question 36
Consider the C program shown below
#include<stdio.h>
#define print(x) printf(“%d”,x)
int x;
void Q (int z)
{
z+=x; print(z);
}
void p (int* y){ int x=*y+2;
Q(x); *y=x-1; print(x);
}
main (void){
x=5;
p(&x);
print(x);
}
The output of this program is
(A) 12 7 6
(B) 22 12 11
(C) 14 6 6
(D) 7 6 6
Solution 36
First x=5
Then by function p(&x)
X =5+2=7
Then by function
Q(x) z =z+x
=7+5=12
Here x is global variable so still it
is 5. Return to function p(&x) Y
=7-1=6 print x =7
return to main
Print x =6 Here this is global x whose *y ahs been changed to 6 so 6
is printed
Option A is correct
Question 37
temp
=a; a
=b;
b =temp;
}
In the order to exchange the values of two variables x and y .
(A) call swap (x,y)
(B) call swap (&x ,&y )
Solution 38
}
Run on IDE
A 765
B. 5 6 7
C 777
D Compiler Dependent
Solution 39
return (x + y + z);
}
A. Function is made globally available
sum has no use in foo(), it is there just to confuse. Function foo() just
prints all digits of a number. In main, there is one more printf
statement
Correct ans D
Question 42
The most appropriate matching for the following pairs (GATE
CS 2000)
X: m=malloc(5); m= 1: using dangling
NULL; Y: free(n); n- pointers
(a) X — 1 Y—
3 Z-2
(b) X — 2 Y—
1 Z-3
(C) X — 3 Y—
Solution 42
Answer (d)
X -> A pointer is assigned to NULL without freeing memory so a clear
int main()
{ double
da, db;
// input
da db =
foo(da);
double
foo(double a){
return a;
The above code compiled without any error or warning. If Line 1 is deleted, the above code
will show:
A.no compile warning or error
B.some compiler-warnings not leading to unintended results
C.some compiler-warnings due to type-mismatch eventually leading to unintended results
D.compiler errors
Solution 43
In C, if a function is called before its declaration, the compiler assumes the return
type of the function as int if the function double foo() in the above
code is defined later to main() and the calling statement, then it will not compile
successfully. Because the compiler assumes the return type as “int” by default.
And at declaration, if the return type is not matching with int then the compiler
will give an error.
Solution A
Eplanation: count is static variable in incr(). Statement static int count = 0 wil
assign count to 0 only in first call. Other calls to this function will take the old
values of count.
Count will become 0 after the call incr(0)
Count will become 1 after the call incr(1)
Count will become 3 after the call incr(2)
Count will become 6 after the call incr(3)
Count will become 10 after the call incr(4)
Question 45
Consider the following C declaration struct {
short s [5]; union {
float y; long z;
}u;
} t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively.
Answer: (c)
Explanation: Short array s[5] will take 10 bytes as size of short is 2 bytes.
Since u is a union, memory allocated to u will be max of float y(4 bytes) and
long z(8 bytes). So, total size will be 18 bytes (10 + 8).
Question 46
What is the output of the following
program? #include <stdio.h> funcf(int x)
}
}
Solution 46
Solution 43 80
The count=1 and it goes till two,so following statement will be executed twice.
y += funcf(x) + funcg(x);
A. 5 B. 8 C. 9 D. 20
Solution 47
Solution C
f(20,1) = 9.
f(10,2) - 1 = 9
f(5,4) - 2 = 10
f(2,8) + 4 = 12
f(1,16) - 8 = 8
f(0,32) + 16 =
16
Question 48
Consider the following C
program. void f(int, short);
void main()
{
int i = 100;
short s = 12;
short *p = &s;
; // call to f()
}
Which one of the following expressions, when placed in the blank above, will NOT result in a type
checking error?
A f(s, *s)
B. i = f(i,s)
C. f(i,*s)
Solution 48
Solution C
Assuming that the base address of array starts from 1000 and an integer
takes 4 Bytes.After the last recursive call f(1016,1) returns, in the
previous call we wil have return max(0,2) and then return max(2,-4) and
then return max(2,3) and then final y return max(3,-2) = 3
Question 50
Consider the following C-program :
int fun()
{
static int num = 16;
return num--;
}
int main()
{
for(fun(); fun(); fun())
printf("%d ", fun()); return 0;
}
What is output of above program?
.
A Infinite loop
B 13 10 7 4 1
.
C 15 12 8 5 2
.
D 14 11 8 5 2
Solution 50
• Solution D
• Explanation:14 11 8 5 2
Since num is static in fun( ), the old value of num is preserved for subsequent function
calls. Also, since the statement return num-- is postfix, it returns the old value of num and
updates the value for next function call.
Question 51
Given a boolean function f (x1, x2, ..., xn), which of the following equations is
NOT true
A f (x1, x2, ..., xn) = x1'f(x1, x2, ..., xn) + x1f(x1, x2, ..., xn)
B f (x1, x2, ..., xn) = x2f(x1, x2, … ,xn) + x2'f(x1, x2, …,xn)
C f (x1, x2, ..., xn) = xn'f(x1, x2, … ,0) + xnf(x1, x2, …, 1 )
D f (x1, x2, ..., xn) = f(0, x2, … ,xn) + f(1, x2, .., xn)
Solution 51
.Option D
Case 1: taking x1=0 RHS = 1.f(x1, x2, …, xn) + 0.f(x1, x2, …, xn) RHS =f(x1, x2, …, xn).
Case 2: taking x1=1 RHS = 0.f(x1, x2, …, xn) + 1.f(x1, x2, …, xn) RHS =f(x1, x2, …, xn). In both cases
RHS=LHS, so, (A) is true
Option B: f (x1, x2, …, xn) = x2f(x1, x2, …, xn) + x2’f(x1, x2, …, xn)
Case 1: taking x2=0 RHS= 0.f(x1, x2, …, xn) +1.f(x1, x2…,xn) RHS =f(x1, x2, …, xn).
Case 2: taking x2=1 RHS = 1.f(x1, x2, …, xn) + 0.f(x1, x2, …, xn) RHS =f(x1, x2, …, xn).
In both cases RHS=LHS, so, (B) is true. Option C: f (x1, x2, …, xn) =
xn’f(x1, x2, …, 0) + xnf(x1, x2, …,1) Case 1: taking xn=0 RHS= 1.f(x1,
is true.
Option D: f (x1, x2, …, xn) = f(0, x2, …, xn) + f(1, x2, .., xn) Here, no way to equate
LHS and RHS so
‘
NOT true’. NO term depends on value of ‘x1’.
Question 52
Consider the following C code.
#include #include
void main()
{
double pi =
3.1415926535; int a =
1;
int i;
for(i=0; i < 3; i++)
if(a = cos(pi *
i/2) ) printf("%d
",1);
else printf("%d ", 0);
}
Solution 52.
In each iteration of the loop, j is incremented by 1, which means j takes on the values 2,
3, 4, 5, ..., until i/j becomes less than or equal to 0.001.
Since i/j decreases with each iteration, the loop wil iterate a large number of times
before the condition becomes false.Therefore, the program wil produce more than 29
lines of output. The correct answer is option D: More than 29 lines of output.
Question 54
Output of following
program?
#include <stdio.h>
int main()
{
int i = 5;
printf("%d %d %d", i++,
i++, i++); return 0;
}
A. 7 6 5
B. 5 6 7
C. 7 7 7
D. Compiler Dependent
Solution 54
When parameters are passed to a function, the value of every parameter is
evaluated before being passed to the function. What is the order of
evaluation of parameters - left-to-right or right-to-left? If evaluation order is left-to-
right, then output should be 5 6 7 and if the evaluation order is right- to-left, then
output should be 7 6 5. Unfortunately, there is no fixed order defined by C
standard. A compiler may choose to evaluate either from left- to-right. So the
output is compiler dependent.
Solution D
Question 55
A. Passed by value
B. Passed by reference
Solution A
In C, function parameters are always passed by value. Pass-by-
reference
is simulated in C by explicitly passing pointer values.
Question 56
macro Add
x,y Load y
Mul x
Store y
end
macro
A Variables
B. Identifiers
C.Actual
Solution 57
Actual parameters:-
the function or method call in the calling environment.At the time of the call each
function definition.
Question 58
Although C does not support call by name parameter passing, the effect
can be correctly simulated in C.
A TRUE
B FALSE
Solution 58
A TRUE
B FALSE
Solution 60
False The language can have dynamic data types which requires
while r ≥ y
do begin
r := r - y
q := q + 1
end
end
The loop terminates when r<y. So, r<y is one post condition.
In each iteration q is incremented by 1 and y is subtracted from r. Initial
value of is x. So, loop iterates x/y times and q will be equal to x/y and
r = x % y ⇒ x = qy + r;
Question 62
Consider the C function given below.
int f(int j)
{
static int i = 50;
int k;
if (i == j)
{
printf("something");
k = f(i);
return 0;
}
else return 0;
}
Which one of the following is TRUE?
A The function returns 0 for all values of j.
B The function prints the string something for all values of j.
C The function returns 0 when j = 50.
Solution 62
Answer: (D)
Explanation:
When j is 50, the function would call itself again and again as neither i nor
double f (double x) {
1
Question 64
What is the return value of f (p, p), if the value of p is initialized to 5 before the
call? Note that the first parameter is passed by reference, whereas the
second parameter is passed by value. int f (int &x, int c) {
c = c - 1;
if (c==0)
return 1; x =
x + 1;
return f(x,c) * x;
}
A 3024
B 6561
C 55440
D 161051
Solution 64
Answer (B)
Since c is passed by value and x is passed by reference, all functions will have
f(5, 5) = f(x, 4)*x = f(x, 3)*x*x = f(x, 2)*x*x*x = f(x, 1)*x*x*x*x = 1*x*x*x*x =
x^4
Since x is incremented in every function call, it becomes 9 after f(x, 2) call.
II. Is CORRECT. Programming languages that support nested also have a field in the call frame
points to the stack frame of the latest activation of the procedure that mostthat
Subroutiene closely encapsulates the callee,
i.e. the immediate scope of the callee. This is called an access link or static link (as it keeps track of static
nesting during dynamic and recursive calls) and provides the routine (as well as any other routines it may
invoke) access to the local data of its encapsulating routines at every nesting level. Some architectures,
compilers, or optimization cases store one link for each enclosing level (not just the immediately
enclosing), so that deeply nested routines that access shallow data do not have to traverse several links;
this strategy is often called a “display”
III. Recursion CAN be implemented with any kind of Dynamic Storage Allocation scheme.
IV. Nesting features are always implemented in a language using STACK and NOT Heap. (See above point II
for details)
V.Is CORRECT. In stack based allocation scheme, once a function has returned, it is removed from function
Question 66
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 dynamic scoping and call by name parameter passing mechanism,
the values printed by the above program are(GATE CSE 2003)
Solution 66
If the programming language uses static scoping and call by name parameter passing mechanism, the values
printed by the above program are(GATE CSE 2003)
A 115, 220
Solution 67
Answer: (D)
Explanation:
Value of variable x doesn’t change anytime in the function P(x). Hence,
whatever its value is when this function is called, only that will be used in all the
print statements. Clearly, 100+5+10, 100+5 i.e. 115, 105 will be printed by the
program.
Question 68
What is printed by the print statements in the program P1 assuming call by reference
parameter passing? Program P1()
{
x=10
y=3;
func1(y,x,x);
x;
y;
}
func1(x,y,z)
{
y=y+4;
z=x+y+z;
}
Solution 68
Answer is B
Here, variableof func1 points to address of variable y
y=y+4⟹y=10+4=14
and
z=x+y+z⟹z=14+14+3=31
z will be stored back in x. Hence, x=31 and y will remain as it
is. (y=3)
Answer is 31,
3
Question 69
Consider the following program
Program P2
var n:int;
procedure W(var x:int)
begin
x=x+1; print x;
end
procedure D
begin
var n:int;
n=3;
W(n);
end
begin \\begin P2 n =
10;
D;
If the language has dynamic scoping and parameters are passed by reference, what
will be printed by the program?
A .10
B .11
C.3
D.None of the above
Solution 69
ans is D.
here, because of dynamic scoping the value of n passed in w(n) will be
n=3.
X: m=malloc(5); m= NULL; Y:
free(n); n->value = 5;
Z: char *p; *p='a';
1: using dangling
2: using uninitialized pointers
3. lost memory
is:
A. X – 1 Y – 3 Z 2
–
B. X – 2 Y – 1 Z 3
–
C. X – 3 Y – 2 Z 1
–
Solution 70
Answer is (D).
X:m = NULL makes the pointer point to NULL. But the memory created using
mallocis
still there and but cannot be used as we don't have a link to it. Hence, lost memory
B. 122 75 83 .
C. * − +
D. P x +
Answer : Option A is the
answer. char a = ‘P’
char b = ‘x’
As per precedence of operators, () evaluated prior to +/-
Note that &,^ and | are bit wise operators and Addition/Subtraction of characters applied on
their ASCII values.
‘+’ = 43
which constructs will you not include in a programming language such that it should be
possible to program the terminates (i.e., halting) function in the same programming
language.
A. (ii), (iii), (iv)
B. (v), (vii), (viii)
C. (vi), (vii), (viii)
Solution 72
This question is actually asking about the halting problem of Turing machines. Or in other words which of the
constructs are needed to make a programming languag Turing complete – when it becomes Turing
complete, halting problem becomes undecidable for it.
assignment ✓
1>for loops where the loop parameter cannot be changed within the loop
2> As described above this just translatedto a finitenumber of sequential instructions
when unrolled. Some people might be confused with loops like
int n = 0; {
for(int i=1;i>n;
}
Here, if the loop body is not touching either i or n, the loop never terminates. But this decision (that it never
terminates) can be decided easily by a written program (analyzing this is decidable and you can think of a C
code to do it and equivalently we can have a Turing machine to decide this). So, the above loop even thoug
being non-halting does not make the “halting decision” undecidable.
3>if-then-else ✓. This just reduces one path (a set of instructions) from the linear sequence of instructions
and hence does not affect the halting decision (assumin there are no other structures in either of the paths)
4>forward go to ✓
Like, if-else this also just eliminates some set of instructions.
5>arbitrary go to ❌This can simulate a for loop and so can cause problem in
deciding halting.
6>non-recursive procedure call ✓. Each of the called procedure contributes to the
number of executed instructions but since there is no recursion they’ll eventuall
halt as long as each of the called procedures halt.
7>recursive procedure/function call ❌. This will also run into the same problem of a
loop where the loop variables are changed inside the loop body. We may not b
able to determine if the sequence of recursive calls ever terminates.
8>repeat loop ❌Similar to a for loop if the looping condition is changed within the
loop body this can make the halting decision undecidable.
Correct Option: B.
Question 73
A certain processor supports only the immediate and the direct addressing modes.
Which of the following programming language features cannot be
A Pointers
B. Arrays
C. Records
Now, to handle recursive procedures we need to use stack. A local variable inside
the stack will be accessed as *(SP+offset) which is nothing but a pointer access
and requires indirect addressing. Usually this is done by moving the SP value to
Base register and then using Base Relative addressing to avoid unnecessary
memory accesses for indirect addressing- but not possible with just direct and
immediate addressing.
D activation tree
Solution 74
Correct Option: C
Properties of
displays
Calling a subprogram
replace and restore. in the higher level – add an entry and may need to save
the old pointers.
Calling a subprogram in the lower level – shrink the pointer and restore it when the
subprogram returns.
Question 75
In which one of the following cases is it possible to obtain different results for call-
by-reference and call-by-name parameter passing methods?
8;
Question 76
Suppose we are given n keys, m has table slots, and two simple uniform hash
functions h1 and h2. Further suppose our hashing scheme uses h1
for the odd keys and h2 for the even keys. What is the expected number of keys
in a slot?
A m/n
B n/m
2n/m
Solution 76
Answer: (B)
Explanation:
For a uniform hash function, regardless of the number of hash functions, the
Consider a double hashing scheme in which the primary hash function is h1(k)=k
mod 23, and the secondary hash function is h2(k)=1+(k mod 19).
Assume that the table size is 23. Then the address returned by probe 1 in the
probe sequence (assume that the probe sequence begins at probe 0) for key
value k=90 is _ .
Solution 77
, we have to determine the second element of the probe sequence (i.e. i =1) for the
key k=90.
(ℎ1(90)+1∗ℎ2(90))mod23=(21+15)mod23=36mod23=13
Question 78
i.A hash function (these are often used for computing digital signatures) is an
injective function.
collisions. The key values are integers and the hash function used is key
% 10. If the values 43, 165, 62, 123, 142 are inserted in the table, in what
A. 2
B. 3
C. 4
D. 6
Solution 80
43 in loc 3
165 in loc 5
62 in loc 2
Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and
the hash function x mod 10, which of the following statements are true?
i) 9679, 1989, 4199 hash to the same value
ii) 1471, 6171 has to the same value
iii)All elements hash to the same value
iv) iv)Each element hashes to a different
value
A i only
B. ii only
C.i and ii only
D iii or iv
Solution 81
Answer: (C)
9679, 1989 and 4199 all these give same hash value i.e 9
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
Solution 82
Sequence given in option (B) is not possible, because of entry 1 (=0001) and
(=1010), and 14 (=1110) in the third column, 3 sequence is not given in the final
hash table.
Question 84
Consider a hash table with 9 slots. The hash function is h(k) = k mod 9. The
collisions are resolved by chaining. The following 9 keys are inserted
in the order: 5, 28, 19, 15, 20, 33, 12, 17, 10. The maximum, minimum, and
average chain lengths in the hash table, respectively, are
A. 3, 0, and 1
B. 3, 3, and 3
C. 4, 0, and 1
D. 3, 0, and 2
Solution 84
Answer: (A)
Explanation: Following are values of hash function for all
keys 5 --> 5
28 --> 1
19 --> 1 [Chained with 28]
15 --> 6
20 --> 2
33 --> 6 [Chained with 15]
12 --> 3
17 --> 8
10 --> 1 [Chained with 28 and 19]
The maximum chain length is 3. The keys 28, 19 and 10 go to same slot 1, and form a
chain of
length 3.
The minimum chain length 0, there are empty slots (0, 4 and 7).
Question 85
Consider a hash table with 100 slots. Collisions are resolved using chaining.
Assuming simple uniform hashing, what is the probability that
A (97 × 97 × 97)/1003
B (99 × 98 × 97)/1003
C (97 × 96 × 95)/1003
Answer: (A)
Explanation:
distributes items into the slots of a hash table. Moreover, each item to be hashed has
.
Solution 86
Answer (C)
The sequence (A) doesn’t create the hash table as the element 52
Let,
T(n) = T(n^(1/a))+1, T(b)
=1 → n^(1/a^k) = b
→ log(n^(1/a^k)) = log(b)
Now, using iterative
method, → ak = log(n) / log (b) =
log_b(n)
= T(n)
→ k = log_a log_b(n)
= [T(n^(1/a))+1] + 1
Therefore,
= [T(n^(1/a^3))+1] + 2
= T(n^(1/a^k)) + k
= [T(n^(1/a^4))+1] + 3
= T(b) + log_a log_b(n)
.
= 1 + log_al og_b(n)
.= [T(n^(1/a^k))+1] + (k-
1) = Θ(log_a
A. 10
ve
B. 20 ?
C. 30
D. 40
.
Solution 88
Answer (C)
In a valid insertion sequence, the elements 42, 23 and 34 must appear before
The keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted into an initially empty hash
table of length 10 using open addressing with hash function h(k) = k
0
1
2 12
3 13
4 2
5 3
6 23
7 5
8 18
9 15
Question 90
Consider a hash table of size 11 that uses open addressing with linear probing.
Let h(k) = k mod 11 be the hash function used. A sequence of records with keys
Solution
D
Type to enter a
caption.
Question 91
Consider a hash table of size seven, with starting index zero, and a hash function
(3x + 4)mod7. Assuming the hash table is initially empty, which of
the following is the contents of the table when the sequence 1, 3, 8, 10 is
inserted into the table using closed hashing? Note that ‘_’ denotes an empty
location in the table.
A 8, _, _, _, _, _, 10
B 1, 8, 10, _, _, _, 3
C 1, _, _, _, _, _,3
D 1, 10, 8, _, _, _, 3
Solution 91
Let us put values 1, 3, 8, 10 in the hash of size 7. Initially, hash table is empty
- - - - - - -
0 1 2 3
4 5 6
The value of function (3x + 4)mod 7 for 1 is 0, so let us put the value at 0
1 - - - - - -
0 1 2 3
4 5 6
The value of function (3x + 4)mod 7 for 3 is 6, so let us put the value at 6
1 - - - - - 3
0 1 2 3
4 5 6
The value of function (3x + 4)mod 7 for 8 is 0, but 0 is already occupied, let us put the value(8) at
next available
space(1)
1 8 - - - - 3
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 10 is 6, but 6 is already occupied, let us put the value(10) at
next available
Question 92
Consider a hash function that distributes keys uniformly. The hash table size is
20. After hashing of how many keys will the probability that any
A. 5
B. 6
C. 7
D. 10
Solution 92
The question is a bit ambiguous.
After hashing of how many keys, will the probability that any new key hashed collides with an existing one exceed 0.5.
Here, 'new key hashed' is the ambiguity. It can mean the probability of a collision in the next 'hash', or the probability
of a collision in any of the hashes of the 'new keys' starting from the first insertion. For the first case answer must be
10 to get probability equal
to
So,0.5,
we and
needsoto11 must
find be the
n such answer
that after nfor probability
hashes, >0.5. Thus
probability we can
of collision (inconclude from
any of the n>0.given choices, it is the second
hashes)
case. 5
.
Probability that there will be a collision after n hashes (a collision happened in at least one of those n hashes)
For n=5, we get, 0.5814 and for n=6, we get 0.43605. So, answer
should be =6. Correct Answer: B
Question 93
Which one of the following statements is TRUE for all positive functions
f(n) ?
A f(n2) = (f(n)2), when f(n) is a polynomial
B f(n2) = o(f(n)2)
C f(n2) = O(f(n)2), when f(n) is an exponential function D
f(n2) = Ω(f(n)2)
Solution 93
Answer: (A)
Explanation:
Option A: It always holds because if we square the input variable, then the
B f(2^n) = 1
C f(5* +1+
1
2^n) = D
+1
f(2^n + 1)
Solution 94
Solution 94
Let,
T(n) = T(n^(1/a))+1, T(b)
=1 → n^(1/a^k) = b
→ log(n^(1/a^k)) = log(b)
Now, using iterative
method, → ak = log(n) / log (b) =
log_b(n)
= T(n)
→ k = log_a log_b(n)
= [T(n^(1/a))+1] + 1
Therefore,
= [T(n^(1/a^3))+1] + 2
= T(n^(1/a^k)) + k
= [T(n^(1/a^4))+1] + 3
= T(b) + log_a log_b(n)
.
= 1 + log_al og_b(n)
.= [T(n^(1/a^k))+1] + (k-
1) = Θ(log_a
(A) Only I
(B) Only
II
(C) I or III or IV but
not II
(D) II or III or IV but
not I
Solution 95
Which of the following is the tightest upper bound that represents the
number of swaps required to sort n numbers using selection sort?
A.O(log n)
B. O(n)
C.O(n log n)
D.O(n2)
Solution 96
Answer: (B)
Explanation: To sort elements in increasing order, selection sort always picks the
maximum element from remaining unsorted array and swaps it with the last
element in the remaining array. So the number of swaps, it makes in n-1 which is
O(n)
Question 97
Which one of the following is the tightest upper bound that represents the time
complexity of inserting an object in to a binary search tree of n
nodes?
O(1)
B. O(log n)
C. O(n)
D. O(n log n)
Solution 97
Answer: (C)
Explanation: To insert an element, we need to search for its place first. The
search operation may take O(n) for a skewed tree like following.
To insert 50, we will have to traverse all nodes.
10
\
20
\
30
\
40
Question 98
A. Θ(n^2)
B. Θ(n^2 logn)
C. Θ(n^3)
D Θ(n^3 logn)
Solution 98
Answer: (C)
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
A. A(n)=Ω(W(n))
B. A(n)=Θ(W(n))
C. A(n)=O(W(n))
D. A(n)=0(W(n))
Solution 99
Answer: (C)
A. 12
B. 10
C. 6
D. 5
Solution 100
Answer: (C)
Explanation:
Since, 10nlog_10 n ≤ 0.0001n^2
Given n = 10k records.
Therefore,
⟹10×(10k)log_10 10^k ≤ 0.0001(10^k)^2
⟹10^(k+1) *k ≤ 0.0001 × 10^(2k)
⟹k ≤ 10^(2k−k−1−4)
⟹k ≤ 10^(k−5)
Hence, value 5 does not satisfy but value 6 satisfies. 6 is the smallest value of k
for which
package B will be preferred over A. Option (C) is correct.
Question 101
The number of comparisons made in the execution of the loop for any n >
0 is: A ⌈log2⌉+1
B. n
C. ⌈log2⌉
D. ⌊log2⌋+1
Solution 101
Answer: (D)
Explanation:
We can see it by taking few examples like n = 1, n = 3,
etc.
Answer: (C)
Note the semicolon after the for loop, so there is nothing in the body.
Question 103
A O (n)
B O (n log n)
C O
(n^3/2)
D O
(n^3)
Solution 103
Answer (d)
In mathematics, the transitive closure of a binary relation R on a set X is the smallest
transitive relation on X that contains R. If the original relation is transitive, the
transitive closure will be that same relation; otherwise, the transitive closure will be a
different relation.
In computer science the concept of transitive closure can be thought of as constructing a
data structure that makes it possible to answer reachability questions. That is, can one
get from node a to node other node b in one or more hops? A binary relation tells you
only that node a is connected to node b, and that node b is connected to node c, etc.
After the transitive closure is constructed in an O(1) operation one may determine that
node c is reachable from node a.
In the worst case, the number of comparisons needed to search a singly linked
list of length n for a given element is
A log n
B. n/2
C.Log_2 n - 1
D n
Solution 104
Answer: (D)
Explanation: Singly linked list has uni –directional flow, i.e., it has only
D activation tree
Solution 105
Correct Option: C
Properties of
displays
Calling a subprogram in the higher level – add an entry and may need to save
replace and restore.
the old pointers.
Calling a subprogram in the lower level – shrink the pointer and restore it when the
subprogram returns.
Question 106
In which one of the following cases is it possible to obtain different results for call-
by-reference and call-by-name parameter passing methods?
Let f(n) = n^2 log n and g(n) = n(log n)^10 be two positive functions of n.
Which of the following statements is correct?
Answer: (C)
Explanation:
As list concatenation requires traversing at least one list to the end. So
singly linked list and doubly linked list requires O(n) time complexity
whereas circular doubly linked list required O(1) time.
Question 109
Answer: (D)
Note that you can take the log of each function then compare.
Question 110
The given diagram shows the flowchart for a recursive function A(n). Assume that all
statements, except for the recursive calls, have O(1) time complexity. If the worst
case time complexity of this function is O(n^α), then the least possible value
(accurate up to two decimal positions) of α is
(A) 2.2 to
2.4
(B) 3.2 to
3.4
(C) 0 to 1.8
(D) 1
Solution 110
Answer: (A)
Explanation: The time complexity of a recurrence relation is the worst case time complexity.
First we have to find out the number of function calls in worst case from the flow chart.
The worst case will be when all the conditions (diamond boxes) turn out towards non-
returning paths taking the longest root. In the longest path we have 5 function calls.
from a linearly ordered set. For a delete operation, a pointer is provided to the
record that must be deleted. For the decrease-key operation, a pointer is provided
Explanation: The time complexity of insert in unsorted array is O(1), O(Logn) in Min-Heap, O(n) in
sorted array and sorted DLL. For unsorted array, we can always insert an element at end and do
insert in O(1) time
For Min Heap, insertion takes O(Log n) time. Refer Binary Heap operations
for details. For sorted array, insert takes O(n) time as we may have to
For sorted doubly linked list, insert takes O(n) time to find position of element to be
move all elements worst case.
inserted.
(D) nlog(logn)
Answer: (D)
Explanation:
int fun1 (int n)
{
int i, j, k, p, q = 0;
Let f(n) = n and g(n) = n(1+sin n), where n is a positive integer. Which of
I. f(n) = O(g(n))
(A) Only I
(B) Only II
Answer: (D)
Explanation: The value of sine function varies from -1 to 1. For sin = -1 or any
other negative value, I becomes false.
The number of elements that can be sorted in Θ(log n) time using heap
sort is
(A) A
(B) B
(C) C
(D) D
Solution 114
Answer C
Question 115
You are given the postorder traversal, P, of a binary search tree on the n elements
1, 2, … , n. You have to determine the unique binary search tree
that has P as its postorder traversal. What is the time complexity of the most
efficient algorithm for doing this?
(A) O(Logn)
(B) O(n)
(C) O(nLogn)
Answer: (B)
Explanation: One important thing to note is, it is Binary Search Tree, not Binary
Tree. In BST, inorder traversal can always be obtained by sorting all keys.
Question 116
(A) Θ(n)
(B) Θ(logn)
(C) Θ(n*logn)
(D) Θ(1)
Solution 116
Answer: (B)
Explanation:
If you answered Theta(1), then think of examples {1, 2, 2, 2, 4, 4}, {1, 1, 2, 2, 2, 2, 3, 3}
The Best
way to find out whether an integer appears more than n/2 times in a sorted
array(Ascending
Order) of n integers, would be binary search approach.
The First occurrence of an element can be found out in O(log(n)) time using divide and
The Last occurrence of an element can be found out in O(log(n)) time using divide and
Solution I, II, IV
A[2] will not give compile time error because this can
be considered as pointer A[2][3] this will result in an
integer hence no error will occur
B[1] This code attempts to access the second row of a two-dimensional array B by
using the statement B[1] which is
syntactically incorrect.
B[2][3] this will also result in an integer hence no error will occur
Question 118
A program P reads in 500 integers in the range [0, 100] representing the cores of
500 students. It then print the frequency of each score above 50. What would be
the best way for P to store the frequencies?
A.Array of 50 numbers
B.Array of 100 numbers
C.Array of 500 numbers
D.Dynamically allocated Array of 550 numbers
Solution:A
Since the program P needs to store the frequency of each score above 50, the best
way to store the frequencies would be to use an array with 50 elements. Each
element of the array corresponds to a score from 51 to 100, and stores the
frequency of that score in the input array.
Question 119
[0 -1 -2]
[1 0 -1]
[2 10]
Solution 119
Solution A
For the given array V with dimensions n x n, where V [i, j] = i - j for all 1 ≤i ≤
n and 1 ≤j ≤n, let's consider the specific case of a 3x3 array.
As we can see the resultant matrix is skew symmetric matrix hence sum of
element is zero
Question 120
Let A be a square matrix of size n x n. Consider the following program. What is the expected
output?
C = 100
for i = 1 to n do
for j = 1 to n do {
Temp = A[i][j] + C A[i][j] = A[j][i]
A[j][i] = Temp - C
}
for i = 1 to n do
for j = 1 to n do
Output(A[i][j]);
A.The matrix A itself
B.Transpose of matrix A
C.Adding 100 to the upper diagonal elements and subtracting 100 from diagonal elements
Solution 120
Solution : A
If we take look at the inner statements of first loops, we can notice that the
statements swap A[i][j] and A[j][i] for all i and j. Since the loop runs for all every
element A[l][m] would be swapped twice, once for i = l and j = m and then for i =
m and j = l. Swapping twice means the matrix doesn’t change elements,
Question 121
A three dimensional array in ‘C++’ is declared as int A[x][y][z]. Consider that array
elements are stored in row major order and indexing begins from 0.
Here, the address of an item at
the location A[p][q][r] can be computed as follows (where w is the word length
of an integer):
A. &A[0][0][0] + w(y * z * q + z * p + r)
C. &A[0][0][0] + w(x * y * p + z * q+ r)
D. &A[0][0][0] + w(x * y * q + z * p + r)
Solution 121
Solution: B
According to above question we have to find the address of A[p][q][r] To reach pth row
we must have to cross 0 to p-1 row i.e. p rows and each rows contains y∗z elements
Hence , = y∗z∗p Now to reach qth element in pth row we have to cross q rows and
each row contains z(total columns) elements =z∗q to reach rth elements we have to
cross r elements in (p+1)th row Total elements to cross =(y∗z∗p+z∗q+r) Now each
element occupies m amount of space in memory Therefore total space occupied by
these elements = m(y∗z∗p+z∗q+r) Hence , address of A[p][q][r]=base address+
Space Occupied by the Elements Before it.
=&A[0][0][0]+m(y*z*p+z*q+r) Hence Option (B) is correct.
Question 122
Consider a two dimensional array A[20][10]. Assume 4 words per memory cell, the
base address of array A is 100, elements are stored in row-major order and first
element is A[0][0]. What is the address of A[11][5] ?
A. 560
B. B. 460
C. C. 570
D. D. 575
Solution 122
Solution A
Element A[11][0] is stored at "Base Address + 11 * 10 * 4" which is "Base
Address + 440" = 540. So A[11][5] is stored at 540 + 5*4 = 560.
Question 123
Solution: A
Solution: 6
Explanation:
Can a tree stored in an array using either one of inorder or post order or
pre order traversals be again reformed?
a) Yes just traverse through the array and form the tree
b) No we need one more traversal to form a tree
c) No in case of sparse trees
d) Yes by using both inorder and array element
Solution 126
Answer: b
Explanation: We need any two traversals for tree formation but if
some additional stuff or techniques are used while storing a tree
in an array then one traversal can facilitate like also storing null
values of a node in array.
Question 127
Answer: d
Explanation: Random access is not possible with linked lists.Also
it includes extra memory space for each element thereby
increasing its space complexity.
Question 128
Identify the reason which doesn’t play a key role to use threaded binary
trees?
a) The storage required by stack and queue is more
b) The pointers in most of nodes of a binary tree are NULL
c) It is Difficult to find a successor node
d) They occupy less size
Solution 128
Answer: d
Explanation: Threaded binary trees are introduced to make the Inorder
traversal faster without using any stack or recursion. Stack and Queue
require more space and pointers in the majority of binary trees are null
and difficulties are raised while finding successor nodes. Size constraints
are not taken on threaded binary trees, but they occupy less space than a
stack/queue.
Question 129
Solution: A
Initially, p is pointing to the first element of the array A, which is 0. After
executing p += 3, p points to the fourth element of the array,
which is 3. Therefore, the first printf statement outputs 3.
After that, p is modified again with p -= 2. Now p points to the second element
of the array, which is 1. Therefore, the second printf statement outputs 1.
Therefore, the correct option is (A) 3 1.
Question 130
Consider the following C function.
int f(int arr[], int
n) { int i, j; for (i
= 0; i < n; i++)
{
for (j = i + 1; j < n; j++) { if (arr[i] < arr[j]) {
break;
}
}
if (j == n) {return arr[i];
}
}
return -1;
}
The function takes an integer array and its size as input, and returns the largest element in the array which is
larger than all the elements to its right. If there is no
such element, it returns -1. What is the output of
the following program? int main() {
int arr[] = {2, 3, 5, 8, 10, 6};
printf("%d\n", f(arr, 6));
return 0;
Solution 130
Solution C
The function f finds the largest element in the array that is larger than all the
elements to its right. For the given input array arr, the function will return 6,
because it is the largest element in the array that is larger than the element to its
right (i.e., arr[5] is less than arr[4], but greater than all theother elements to its
right).
Therefore, the output of the program is 6. The correct option is (C).
Question 131
Consider the following C program. void print(char *str) {
if (*str == '\0') { return;
} else {
print(str + 1); printf("%c", *str);
}
}
int main() {
char str[] = "hello world"; print(str);
return 0;
}
What is the output of
the program?
(A)dlrow olleh
(B)dlroW olleH
(C)olleH
dlroW
(D)olleh
world
Solution 131
Solution A
The print function recursively prints the characters of the input string in reverse
order. It first checks whether the current character is the null character, which
marks the end of the string. If it is not the null character, it makes a recursive call
to print with the next character in the string, and then prints the current character.
For the input string "hello world", the print function will print the characters in
reverse order, resulting in the output "dlrow olleh". Therefore, the correct option is
(A).
Question 132
What may be the psuedo code for finding the size of a tree?
a) find_size(root_node–>left_node) + 1 + find_size(root_node–>right_node)
b) find_size(root_node–>left_node) + find_size(root_node–>right_node)
c) find_size(root_node–>right_node) – 1
d) find_size(root_node–>left_node + 1
Solution 132
Answer: a
Explanation: Draw a tree and analyze the expression. we are
always taking size of left subtree and right subtree and adding
root value(1) to it and finally printing size.
Question 133
What is the code below trying to print?
void print(tree *root,tree *node)
{ if(root ==null) return 0
if(root-->left==node || root-->right==node) || print(root->left,node) ||printf(root-
>right,node)
{
print(root->data)
}
}
A) just printing all nodes
b) not a valid logic to do any task
c) printing ancestors of a node passed as argument
d) printing nodes from leaf node to a node passed as argument
Solution 133
Answer: c
Explanation: We are checking if left or right node is what the
argument sent or else if not the case then move to left node or
right node and print all nodes while searching for the argument
node.
Question 134
Answer: b
Explanation: If a binary tree is represented in an array, parent
nodes are found at indices (i-1)/2.
Question 135
Which of the following properties are obeyed by all three tree – traversals?
a) Left subtrees are visited before right subtrees
b) Right subtrees are visited before left subtrees
c) Root node is visited before left subtree
d) Root node is visited before right subtree
Solution 135
Answer: a
Explanation: In preorder, inorder and postorder traversal the left subtrees
are visited before the right subtrees. In Inorder traversal, the Left subtree
is visited first then the Root node then the Right subtree. In postorder
traversal, the Left subtree is visited first, then Right subtree and then the
Root node is visited
Question 136
Consider the following C program. #include <stdio.h>
int main()
{ int arr[10];
printf("%d, %d\n", arr[0], arr[9]);
return 0;
}
What is the output of the
program?
(A) 0, 0
(B) 1, 10
(C)Garbage,
Garbage
(D)Compiler error
Solution 136
Solution C
The output of the program is unpredictable and can vary from system to
system.
The array arr is not initialized and its elements contain garbage
values.Accessing uninitialized variables or arrays can lead to undefined
behavior. In this case, the program may print any values for arr[0] and
arr[9],depending on the garbage values stored in
these memory locations.
Question 137
int main() {
int arr[] = {5, 2, 9, 4, 3, 1, 0, 8, 6, 7};
int i, j;
for (i = 0; i < 9; i++) {
j = i + 1;
while (j > 0 && arr[j-1] > arr[j]) { int temp = arr[j];
arr[j] = arr[j-1]; arr[j-1] = temp; j = j - 1;
}
}
for (i = 0; i < 10; i++) printf("%d ", arr[i]);
return 0;
}
Solution 139
program is: 0 1 2 3 4 5 6 7 8 9.
Question 140
Consider the following C function:
void transpose(int n, int A[][n]) { int i, j, tmp;
for (i = 0; i < n; i++) {
for (j = i+1; j < n; j++) { tmp = A[i][j];
A[i][j] = A[j][i];
A[j][i] = tmp;
}
}
}
Assuming that the matrix A icontiguous block of memory, what is the formula to
access the (i,j)th s stored in row-major order in a
element of A?
Solution 140
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int *p = a, *q = &a[8]; printf("%d", (*p)++);
printf("%d", ++(*q));
printf("%d", (*p) + (*q));
printf("%d", ++(*p) + ++(*q)); return 0;
}
.
Solution 141
#include<stdio.h>
int main()
{ int
a=5,*p=&a,**q=&
p;
**q=6;
printf("%d\n",a); return 0;
}
a)5
b)6
c)0
d)Compiler error
Solution 142
The output of the given C code is 6. Explanation:
The variable a is initialized to 5, and a pointer variable p is
initialized to the address of a. A d•ouble pointer variable
q is initialized to the address of p.
The statement **q = 6; assigns the value 6 to the variable pointed to by q, which is a.
Therefore, the value of a is now 6.
The printf statement prints the value of a, which is 6.
Hence, the correct option is (b) 6.
Question 143
I.A pointer can be incremented or decremented to point to the next or previous element of
an array.
II.A pointer can be dereferenced to access the value stored at the memory location it points
to.
III.A pointer can be used to pass an array as a
parameter to a function. a)Only I and II are
true
b)Only II and III are true
c)Only I and III are true
Solution 143
The correct answer is option (d) I, II, and III are all true. Explanation:
I.A pointer can be incremented or decremented to point to the next or previous
element of an array.
This is true. In C, pointers can be used to access elements of an array by
incrementing or decrementing the pointer to point to the next or previous
element in the array. For example, if ptr is a pointer to an integer, then ptr+
+ will point to the next integer in memory.
II.A pointer can be dereferenced to access the value stored at the memory location
it points to.
This is also true. Dereferencing a pointer means accessing the value stored at the
memory location pointed to by the pointer. For example, if ptr is a
pointer to an integer, then *ptr will give the value stored at the memory location pointed to by ptr.
III. A pointer can be used to pass an array as a parameter to a function. This is true. In C, arrays
are passed to functions by using a pointer to the first element of the array. For example, if arr is
an array of integers, then itcan be passed to a function like this: function_name(arr)
orfunction_name(&arr[0]), where function_name is the name of the function.
Question 144
a)H
b)e
c)l
d)o
Solution 144
The output of the given C code is e. Explanation:
The variable str is initialized with the string "Hello".
A pointer variable p is initialized to point to the first character of the string str.
The statement *++p increments the value of p by one, which makes it point to
the second character of the string, and then dereferences the pointer to print the
value of the second character, which is e.
Therefore, the output is e.
The function of the given Linked List with the first node as the head is:- void
funx1(struct node* head)
{
if (head == NULL) return;
funx1 (head -> next) ;
printf (" %d ", head -> data ) ;
}
A.It will print all the nodes of linked lists.
B.It will print all the nodes of the linked list in reverse order.
C.It will print alternate nodes of the Linked List
D.It will print alternate nodes in reverse order
Solution 146
Solution B.
It will print all the nodes of the linked list in reverse order. funx1() prints the
given Linked List in reverse order. For Linked List (1->2->3->4->5),
funx1() prints 5->4->3->2->1.
Question 147
Please choose the correct option about the Linked List compared with an array.
A.Arrays have a better cache locality to it will increase their performance.
B.It is easy to insert and delete elements from the Linked List.
C.Random access is denied in a typical implementation of Linked Lists.
D.The size of an array is fixed; linked lists can change their size.
E.All of the above
Solution 147
Solution: E.
All four statements are correct. Data structure having a better
cache will
increase its performance. Deletion and Insertion are easy in a
linked list and the size of the array is fixed while the linked list can
change it.
Question 148
Consider the following function that references a Doubly Linked List head as a parameter. Consider that a node of the
doubly linked list has the previous pointer and the next pointer as next.
void fun(struct node **head_ref)
{
struct node *temp = NULL; struct node *current = *head_ref;
if(temp != NULL )
*head_ref = temp->prev;
}
Consider that reference head of the doubly linked list and passed to the above function as (1<->2<->3<->4<->5<->6).
Which of the
following
Q8 is a modified, linked list after the function call?
>
Solution: C.
6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1
The function will reverse the doubly linked list by swiping the addresses of
the node.
Question 149
Which algorithms can be used to sort a random linked list with minimum time
complexity?
A.Insertion Sort
B.Quick Sort
C.Heap Sort
D.Merge Sort
Solution 149
Solution: D.
135531
fun () prints some of the linked List nodes provided, first from head to end and then
from end to the head. If the Link List has the same number of nodes, then
skip the last one.
Question 151
The following 'C' programming function takes a simply-linked list as an input argument and modifies the list by moving the
front of the list from the last
element to the and returns the revised list. Some part of the code is left incomplete. Choose the
correct alternative to fill the blank line. typedef struct node
{
int value;
struct node *next;
}Node;
Solution: D
q -> next = NULL ; p -> next = head ; head = p ;
As we know, p is the last node. If we set it to head, it will become the
starting point of the linked list, and we also have to remove the earlier
head element point it as the null
Question 152
.
Suppose every set is represented as a linked list with elements in arbitrary order. Which
operations among union, intersection, membership, cardinality will be the slowest?
A.union only
B.intersection, membership
C.membership, cardinality
D.union, intersection
Solution 152
Were you given pointers to the first and last nodes of a singly
linked list, an Option that depends on the linked list's length?
A.Delete the first element.
B.Insert a new element as the first element.
C. Delete the last element.
D. Add element at the end of the list
Solution 154
Solution B
The function checks if the current element is less than or equal to the next
element, and recursively applies the same check to the next element. If
the end of the list is reached (i.e., p->next is NULL), or the next element is
lessthan the current element, the
function returns 1. Otherwise, it returns 0.
Therefore, the function returns 1 only if the linked list is sorted in non-
decreasing order.
Question 156
Solution A
as we can not get rear from front in O(1), but if p is rear we can implement both
enQueue and deQueue in O(1) because from rear we can get front in O(1).
Question 157
Which of the following graph traversals closely imitates level order
traversal of a binary tree?
a) Depth First Search
b) Breadth First Search
c) Depth & Breadth First Search
d) Binary Search
Solution 157
Answer: b
Explanation: Both level order tree traversal and breadth first
graph traversal follow the principle that visit your neighbors first
and then move on to further nodes
Question 158
In a binary search tree, which of the following traversals would print the
numbers in the ascending order?
a) Level-order traversal
b) Pre-order traversal
c) Post-order traversal
d) In-order traversal
Solution 158
Answer: d
Explanation: In a binary search tree, a node’s left child is always lesser
than the node and right child is greater than the node, hence an in-order
traversal would print them in a non decreasing fashion.
Sanfoundry Global Educatio
Question 159
Answer: c
Explanation: A binary tree, which is completely filled, with the possible
exception of the bottom level, which is filled from left to right is called
complete binary tree. A Tree in which each node has exactly zero or two
children is called full binary tree. A Tree in which the degree of each node
is 2 except leaf nodes is called perfect binary tree.
Question 160
Consider the following data. The pre order traversal of a binary tree is A, B,
E, C, D. The in order traversal of the same binary tree is B, E, A, D, C. The
level order sequence for the binary tree is _________
a) A, C, D, B, E
b) A, B, C, D, E
c) A, B, C, E, D
d) D, B, E, A, C
Solution 161
Answer: c
Explanation: The inorder sequence is B, E, A, D, C and
Preorder sequence is A, B, E, C, D. The tree constructed with
the inorder and preorder sequence i
Question 162
Consider the following data and specify which one is Preorder Traversal
Sequence, Inorder and Postorder sequences.
S1: N, M, P, O, Q
S2: N, P, Q, O, M
S3: M, N, O, P, Q
a) S1 is preorder, S2 is inorder and S3 is postorder
b) S1 is inorder, S2 is preorder and S3 is postorder
c) S1 is inorder, S2 is postorder and S3 is preorder
d) S1 is postorder, S2 is inorder and S3 is preorder
Solution 162
Answer: c
Explanation: Preorder traversal starts from the root node and postorder
and inorder starts from the left child node of the left subtree. The first
node of S3 is different and for S1 and S2 it’s the same. Thus, S3 is preorder
traversal and the root node is M. Postorder traversal visits the root node at
last. S2 has the root node(M) at last that implies S2 is postorder traversal.
S1 is inorder traversal as S2 is postorder traversal and S3 is preorder
traversal. Therefore, S1 is inorder traversal, S2 is postorder traversal and
S3 is preorder traversal.
Question 163
Answer: c
Explanation: The last, second last nodes visited in post-order traversal are
root and it’s right child respectively. Option T Q R S O P can’t be a pre-
order traversal, because nodes O, P are visited after the nodes Q, R, S.
Option T O Q R P S, can’t be valid, because the pre-order sequence given
in option T O Q R P S and given post-order traversal creates a tree with
node T as root and node O as left subtree. Option T Q O P S R is valid.
Option T Q O S P R is not valid as node P is visited after visiting node S.
Question 164
A binary search tree contains values 7, 8, 13, 26, 35, 40, 70, 75. Which one
of the following is a valid post-order sequence of the tree provided the pre-
order sequence as 35, 13, 7, 8, 26, 70, 40 and 75?
a) 7, 8, 26, 13, 75, 40, 70, 35
b) 26, 13, 7, 8, 70, 75, 40, 35
c) 7, 8, 13, 26, 35, 40, 70, 75
d) 8, 7, 26, 13, 40, 75, 70, 35
Solution 164
Answer: d
Explanation: The binary tree contains values 7, 8, 13, 26, 35, 40,
70, 75. The given pre-order sequence is 35, 13, 7, 8, 26, 70, 40
and 75. So, the binary search tree formed is
Thus post-order sequence for the tree is 8, 7, 26, 13, 40, 75, 70
and 35.
Question 165
Answer: a
Explanation: Every node in a full binary tree has either 0 or 2
children. A binary tree can be generated by two traversals if one
of them is in-order. But, we can generate a full binary tree using
post-order and pre-order traversals.
Question 166
The maximum number of nodes in a tree for which post-order and pre-
order traversals may be equal is ______
a) 3
b) 1
c) 2
d) any number
Solution 166
Answer: b
Explanation: The tree with only one node has post-order and pre-
order traversals equal
Question 167
Answer: d
Explanation: In the worst case we have d stack frames in the
recursive call, hence the complexity is O(d).
Question 169
Answer: a
Explanation: Array indexing starts from 0.
Question 170
Answer: c
Explanation: Trying to access an element beyond the limits of an
array gives ArrayIndexOutOfBoundsException.
Question 171
Answer: b
Explanation: ArrayIndexOutOfBoundsException is a run-time
exception and the compilation is error-free
Question 172
Answer: d
Explanation: Whenever a particular memory location is referred
to, it is likely that the locations nearby are also referred, arrays
are stored as contiguous blocks in memory, so if you want to
access array elements, spatial locality makes it to access quickly.
Question 173
Answer: d
Explanation: Arrays store elements of the same data type and
present in continuous memory locations.
10. What are the disadvantages of arrays?
a) Data structure like queue or stack cannot be implemented
b) There are chances of wastage of memory space if elements
inserted in an array are lesser than the allocated size
c) Index value of an array can be negative
d) Elements are sequentially accessed
Solution 174
Answer: b
Explanation: Arrays are of fixed size. If we insert elements less
than the allocated size, unoccupied positions can’t be used again.
Wastage will occur in memory.
Question 175
Answer: b
Explanation: Push operation allows users to insert elements in the
stack. If the stack is filled completely and trying to perform push
operation stack – overflow can happen.
Question 176
Answer: a
Explanation: Underflow occurs when the user performs a pop operation on
an empty stack. Overflow occurs when the stack is full and the user
performs a push operation. Garbage Collection is used to recover the
memory occupied by objects that are no longer used.
Question 177
Answer: d
Explanation: In stack data structure, elements are added one by
one using push operation. Stack follows LIFO Principle i.e. Last In
First Out(LIFO).
Question 178
Answer: d
Explanation: Data transfer between the two asynchronous process
uses the queue data structure for synchronisation. The rest are all
stack applications.
Question 179
Answer: b
Explanation: In the entire parenthesis balancing method when the
incoming token is a left parenthesis it is pushed into stack. A right
parenthesis makes pop operation to delete the elements in stack till we
get left parenthesis as top most element. 2 left parenthesis are pushed
whereas one right parenthesis removes one of left parenthesis. 2 elements
are there before right parenthesis which is the maximum number of
elements in stack at run time.
Question 180
Answer: d
Explanation: Postfix Expression is (6*(3-(2+4))) which results -18
as output.
Question 181
Answer: d
Explanation: When we perform the conversion from infix to postfix
expression +, *, (, * symbols are placed inside the stack. A maximum of 4
symbols are identified during the entire conversion.
Question 182
Answer: a
Explanation: The stack is a simple data structure in which elements are
added and removed based on the LIFO principle. Open parenthesis is
pushed into the stack and a closed parenthesis pops out elements till the
top element of the stack is its corresponding open parenthesis. If the stack
is empty, parenthesis is balanced otherwise it is unbalanced
Question 183
Answer: b
Explanation: Infix expression is (A*B)+(C/D)
AB*+(C/D)
AB*CD/+. Thus postfix expression is AB*CD/+.
Question 184
Answer: a
Explanation: The given infix expression is (A + B ⋀D)/(E – F)+G.
(A B D ^ + ) / (E – F) +G
(A B D ^ + E F – ) + G. ‘/’ is present in stack.
A B D ^ + E F – / G +. Thus Postfix Expression is A B D ^ + E F – / G +
Question 185
Answer: a
Explanation: The Infix Expression is x + y * z + (p * q + r) * s.
(x y z ) + (p * q + r) * s. ‘+’, ‘*’ are present in stack.
(x y z * + p q * r) * s. ‘+’ is present in stack.
x y z * + p q * r + s * +. Thus Postfix Expression is x y z * + p q * r + s * +.
Question 186
Which of the following statement(s) about stack data structure is/are NOT
correct?
a) Linked List are used for implementing Stacks
b) Top of the Stack always contain the new node
c) Stack is the FIFO data structure
d) Null link is present in the last node at the bottom of the stack
Solution 186
Answer: c
Explanation: Stack follows LIFO.
Question 187
Assume that the operators +,-, X are left associative and ^ is right
associative. The order of precedence (from highest to lowest) is ^, X, +, -.
The postfix expression for the infix expression a + b X c – d ^ e ^ f is?
a) abc X+ def ^^ –
b) abc X+ de^f^ –
c) ab+c Xd – e ^f^
d) -+aXbc^ ^def
Solution 187
Answer: b
Explanation: Given Infix Expression is a + b X c – d ^ e ^ f. And X is right
associative. Thus the final postfix expression is abc X+def^^-
Question 188
If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted
one at a time, what is the order of removal?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
Solution 188
Answer: b
Explanation: Stack follows LIFO(Last In First Out). So the removal order of
elements are DCBA
Question 189
A linear list of elements in which deletion can be done from one end
(front) and insertion can take place only at the other end (rear) is known as
_____________
a) Queue
b) Stack
c) Tree
d) Linked list
Solution 189
Answer: a
Explanation: Linear list of elements in which deletion is done at front side
and insertion at rear side is called Queue. In stack we will delete the last
entered element first.
Question 190
If the elements “A”, “B”, “C” and “D” are placed in a queue and are
deleted one at a time, in what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
Solution 190
Answer: a
Explanation: Queue follows FIFO approach. i.e. First in First Out Approach.
So, the order of removal elements are ABCD
Question 191
Answer: b
Explanation: Queue always has two ends. So, single ended queue is
not the type of queue.
Question 192
Consider an implementation of unsorted singly linked list. Suppose it has
its representation with a head pointer only. Given the representation,
which of the following operation can be implemented in O(1) time?
i) Insertion at the front of the linked list ii) Insertion at the end of the
linked list
iii) Deletion of the front node of the linked list iv) Deletion of the last node
of the linked list
a) I and II
b) I and III
c) I, II and III
d) I, II and IV
Solution 192
Answer: b
Explanation: We know the head node in the given linked list. Insertion and
deletion of elements at the front of the linked list completes in O (1) time
whereas for insertion and deletion at the last node requires to traverse
through every node in the linked list. Suppose there are n elements in a
linked list, we need to traverse through each node. Hence time complexity
becomes O(n).
Question 193
. In linked list each node contains a minimum of two fields. One field is
data field to store the data second field is?
a) Pointer to character
b) Pointer to integer
c) Pointer to node
d) Node
Solution 193
Answer: c
Explanation: Each node in a linked list contains data and a pointer
(reference) to the next node. Second field contains pointer to node
Question 194
What would be the asymptotic time complexity to add a node at the end
of singly linked list, if the pointer is initially pointing to the head of the list?
a) O(1)
b) O(n)
c) θ(n)
d) θ(1)
Solution 194
Answer: c
Explanation: In case of a linked list having n elements, we need
to travel through every node of the list to add the element at the
end of the list. Thus asymptotic time complexity is θ(n)
Question 195
Answer: a
Explanation: To add an element at the front of the linked list, we will create
a new node which holds the data to be added to the linked list and pointer
which points to head position in the linked list. The entire thing happens
within O (1) time. Thus the asymptotic time complexity is O (1).
Question 196
Answer: a
Explanation: As it represents the right way to create a node.
Question 197
What kind of linked list is best to answer questions like “What is the item
at position n?”
a) Singly linked list
b) Doubly linked list
c) Circular linked list
d) Array implementation of linked list
Solution 197
Answer: d
Explanation: Arrays provide random access to elements by providing the
index value within square brackets. In the linked list, we need to traverse
through each element until we reach the nth position. Time taken to
access an element represented in arrays is less than the singly, doubly and
circular linked lists. Thus, array implementation is used to access the item
at the position n
Question 198
Answer: c
Explanation: Linked lists saves both space and time.
Question 199
. Which of the following points is/are not true about Linked List data
structure when it is compared with an array?
a) Arrays have better cache locality that can make them better in terms of
performance
b) It is easy to insert and delete elements in Linked List
c) Random access is not allowed in a typical implementation of Linked Lists
d) Access of elements in linked list takes less time than compared to
arrays
Solution 199
Answer: d
Explanation: To access an element in a linked list, we need to
traverse every element until we reach the desired element. This
will take more time than arrays as arrays provide random access to
its elements.
Question 200
What is the output of following function for start pointing to first node of following
linked list?
1->2->3->4->5->6
void fun(struct node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data); }
a) 1 4 6 6 4 1
b) 1 3 5 1 3 5
c) 1 2 3 5
d) 1 3 5 5 3 1
Solution 200
Answer: d
Explanation: fun() prints alternate nodes of the given Linked List, first from
head to end, and then from end to head.
If Linked List has even number of nodes, then skips the last node.
Question 201
Given pointer to a node X in a singly linked list. Only one pointer is given,
pointer to head node is not given, can we delete the node X from given
linked list?
a) Possible if X is not last node
b) Possible if size of linked list is even
c) Possible if size of linked list is odd
d) Possible if X is not first node
Solution 201
Answer: a
Explanation: Following are simple steps.
struct node *temp = X->next;
X->data = temp->data;
X->next = temp->next;
free(temp);
Question 202
You are given pointers to first and last nodes of a singly linked list, which of
the following operations are dependent on the length of the linked list?
a) Delete the first element
b) Insert a new element as a first element
c) Delete the last element of the list
d) Add a new element at the end of the list
Solution 202
Answer: c
Explanation: Deletion of the first element of the list is done in O (1) time
by deleting memory and changing the first pointer.
Insertion of an element as a first element can be done in O (1) time. We
will create a node that holds data and points to the head of the given
linked list. The head pointer was changed to a newly created node.
Deletion of the last element requires a pointer to the previous node of last,
which can only be obtained by traversing the list. This requires the length
of the linked list.
Adding a new element at the end of the list can be done in O (1) by
changing the pointer of the last node to the newly created node and last is
changed to a newly created node.
Question 203
Answer: d
Explanation: The worst-case happens if the required element is at last or
the element is absent in the list. For this, we need to compare every
element in the linked list. If n elements are there, n comparisons will
happen in the worst case.
Question 204
Answer: d
Explanation: Array elements can be accessed in two steps. First, multiply
the size of the data type with the specified position, second, add this value
to the base address. Both of these operations can be done in constant
time, hence accessing elements at a given index/position is faster
Question 205
Answer: d
Explanation: Depending on whether the array is full or not, the complexity
in dynamic array varies. If you try to insert into an array that is not full,
then the element is simply stored at the end, this takes O(1) time. If you
try to insert into an array which is full, first you will have to allocate an
array with double the size of the current array and then copy all the
elements into it and finally insert the new element, this takes O(n) time.
Question 206
Answer: d
Explanation: To implement file system, for separate chaining in hash-tables
and to implement non-binary trees linked lists are used. Elements are
accessed sequentially in linked list. Random access of elements is not an
applications of linked list
Question 207
Answer: d
Explanation: A doubly linked list has two pointers ‘left’ and ‘right’ which
enable it to traverse in either direction. Compared to singly liked list which
has only a ‘next’ pointer, doubly linked list requires extra space to store
this extra pointer. Every insertion and deletion requires manipulation of
two pointers, hence it takes a bit longer time. Implementing doubly linked
list involves setting both left and right pointers to correct nodes and takes
more time than singly linked list
Question 208
Answer: a
Explanation: Memory efficient doubly linked list has only one pointer to
traverse the list back and forth. The implementation is based on pointer
difference. It uses bitwise XOR operator to store the front and rear pointer
addresses. Instead of storing actual memory address, every node store the
XOR address of previous and next nodes.
Question 209
Answer: b
Explanation: The pointer difference is calculated by taking XOR of pointer
to previous node and pointer to the next node.
Question 210
Answer: c
Explanation: The ‘next’ pointer points to null only when the list is empty,
otherwise it points to the head of the list. Every node in a circular linked
list can be a starting point(head).
Question 211
Answer: c
Explanation: Generally, round robin fashion is employed to allocate CPU
time to resources which makes use of the circular linked list data structure.
Recursive function calls use stack data structure. Undo Operation in text
editor uses doubly linked lists. Hash tables uses singly linked lists.
Question 212
Consider a small circular linked list. How to detect the presence of cycles
in this list effectively?
a) Keep one node as head and traverse another temp node till the end to
check if its ‘next points to head
b) Have fast and slow pointers with the fast pointer advancing two nodes
at a time and slow pointer advancing by one node at a time
c) Cannot determine, you have to pre-define if the list contains cycles
d) Circular linked list itself represents a cycle. So no new cycles cannot be
generated
Solution 212
Answer: b
Explanation: Advance the pointers in such a way that the fast pointer
advances two nodes at a time and slow pointer advances one node at a
time and check to see if at any given instant of time if the fast pointer
points to slow pointer or if the fast pointer’s ‘next’ points to the slow
pointer. This is applicable for smaller lists.
Question 213
Answer: b
Explanation: Time complexity of inserting a new node at the head of the
list is O(n) because you have to traverse through the list to find the tail
node.
Question 214
Which of the following real world scenarios would you associate with a
stack data structure?
a) piling up of chairs one above the other
b) people standing in a line to be serviced at a counter
c) offer services based on the priority of the customer
d) tatkal Ticket Booking in IRCTC
Solution 214
Answer: a
Explanation: Stack follows Last In First Out (LIFO) policy. Piling up of chairs
one above the other is based on LIFO, people standing in a line is a queue
and if the service is based on priority, then it can be associated with a
priority queue. Tatkal Ticket Booking Follows First in First Out Policy. People
who click the book now first will enter the booking page first.
Question 215
Answer: c
Explanation: Removing items from an empty stack is termed as
stack underflow.
Question 216
What happens when you pop from an empty stack while implementing
using the Stack ADT in Java?
a) Undefined error
b) Compiler displays a warning
c) EmptyStackException is thrown
d) NoStackException is thrown
Solution 216
Answer: c
Explanation: The Stack ADT throws an EmptyStackException if the
stack is empty and a pop() operation is tried on it.
Question 217
Answer: a
Explanation: You cannot modify the size of an array once the memory has
been allocated, adding fewer elements than the array size would cause
wastage of space, and adding more elements than the array size at run
time would cause Stack Overflow.
Question 218
Answer: a
Explanation: Array indexing start from 0, hence N-1 is the last
index.
Question 219
Which of the following statements are not correct with respect to Singly
Linked List(SLL) and Doubly Linked List(DLL)?
a) Complexity of Insertion and Deletion at known position is O(n) in SLL
and O(1) in DLL
b) SLL uses lesser memory per node than DLL
c) DLL has more searching power than SLL
d) Number of node fields in SLL is more than DLL
Solution 219
Answer: d
Explanation: To insert and delete at known positions requires complete
traversal of the list in worst case in SLL, SLL consists of an item and a node
field, while DLL has an item and two node fields, hence SLL occupies lesser
memory, DLL can be traversed both ways(left and right), while SLL can
traverse in only one direction, hence more searching power of DLL. Node
fields in SLL is 2 (data and address of next node) whereas in DLL is 3(data,
address to next node, address to previous node).
Question 220
Answer: a
Explanation: When Rear = MAX_SIZE – 1, there will be no space left for the
elements to be added in queue. Thus queue becomes full.
Question 221
Answer: c
Explanation: This code is only retrieving the top element, note that
it is not equivalent to pop operation as you are not setting the
‘next’ pointer point to the next node in sequence.
Question 222
Answer: b
Explanation: Adding items to a full stack is termed as stack
underflow.
Question 223
In a circular queue, how do you increment the rear end of the queue?
a) rear++
b) (rear+1) % CAPACITY
c) (rear % CAPACITY)+1
d) rear–
Solution 223
Answer: b
Explanation: Ensures rear takes the values from 0 to (CAPACITY-
1).
Question
224
What is the term for inserting into a full queue known as?
a) overflow
b) underflow
c) null pointer exception
d) program won’t be compiled
Solution 224
Answer: a
Explanation: Just as stack, inserting into a full queue is termed
overflow
Question 225
Answer: a
Explanation: In a linear queue, dequeue operation causes the starting
elements of the array to be empty, and there is no way you can use that
space, while in a circular queue, you can effectively use that space. Priority
queue is used to delete the elements based on their priority. Higher
priority elements will be deleted first whereas lower priority elements will
be deleted next. Queue data structure always follows FIFO principle.
Question 226
Answer: c
Explanation: The size of array is fixed in normal arrays. We need
to know the number of nodes in the tree before array declaration.
It is the main disadvantage of using arrays to represent binary
trees.
Question 227
What must be the ideal size of array if the height of tree is ‘l’?
a) 2l-1
b) l-1
c) l
d) 2l
Solution 227
Answer: a
Explanation: Maximum elements in a tree (complete binary tree
in worst case) of height ‘L’ is 2 L-1. Hence size of array is taken as
2L-1.
Question 228
What are the children for node ‘w’ of a complete-binary tree in an array
representation?
a) 2w and 2w+1
b) 2+w and 2-w
c) w+1/2 and w/2
d) w-1/2 and w+1/2
Solution 228
Answer: a
Explanation: The left child is generally taken as 2*w whereas the right child
will be taken as 2*w+1 because root node is present at index 0 in the
array and to access every index position in the array.
Question 229
What is the parent for a node ‘w’ of a complete binary tree in an array
representation when w is not 0?
a) floor(w-1/2)
b) ceil(w-1/2)
c) w-1/2
d) w/2
Solution 229
Answer: a
Explanation: Array cannot represent arbitrary shaped trees. It can only be
used in case of complete trees. If every node stores data saying that which
of its children exists in the array then elements can be accessed easily.
Question 230
In a complete k-ary tree, every internal node has exactly k children. The
A. nk
B. (n –1) k+ 1
C. n( k –1) + 1
D. n( k –1)
Solution 230
For an k-ary tree where each node has k children or no children, following relation
holds L = (k-1)*n + 1 Where L is the number of leaf nodes and n is
k=3
=9
Question 231
Given 8 identical coins out of which one coin is heavy and a pan balance.
How many minimum number of measurements are needed to find the
heavy coin?
A. 2
B. 3
C. 4
D. 7
Solution 131
Divide the coins into three groups and name the coins according to there group: A: A1, A2, A3
measurements needed.
So, the above observations says that in any case, 2 measurements are enough
to find the heavy coin.
Question 232
There are 25 horses among which you need to find out the fastest 3 horses.
You can conduct race among at most 5 to find out their relative
speed. At no point you can find out the actual speed of the horse in a race. Find out
B. 7
C. 8
D. 9
Solution 234
Divide the horses in 5 groups and run 5 races. Take toppers of 5 races and run
6th race more race, the topper of this race will be the fastest
horse among all 25. Now run the 7th race among following horses. 1) Second
and third fastest horses of 6th race 1) Take the second and third
fastest horses of the group which belong to the topper of 6th race. 2) Take the
horse of 6th race. The fastest and second fastest of 7th race are the 2nd and 3rd
Which one of the following statements is TRUE for all positive functions
f(n) ?
A. f(n2) =(f(n)2), when f(n) is a polynomial
B. f(n2) = o(f(n)2)
D. f(n2) = Ω(f(n)2)
Solution 235
Answer: (A)
Explanation:
Option A: It always holds because if we square the input variable, then the highest
In this method, we directly implement the formula for the nth term in the Fibonacci series.
Fn = {[(√5 + 1)/2] ^ n} / √5
Note: Above Formula gives correct result only upto for n<71. Because as we move forward
from n>=71 , rounding error becomes
significantly large . Although , using floor function instead of round function will give
correct result for n=71 . But after from n=72 , it also fails.
Example: For N=72 , Correct result is 498454011879264 but above formula gives
498454011879265.
Question 237
T(n) = T(n^(1/a)) → n^(1/a^k)
+1, T(b) = 1 = b
→ log(n^(1/a^k)) = log(b)
Now, using iterative → ak = log(n) / log (b) =
method, log_b(n)
= T(n) → k = log_a log_b(n)
= [T(n^(1/a))+1] + 1 Therefore,
= [T(n^(1/a^3))+1] + 2
= T(n^(1/a^k)) + k
= [T(n^(1/a^4))+1] + 3
= T(b) + log_a log_b(n)
.
= [T(n^(1/a^k))+1] + = 1 + log_al og_b(n)
(k-1)
= Θ(log_a
= T(n^(1/a^k)) + k
Let, log_b(n)) Option
Question 238
which is
O(nLogLogn)
Question 239
Consider the following program fragment for reversing the digits in a given
integer to obtain a new integer. Let n = D1D2…Dm
int n, rev;
rev = 0;
while (n
> 0)
{
rev = rev*10 + n%10;
n = n/10;
}
The loop invariant condition at the end of the ith iteration is:
A. n = D1D2….Dm-i and rev = DmDm-1… Dm- i+1
B. n = Dm-i+1…Dm-1Dm and rev = Dm-1….D2D1
C. n != rev
D. n = D1D2….Dm and rev = DmDm-1…D2D1
Solution
239
SOLUTION A
The loop one by adds digits to rev starting from the last digit of n. It also
Answer:
(C)
Answer:
(C)
of 1.....n ?
A. n(n - 1)/2
B. n(n - 1)/4
C. n(n + 1)/4
D. 2n[log2 n]
Solution 242
C O((log n)^k) for some constant k > 0, but not O ((log log n)^m) for
To answer that question, you need to find upper and perhaps lower bounds on the
complexity of finding an integer cube root m of n. At least one upper bound is
trivial, and rules out answers A and B: m can be found in O(log n) time using
binary search.
Also note that the input size is O(log n) because the minimum number of bits
needed to represent an arbitrary n in binary notation is proportional to log n.
Because all bits of the number must be processed to solve the problem, θ(log n)
is a lower bound on the time to solve the problem, and therefore the problem
cannot be solved in time O((log log n)^w) [where w is some constant > 0]
because that isn't O(log n). Thus, answer C applies.
Question 244
The following are the starting and ending times of activities A, B, C, D, E, F, G and
H respectively in chronological order: "asbscsaedsceesfsbedegseefehsgehe" Here,
xs denotes the starting time and xe denotes the ending time of activity X. W 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. 3
B. 4
C. 5
D. 6
Solution 244
Warshall’s algorithm can be used to construct the Transitive closure of directed graphs ().
In Warshall’s original formulation of the algorithm, the graph is unweighted and represented
by a Boolean adjacency matrix. Then the addition operation is replaced by logical
conjunction (AND) and the minimum operation by
logical disjunction (OR).
Question 247
Let a_n represent the number of bit strings of length n containing
two
consecutive 1s. What is the recurrence relation for an?
A. a_(n–2) + a_(n–1) + 2^(n–2)
B. a_(n–2) + 2a_(n–1) + 2^(n–2)
C. 2a_(n–2) + a_(n–1) + 2^(n–2)
D. 2a_(n–2) + 2a_(n–1) + 2^(n–2)
Solution 247
Simple Solution One way to solve this is to try for small values and rule
out options.
a0 = 0
a1
a2 =
=01 ["11"] Number 1 has already two consecutive 1's so
a3 = 3 ["011", "110", "111"] number of binary strings beginning with
a4 = 8 ["0011", "0110", "0111", number 3 is 2n-2
"1101",
"1011", "1100", "1110",
as remaining n-2 bits can have any value.
Number 2 has two 0's so remaining n-2 bits
If we check"1111"]
for a3, we can see that only A and C satisfy the
value. A must have two consecutive 1's. Therefore
mong (A) and (C), only (A) satisfies for a4. Another Solution number of binary strings that can be formed by
(With Proof) number 2 is an-2.
A string of length n (n >= 2) can be formed by Number 3 and Number 4 together form all
following 4 prefixes strings of length
1) 11 followed by a string of
length n-2 n-1 and two consecutive 1's.
2) 00 followed by a string of
length n-2
3) 01 followed by a string of
length n-2
4) 10 followed by a string of
length n-2
Question 248
Given below are some algorithms, and some algorithm design paradigms.
List-I
A.Dijkstra’s Shortest Path
B.Floyd-Warshall algorithm to compute all pairs shortest path
C.Binary search on a sorted array
D.Backtracking search on a graph
List-II
1.Divide and Conquer
2.Dynamic Programming
3.Greedy design
4.Depth-first search
5.Breadth-first search
Match the above algorithms on the left to the corresponding design paradigm they follow
Codes: A B C D
(a) 1 3 1 5
(b) 3 3 1 5
Solution 248
Dijkstra’s Shortest Path is a Greedy Algorithm.
Suppose c = 〈c[0], ... , c[k – 1]〉 is an array of length k, where al the entries are
from the set
{0, 1}. For any positive integers a and n, consider the following pseudocode.
DOSOMETHING (c, a, n)
z ← 1
for i ← 0 to k – 1
do z ← z2 mod
n if c[i] = 1
then z ← (z × a) mod
n return z
If k = 4, c = 〈1, 0, 1, 1〉, a = 2 and n = 8, then the output of DOSOMETHING(c, a, n)
is .
Solution 249
For i = 2, z = 16 mod 8 = 0
Answer: (C)
Explanation:
As list concatenation requires traversing at least one list to the end. So
singly linked list and doubly linked list requires O(n) time complexity
X, Y and Z are closed intervals of unit length on the real line. The overlap of X and
Y is half a unit. The overlap of Y and Z is also half a unit. Let the
A k must be 1
B. k must be 0
C. k can take any value between 0 and 1 (d) None of the above
f2 has logn in
power. f3 has √n
in power.
Hence, f2, f3, f1 is in increasing order.
Note that you can take the log of each function then
compare.
Question 253
The given diagram shows the flowchart for a recursive function A(n). Assume that all
statements, except for the recursive calls, have O(1) time complexity. If the worst
case time complexity of this function is O(n^α), then the least possible value
(accurate up to two decimal positions) of α is
(A) 2.2 to
2.4
(B) 3.2 to
3.4
(C) 0 to 1.8
(D) 1
Solution 253
Question 254
A. Θ(1)
B. Θ(logn)
C. Θ(n)
D. Θ(nlogn)
Solution 254
In case of min heap if we need to find out max element than it should be
present at leave nodes so in worst case we need to search till leaf nodes
we can't perform binary search here because its not BST and heaps need
not be in sorted order so in worst case it would be (n/2)+1. On normalizing
it would be O(n) which is option 3.
Question 255
Consider the following C function. int fun1 (int n)
{
int i, j, k, p, q = 0;
for (i = 1; i < n; ++i)
{
p = 0;
for (j = n; j > 1; j = j/2)
++p;
for (k = 1; k < p; k = k*2)
++q;
}
return q;
}
Which one of the following most closely approximates the return value of the function fun1?
(A) n^3
(B) n (logn)^2
(C) nlogn
(D) nlog(logn)
Solution 255
Answer: (D)
// Since above loop runs Θ(Log n) times, p =
Explanation: Θ(Log n)
int fun1 (int n) // This loop runs Θ(Log p) times
{
which loglogn for (k=1; k < p;
int i, j, k, p, q = 0;
k=k*2)
// This loop runs Θ(n) ++q;
time for (i = 1; i < n;
++i) }
{ return q;
p = 0; }
T(n) = n(logn +
// This loop runs Θ(Log n)
loglogn) T(n) =
times for (j=n; j > 1; j=j/2)
n(logn) dominant
++p;
Question 256
Let f(n) = n and g(n) = n(1+sin n), where n is a positive integer. Which of
I. f(n) = O(g(n))
(A) Only I
(B) Only II
Answer: (D)
G(n) = n!
H(n) = nlogn
Which of the following statements about the asymptotic behaviour of f(n), g(n),
Answer: (D)
Explanation: According to order of growth: h(n) < f(n) < g(n) (g(n) is
asymptotically greater than f(n) and f(n) is asymptotically greater than
h(n)
We can easily see above order by taking logs of the given 3 functions
lognlogn < n < log(n!)(logs of the given f(n), g(n) and h(n)).
Question 258
Consider the following C functions: int f1(int
n){
if(n == 0 || n == 1){ return n;
}
return (2 * f1(n - 1) + 3 * f1(n - 2));
f1(8) and f2(8) return the values A
}
int f2(int n){ 1661 and 1640
int i; B. 59 and 59
int X[N], Y[N], Z[N]; C. 1640 and 1640
X[0] = Y[0] = Z[0] = 0; D. 1640 and 1661
X[1] = 1; Y[1] = 2; Z[1] = 3;
for(i = 2; i <= n; i++){ X[i] = Y[i -
1] + Z[i - 2]; Y[i] = 2 * X[i];
Z[i] = 3 * X[i];
}
return X[n];
Solution 258
Question 259
Consider the following C code segment:
int IsPrime(n){
int i, n;
for(i=2; i<=sqrt(n);i++){
if(n % i == 0){
printf("No prime\n"); return 0;
}
return 1;
}
}
Let T(n) denote the number of times the for loop is executed by the program on input n.
Which of the following is TRUE?
A.T(n) = O (sqrt(n)) and T(n) = Ω(sqrt(n))
B.T(n) = O (sqrt(n)) and T(n) = Ω(1)
C.T(n) = O (n) and T(n) = Ω(sqrt(n))
Solution 259
Answer: (B)
Question 260
= 2/25
= 0.08
Question 261
Assume that the algorithms considered here sort the input sequences in
ascending order. If the input is already in ascending order, which of the
following is TRUE?
I. Quicksort runs in Θ(n^2) time
II. Bubblesort runs in Θ(n^2) time
III. Mergesort runs in Θ(n) time
IV. Insertion sort runs in Θ(n) time
(A) I and II only
(B) I and III only
(C) II and IV only
(D) I and IV only
Solution 261
Answer: (D)
Explanation:
Input is already in ascending order, which means it is the worst-case situation.
Option 1: Quicksort runs in Θ (n^2) time In quick sort worst case if the first or last element
is selected at the pivot element.
For a Quicksort, in the worst-case recurrence, the relation will become T(n) = T(n-1) + T (1) +
n, Which gives T(n) = Θ (n^2) So, it is correct.
Option 2: Bubble sort runs in Θ (n^2) time
If an array is already sorted in ascending order, then at that time there will be no swap after
the completion of the inner for loop of bubble sort. In this way, bubble sort will take Θ (n)
time complexity.
Option 3: Merge sort runs in Θ (n) time
Merge sort uses the divide and conquer policy to sort the elements. As elements are already
sorted in ascending
order.
Option 4: Insertion sort runs in Θ (n) time
When a new element that is greater than all the elements of the
array is added, then there will be no swap but only a single
comparison. In n -1 swaps, only 0 swaps and n-1 comparisons are
there. The total time complexity in this
case will be Θ (n). So, it is correct.
Question 262
The worst case running times of Insertion sort, Merge sort and Quick sort,
respectively, are:
Explanation:
•Insertion Sort takes Θ(n2) in worst case as we need to run two loops. The outer loop is needed to one
by one pick an element to be inserted at right position. Inner loop is used for two things, to find
position of the element to be
inserted and moving all sorted greater elements one position ahead. Therefore the worst case
recursive formula is T(n) = T(n-1) + Θ(n).
•Merge Sort takes Θ(n Log n) time in all cases. We always divide array in two halves, sort the two
halves and merge them. The recursive formula is T(n) = 2T(n/2) + Θ(n).
•QuickSort takes Θ(n2) in worst case. In QuickSort, we take an element as pivot and partition the array
around it. In worst case, the picked element is always a corner element and recursive formula becomes
T(n) = T(n-1) + Θ(n). An example scenario when worst case happens is, arrays is sorted and our code
Question 263
Which one of the following is the recurrence equation for the worst case time
complexity of the Quicksort algorithm for sorting n ( n≥2 ) numbers?
A T(n) = 2T(n/2) + cn
C T(n) = 2T(n - 1) + cn
D T(n) = T(n/2) + cn
Solution
263
Answer: (B)
Explanation:
In the worst case, the chosen pivot is always placed at a corner position
minimum is
(A) Θ(nlogn)
(B) Θ(n)
(C) Θ(logn)
(D) Θ(1)
Solution
264
Answer: (D)
Explanation: We only need to consider any 3 elements and compare them. So the
number of comparisons is constants, that makes time complexity as Θ(1)
The catch here is, we need to return any element that is neither maximum
not minimum.
Let us take an array {10, 20, 15, 7, 90}. Output can be 10 or 15 or 20
Pick any three elements from given liar. Let the three elements be 10, 20 and
〈89,19,50,17,12,15,2,5,7,11,6,9,100〉
is
A. 4
B. 5
C. 2
D. 3
Solution 265
Answer: (D)
Explanation: 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6,
9, 100〉
/
89
19 50
/\ /\
17 12
15
2
/\ /\
/\
Minimum
5
number of swaps required to convert above tree to Max heap is 3. Below are 3 swap
7 11 6
9 100
operations.
Swap 100 with 15
Swap 100 with 50
Swap 100 with 89
/ 100 \
19 89
/\ / \
17 50
12 5
7/ \ /11
\ 6 9
2 15
Question 266
A priority queue is implemented as a Max-Heap. Initially, it has 5 elements. The
level-order traversal of the heap is: 10, 8, 5, 3, 2. Two new
elements 1 and 7 are inserted into the heap in that order. The level-order
A 10, 8, 7, 3, 2, 1, 5
B 10, 8, 7, 2, 3, 1, 5
C 10, 8, 7, 1, 2, 3, 5
D 10, 8, 7, 5, 3, 2, 1
Solution
Answer: (A) 266
Explanation: o need to heapify as 5 is greater
Initially heap has 10, 8, 5, 3, 2 than 1. After insertion of 7
10 10
/
/ \ \
8 5 8
5
/\
/\
3 2 Heapify
/\ 5 as 7 is greater
After insertion of 1 than
3 5
2
1 / 10 7
10 \
8
/ \
7
8 5 /\
No
/\ need to heapify any further as 10 is
/\ /
greater
3 2 than 7
3 21 1 5
Question 267
(A) Θ(n)
(C) Θ(n2 )
As we can see from the algorithm, selection sort performs swap only after finding the
appropriate position of the current picked element. So there are O(n) swaps performed in
selection sort.
Because swaps require writing to the array, selection sort is preferable if writing to memory is
significantly more expensive than reading. This is generally the case if the items are huge but
the keys are small.
Another example where writing times are crucial is an array stored in EEPROM or Flash. There is
Question 268
The most efficient algorithm for finding the number of connected components in
an undirected graph on n vertices and m edges has time
complexity.
(A) theta(n)
(B) theta(m)
(C) theta(m + n)
(D) theta(mn)
Solution 268
Answer: (C)
Explanation:
Connected components can be found in O(m + n) using Tarjan’s
B. Bubble sort
C. Quick sort
D. Selection sort
Solution 269
Answer (A)
Worst case complexities for the above sorting algorithms are as follows:
Merge Sort —
nLogn Bubble Sort —
n^2 Quick
Sort — n^2 Selection
Sort — n^2
Question 270
(A) 0(n)
(B) O(logn)
(C) 0(loglogn)
(D) (D) 0(1)
Solution 270
Answer (A)
In a max heap, the smallest element is always present at a leaf node. So we need
to check for
all leaf nodes for the minimum value. Worst case complexity will be O(n)
12
/ \
/ \
8 7
/ /
/\ \ \ /
\
2 3 4
5
Question 271
An element in an array X is called a leader if it is greater than all elements
(A) Solves it in linear time using a left to right pass of the array
(B) Solves it in linear time using a right to left pass of the array
We start from the last index position. The last position is always a leader, as there are no
Every time we encounter a maximum value than the previous maximum value
encountered, we will store the value in the stack as it is the leader
(A) N
(B) N^2
(C) NlogN
(D) N(logN)^2
Solution 272
Answer: (C)
In a heap with n elements with the smallest element at the root, the 7th
(B) Θ(n)
(C) Θ(log n)
(D) Θ(1)
Solution 273
Answer: (D)
Explanation:
In order to find out the kth smallest element, we have to first extract 6
elements from heap and then root of the resultant heap will be the kth
smallest.Total time complexity = 6 Extract-min operations = 6*log2n =
O(log2n)
But we can find out kth smallest from heap using a clever approach by
extracting elements from heap non-destructively. We will use extra space to
create a new min-heap which will contain maximum k elements at any time.
Question 274
Suppose we want to arrange the ii numbers stored in an array such that all
negative values occur before all positive ones. Minimum number of
(A) n-1
(B) n
(C) n+1
Answer: (D)
A B C
a. 3
1 2
4
b. 3 1
Solution 275
Answer: (B)
Question 276
Consider the following array. 23
32 45 69 72 73 89
97
Which algorithm out of the following options uses the least number of comparisons
(among the array elements) to sort above array in ascending order?
A Insertion sort
B. Selection sort
D. Merge sort
Solution 276
Answer: (C)
Insertion sort will give its best case with time complexity of order O(n).
Question 277
Let a_n represent the number of bit strings of length n containing two
consecutive 1s. What is the recurrence relation for an?
A. a_(n–2) + a_(n–1) + 2^(n–2)
If we check for a3, we can see that only A and C satisfy the value. Among (A) and (C), only (A) satisfies
for a4. Another Solution (With Proof)
A string of length n (n >= 2) can be Number 1 has already two consecutive 1's so
formed by following 4 prefixes number of binary strings beginning with
number 3 is 2n-2
1) 11 followed by a string of as remaining n-2 bits can have any value.
length n-2 Number 2 has two 0's so remaining n-2 bits must
2) 00 followed by a string of have two consecutive 1's. Therefore number of
length n-2 binary strings that can be formed by number 2
3) 01 followed by a string of is an-2.
length n-2 Number 3 and Number 4 together form all strings
4) 10 followed by a string of of length n-1 and two consecutive 1's.
length n-2
Question 278
here node with integer 1 has to be at root only. Now for maximum depth of the
tree the following arrangement can be taken. Take root as level 1.
make node 2 at level 2 as a child node of node 1. make node 3 at level 3 as the
child node of node 2. .. .. and so on for nodes 4,5,6,7 .. make node 8 at level 8 as
the child node of node 7. make node 9 at level 9 as the child node of node 8.
Putting other nodes properly, this arrangement of the the complete binary tree will
follow the property of min heap. So total levels are 9. node 9 is at level 9 and depth
of node 9 is 8 from the root.
Question 280
An operator delete(i) for a binary heap data structure is to be designed to delete
the item in the i-th node. Assume that the heap is implemented in an array and i
refers to the i-th index of the array. If the heap tree has depth d (number of edges
on the path from the root to the farthest leaf), then what is the time complexity to
re-fix the heap efficiently after the removal of the element?
(A) O(1)
(B) O(d) but not O(1)
(C) O(2^d) but not O(d)
(D) O(d2^d) but not O(2^d)
Solution 280
Answer: (B)
Explanation:
For this question, we have to slightly tweak the delete_min() operation of the heap data
structure to implement the delete(i) operation. The idea is to empty the spot in the array at
the index i (the position at
which element is to be deleted) and replace it with the last leaf in the heap (remember heap
is implemented as complete binary tree so you know the location of the last leaf), decrement
the heap size and now starting from the current position i (position that held the item we
deleted), shift it up in case newly replaced item is greater than the parent of old item
(considering max-heap). If it’s not greater than the parent, then percolate it down by
comparing with the child’s value. The newly added item can percolate up/down a maximum
of d times which is the depth of the heap data structure.
Question 281
Consider a max heap, represented by the array: 40, 30, 20, 10, 15, 16, 17, 8, 4.
Now consider that a value 35 is inserted into this heap. After
Explanation: The array 40, 30, 20, 10, 15, 16, 17, 8, 4 represents
following heap
/40 \
30
20
After swapping 35 with 15 and swapping 35
/\ /\
10 15 again with 30, we get
16 17
8/ \ 4 40
After insertion of 35, we / \
get
35
/ 40 \ 20
30 /\
10 /\
30
20 16 17
/\
10 /\
15 /\ /
16 17 8 4 15
/\ /
8 4 35
Question 282
We have a binary heap on n elements and wish to insert n more elements (not
necessarily one after another) into this heap. The total time required
for this is
(A) Θ(logn)
(B) Θ(n)
(C) Θ(nlogn)
(D) Θ(n^2)
Solution 282
The worst case time complexity for insertion in a binary heap is O(Logn). So
inserting n elements in a heap of size n should take Θ(nlogn) time. But choice (B)
seems to be more appropriate answer. One of the solution of O(n) complexity can
be to take the ‘n’ elements of the heap and other ‘n’ elements together and
construct heap in O(2n) = O(n). Thanks to pankaj for suggesting this solution.
Question 283
Consider the process of inserting an element into a Max Heap, where the Max
Heap is represented by an array. Suppose we perform a binary
search on the path from the new leaf to the root to find the position for the newly
inserted element, the number of comparisons performed is:
(A) theta(logn)
(B) theta(LogLogn )
(C) theta(n)
(D) theta(nLogn)
Solution 283
Answer (B)
The height of a Max Heap is Θ(logn). If we perform binary search for
A. Θ(1)
B. Θ(logn)
C. Θ(n)
D. Θ(nlogn)
Solution 284
A 3-ary max heap is like a binary max heap, but instead of 2 children, nodes have 3
children. A 3- ary heap can be represented by an array as follows: The root is
stored in the first location, a[0], nodes in the next level, from left to right, is stored
from a[1] to a[3]. The nodes from the second level of the tree from left to right are
stored from a[4] location onward. An item x can be inserted into a 3- ary heap
containing n items by placing x in the location a[n] and pushing it up the tree to
satisfy the heap property.
Which one of the following is a valid sequence of elements in an array
representing 3-ary max heap?
(A) 1, 3, 5, 6, 8, 9
(B) 9, 6, 3, 1, 8, 5
(C) 9, 3, 6, 8, 5, 1
(D) 9, 5, 6, 8, 3, 1
Solution 285
Answer: (D)
Explanation: Following 3-ary Max Heap can be constructed from sequence given
option (D) 9
/ | \
/ | \
5 6 8
/ |
/ |
3 1
Question 286
In order to avoid this we increment this element by the max value in the array so when we
come to this index we can simply ignore it.
When we have traversed the array from 2 to n-1, we need to re-produce the original array by
subtracting the max value from element which is greater than max value..
Note : Indexes are considered 1 based in array for simplicity.
Solution C
Question 287
Suppose there are ⌈ log n ⌉ sorted lists of ⌊ n/log n ⌋ elements each. The time
complexity of producing a sorted list of all these elements is :
(D) Ω(n3/2)
Solution 287
Answer: (A)
Explanation: We can merge x arrays of each size y in in O(xy*Logy) time
using Min Heap.
x = Logn
y = n/Logn
We get O(n/Logn * Logn * Log Log n) which is O(nLogLogn)
Question 288
If T1 = O(1), give the correct matching for the
following pairs:
(M) Tn=Tn−1+n (U) Tn=O(n)
(N) Tn=Tn/2 +n (V) Tn=O(nlogn)
(O) Tn=Tn/2 (W) T=O(n^2)
+nlogn
(X)
(P) Tn=Tn−1 Tn=O(log^2n)
(A) M-W N-V
+logn O-U P-
X
(B) M-W N-U O-X P-
V
(C) M-V N-W O-X P-
Solution 288
Answer: D
Explanation:
(M) T(n) = T(n-1) + n = 1 + 2 + + n = choice is
3 +T(n)
(N) O(n^2)
… = T(n/2) + n = O(n), using master—theorem
(W) case -3, - choice is
(U)
(O) T(n) = T(n/2) + nlogn = O(nlogn), using master theorem case -3, -
choice is (v)
(C) n/2
(D) (n+1)/2
Solution 289
Answer: (D)
Explanation:
If element is at 1 position then it requires 1 comparison. If element is at 2 position
then it requires 2
comparison. If element is at 3 position then it requires 3 comparison. Similarly , If
element is at n position then it requires n comparison.
Total comparison
= n(n+1)/2
Consider a sequence of 14 elements: A = [-5, -10, 6, 3, -1, -2, 13, 4, -9, -1, 4, 12,
-3, 0]. The subsequence sum.
Determine the maximum of S(i,j), where 0 ≤ i ≤ j < 14. (Divide and conquer
approach may be used)
.
Solution 290
to 11,
= S(2, 11)
= 29
(A) Θ(n)
(B) Θ(nLogn)
(C) Θ(n*n)
(D) Θ(log n)
= k + 2(k-1) + 4(K-2) + 8(k-3) + .......+
2^k -------
-(1)
Answer: (A)
2T(2^k) = 2k + 4(k-1) + 8(K-2) + ......
+ 2*2^k +
Explanation:
T(n) = 2T(n/2) + log n 2^(k+1) --------(2)
=x ( x^4 + 4x^2 + 6 )
+5
=x ( x ( x^3 + 4x ) + 6 ) + 5
=x ( x ( x ( x^2 + 4 ) ) + 6 ) + 5
=x ( x ( x (x (x) + 4 ) ) + 6 ) + 5
(A) O(n^2)
(B) O(n*log(n))
(C) Theta(n*log(n))
(D) O(n^3)
Solution 293
Answer: (A)
Explanation:
For any input, there are some permutations for which worst case will be O(n^2).In
some cases, choosing the middle element minimizes the chances of encountering
O(n^2), but in worst case it can go to O(n^2). Whichever element we take as
Pivot, either first or middle, worst case will be O(n^2) since Pivot is fixed in
position. While choosing a random pivot minimizes the chances of encountering
worst case i.e. O(n^2).
Question 294
Let P be a QuickSort Program to sort numbers in ascending order using the first
element as pivot. Let t1 and t2 be the number of comparisons
made by P for the inputs {1, 2, 3, 4, 5} and {4, 1, 5, 3, 2} respectively. Which
one of the following holds?
A t1 = 5
B. t1 < t2
C. t1 > t2
D. t1 = t2
Solution 294
Answer: (C)
In every step of quick sort, numbers are divided as per the following
recurrence.
T(n) = T(n-1) + O(n)
Question 295
Solution 295
Question 296
(A) O(n)
(B) O(n*log(n))
(C) O(n^2)
(D) O(n!)
Solution 296
Answer: (C)
Explanation:
If all elements of the given array are same then that is the worst case
Let s be a sorted array of n integers. Let t(n) denote the time taken for the most
efficient algorithm to determined if there are two elements with sum
less than 1000 in s. which of the following statements is true? (GATE CS 2000)
a) t (n) is 0 (1)
d) t (n) = nC2
Solution 297
Answer: (A)
Explanation:
Let array be sorted in ascending order, if sum of first two elements is less
than 1000 then there are two elements with sum less than 1000
otherwise not. For array sorted in descending order, we need to check
the last two elements. For an array data structure, the number of
operations is fixed in both cases and not dependent on n, Therefore the
complexity is O(1)
Question 298
Answer: (B)
Explanation:
The correct option is B it maintains the relative order of occurrence of
non-
distinct elements
A sorting algorithm is called stable if it keeps elements with equal keys in
the same relative order in the output as they were in the input.
Question 299
Answer (A)
Worst case complexities for the above sorting algorithms are as follows:
Merge Sort —
nLogn Bubble Sort
— n^2
Quick Sort — n^2
Selection Sort —
n^2
Question 300
For merging two sorted lists of sizes m and n into a sorted list of size
m+n,
we require comparisons of
A O(m)
B. O(n)
C. O(m+n)
D. O(log m + log n)
Solution 300
Solution
A I, II and III
B. I, III and IV
C. I, II and IV
Solution 301
Answer: (B)
Explanation: Statement (I) is correct. In a max heap, the smallest element is always present at a
leaf node. So we need to check for all leaf nodes for the minimum value. Worst case complexity
will be O(n)
12
/ \
8 7
/ \
/ /
/\ \\ / \
2 3 4 5
Statement (II) is also correct, otherwise it will not satisfy max-heap property.
Statement (III) is also correct, as build-heap always takes Θ(n) time, (Refer: Convert BST to
Max Heap).
Statement (IV) is false, because construction of binary search tree from max-heap will
take O(nlogn) time.
Question 302
D=2
for i = 1 to n do
for j = i to n do
for k = j + 1 to n do D =
D*3
S1 – 2S = n + (n-1) + …1 = n*(n+1)/2
2S = n*(n+1)*(2n+1)/6 –n*(n+1)/2
S = n*(n+1)*(n-1)/6
Question 304
Consider the following operation along with Enqueue and Dequeue operations on queue where k is a
global parameter.
m=k;
Dequeue
(Q); m = m
-1;
}
What is the worst case time complexity of a sequence of n queue operations on an initially empty
queue?
A. Θ(n)
Solution 304
Θ(n)Since there are 3 queue operation i.e., enqueue, dequeue and Multi -
dequeue.
'n' enqueue operation will take Θ(n) time, 'n' dequeue operation will Θ(n)
time, 'n' Multi- dequeue operation will take Θ(n) time i.e., Min (n, k) but
A list of n strings, each of length n, is sorted into lexicographic order using the
merge-sort algorithm. The worst case running time of this computation
is
(D) O(n^2)
Solution 305
Answer: (B)
Explanation:
When we are sorting an array of n integers, Recurrence relation for Total number of comparisons
T(n) = 2T(n/2) + (n) where (n) is the number of comparisons in order to merge 2 sorted subarrays of
size n/2.
= (nlog2n)
Instead of integers whose comparison take O(1) time, we are given n strings. We can compare 2
strings in O(n) worst case. Therefore, Total number of comparisons now will be (n2log2n) where each
Which algorithm out of the following options uses the least number of comparisons
(among the array elements) to sort above array in ascending order?
A Insertion sort
B. Selection sort
D. Merge sort
Solution 306
Answer: (C)
recurrence relation:
T(n) = cn + T(n/3)
= cn + cn/3 + T(n/9)
Taking the sum of infinite GP series. The value of T(n) will be less
<= 3cn/2
or we can say
cn <= T(n) <= 3cn/2
This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the
Question 308
In quick sort, for sorting n elements, the (n/4)th smallest element is selected as
a pivot using an O(n) time algorithm. What is the worst-case
(A) θ(n)
(B) θ(n*log(n))
(C) θ(n^2)
Answer: (B)
Explanation:
Answer: (B)
Explanation:
For the case where n/5 elements are in one subset, T(n/5) comparisons are needed
for the first
subset with n/5 elements, T(4n/5) is for the rest 4n/5 elements, and n is for
finding the pivot. If there are more than n/5 elements in one set then other set
will have less than 4n/5 elements and time complexity will be less than T(n/5) +
T(4n/5) + n because recursion tree will be more balanced.
Question 310
An array of n numbers is given, where n is an even number. The maximum as
well as the minimum of these n numbers needs to be
needed?
If n is even then initialize min and max as minimum and maximum of the first two elements
respectively.
For the rest of the elements, pick them in pairs and compare their
The total number of comparisons: Different for even and odd n, see below: If n is
odd: 3*(n-1)/2
Suppose we have a O(n) time algorithm that finds median of an unsorted array.
Now consider a QuickSort implementation where we first find median using the
above algorithm, then use median as pivot. What will be the worst case time
(B) O(n^2)
(D) O(nLogn)
Solution 312
Answer:
(D)
Explanation:
When we choose median as pivot element then after the partition algorithm it
will go in the middle of the array having half of the elements to left the left
Thus after partition algorithm the array will be divided into two equal parts of
Answer:
(C)
Explanation: n(logba) = n which is = n^(1-.5) = O(sqrt n)
Quicksort is run on two inputs shown below to sort in ascending order taking the
first element as pivot,
(i) 1, 2, 3,......., n
Let C1 and C2 be the number of comparisons made for the inputs (i) and (ii)
respectively. Then,
(A) C1 < C2
(B) C1 > C2
(C) C1 = C2
Explanation:
Quick Sort performs in the worst case when input is sorted in either
ascending order or descending order. So, quick sort will return equal
search is:
Answer: (B)
Suppose there are ⌈ log n ⌉ sorted lists of ⌊ n/log n ⌋ elements each. The time
complexity of producing a sorted list of all these elements is :
(D) Ω(n3/2)
Solution 317
Answer: (A)
Explanation: We can merge x arrays of each size y in in
O(xy*Logy) time using Min Heap.
x = Logn
y = n/Logn
We get O(n/Logn * Logn * Log Log n) which is O(nLogLogn)
Question 318
T(1) = 1
Solution 318
and so on you can substitute the value of T(n-1) and T(n-2) in T(n) to get a general idea of
the pattern.
T(n) = T(n-2) + n-1 + n T(n) = T(n-3) + n-2 + n-1 + n . . . T(n) = T(n-k) + kn - k(k-1)/2 ...(1)
=> k = n - 1
substitute in (1)
Assume that the last element of the set is used as partition element in Quicksort.
If n distinct elements from the set [ 1… n] are to be sorted, give an input for
which Quicksort takes maximum time.
Solution 319
elements).So, we can say the above points (1) and (2) as answers.
Question 320
A networking company uses a compression technique to encode the message before
transmitting over the network. Suppose the message contains the following characters with
their frequency:
character
Frequency
5 a
b 9
1
c 2
1
3
d 4
1 5
Note : Each character in input message takes 1 byte. If the compression technique used is
6
Huffman
e Coding, how many bits will be saved in the message?
A. f 224
B. 800
C. 576
D. 324
Solution 320
Which of the following is true about Kruskal and Prim MST algorithms? Assume
that Prim is implemented for adjacency list representation using
D. None of these
Solution
322
Solution
A
Question 323
(A) O(n^2)
(B) O(n*log(n))
(C) Theta(n*log(n))
(D) O(n^3)
Solution 323
Answer: (A)
Explanation:
For any input, there are some permutations for which worst case will be O(n^2). In
some cases, choosing the middle element minimizes the chances of encountering
O(n^2), but in worst case it can go to O(n^2). Whichever element we take as
Pivot, either first or middle, worst case will be O(n^2) since Pivot is fixed in
position. While choosing a random pivot minimizes the chances of encountering
worst case i.e. O(n^2).
Question 324
Let P be a QuickSort Program to sort numbers in ascending order using the first
element as pivot. Let t1 and t2 be the number of comparisons
made by P for the inputs {1, 2, 3, 4, 5} and {4, 1, 5, 3, 2} respectively. Which
one of the following holds?
A t1 = 5
B. t1 < t2
C. t1 > t2
D. t1 = t2
Solution 324
Answer: (C)
In every step of quick sort, numbers are divided as per the following
recurrence.
Solution C
Question 326
Suppose the letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16, 1/32, 1/32
respectively. Which of the following is the Huffman code for the
letter a, b, c, d, e, f?
1
/ \
/ \
1/2 a(1/2)
/ \
/ \
1/4 b(1/4)
/ \
/ \
1/8 c(1/8)
/ \
/ \
1/16 d(1/16)
/ \ e f
Question 327
Suppose the letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16,
A. 3
B. 2.1875
C. 2.25
D. 1.9375
Solution 327
We get the following Huffman Tree after applying Huffman Coding Algorithm. The idea is to keep the least
probable characters as low as possible by picking them first.
The letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively.
1/2 a(1/2)
/ \
/ \
1/4 b(1/4)
/ \
/ \
1/8 c(1/8)
/ \
/ \
1/16 d(1/16)
/ \
e f
The average length = (1*1/2 + 2*1/4 + 3*1/8 + 4*1/16 + 5*1/32 + 5*1/32)
= 1.9375 (Solution D)
Question 328
A. (E, G), (C, F), (F, G), (A, D), (A, B), (A, C)
B. (A, D), (A, B), (A, C), (C, F), (G, E), (F, G)
C. (A, B), (A, D), (D, F), (F, G), (G, E), (F, C)
D. (A, D), (A, B), (D, F), (F, C), (F, G), (G, E)
Solution
328
A.False
The idea behind Prim’s algorithm is to construct a spanning tree – means all vertices must be
connected but here vertices are disconnected
B.False
The idea behind Prim’s algorithm is to construct a spanning tree – means all vertices must be
connected but here vertices are disconnected
C.False.
Prim’s is a greedy algorithm and At every step, it considers all the edges that connect the two
sets, and picks the minimum weight edge from
these edges. In this option, since weight of AD<AB, so AD must be picked up first (which is not
true as per the options).
D.TRUE.
Therefore, Answer is D
Prim’s algorithm is also a Greedy algorithm. It starts with an empty spanning tree. The idea is to
maintain two sets of vertices. The
first set contains the vertices already included in the MST, the other set contains the vertices not
yet included. At every step, it considers all the edges that connect the two sets, and picks the
minimum weight edge from these edges. After picking the edge, it moves the other endpoint of
the edge to the set containing MST.
Question 329
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 11
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 Vopt. 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 Vgreedy. The value of Vopt − Vgreedy is .
Solution
329
First we will pick item_4 (Value weight ratio is highest). Second highest is item_1,
but cannot be picked because of its weight. Now item_3 shall be picked. item_2
cannot be included because of its weight. Therefore, overall profit by Vgreedy =
20+24 = 44 Hence, Vopt - Vgreedy = 60-44 = 16 So, answer is 16.
Question 330
indistinguishable, is
Solution 331
There are 3 choices for the first slot, and then 2 for the third slot. That leaves
one letter out of I,A,C unchosen and there are 2 slots that one
might occupy. After that, the L′s must go in the 2 unfilled slots. Hence the answer
is,
3×2×1×2 = 12
Question 331
A. R7=18
B. R7=19
C. R7 is achieved by three different solutions
D. R7 cannot be achieved by a solution consisting of three pieces
Solution 332
According to given data,
Number of pieces
Possible max profits with combination of rod size
7
7 (1, 1, 1, 1, 1, 1, 1)
6
10 (2, 1, 1, 1, 1, 1)
5
13 (2, 2, 1, 1, 1)
4
16 (2, 2, 2, 1)
3
18 (2, 2, 3)
2
18 (6, 1)
1
18 (7)
Therefore, Option (A) and (C) are correct.
Question 333
Consider the string abbccddeee. Each letter in the string must be assigned a binary code
satisfying the following properties:
For any two letters, the code assigned to one letter must not be a prefix of the code
assigned to the other letter.
For any two letters of the same frequency, the letter which occurs earlier in the dictionary
order is assigned a code whose length is at most the length of the code assigned to the
other letter.
Among the set of all binary code assignments which satisfy the above two properties, what is
the minimum length of the encoded string?
A. 21
B. 23
C. 25
D. 30
Solution 333
Alphabet Frequency
a 1
b 2
c 2
d 2
e 3
Required answer,
= 23
Correct Option B
Question 334
B. Prim's algorithm
C. Kruskal algorithm
Solution D
Question 335
Consider a weighted complete graph G on the vertex set {v1, v2, ..vn} such that
the weight of the edge (vi, vj) is 2|i-j|. The weight of a minimum
(A) n — 1
(B) 2n — 2
(C) nC2
(D) 2
Solution 335
Answer (B)
Minimum spanning tree of such a graph is
v1
\
v2
\
v3
\
v4
.
.
.
vn
B. Stack
C. Heap
D. B-Tree
Solution 336
Answer(A)
(B) Θ(∣E∣.∣V∣)
(D) Θ(∣V∣)
Solution 337
Answer: (D)
Explanation:
As T is a minimum spanning tree and we need to add a new edge to existing
spanning tree.
Consider the weighted undirected graph with 4 vertices, where the weight of edge {i, j} g is
given by the entry
The largest possible integer value of x, for which at least one shortest path between some
pair of vertices will contain the edge with weight x is
Solution 338
of weight 12 (2-1-0-3).
Question 339
The graph shown below has 8 edges with distinct integer edge weights. The minimum
spanning tree (MST) is of weight 36 and contains the edges: {(A, C), (B, C), (B, E), (E,
F), (D, F)}. 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 8 edges of this graph is .
Solution 339
Explanation: In every cycle, the weight of an edge that is not part of MST must by
greater than or equal to weights of other edges which are part of
MST.
Since all edge weights are distinct, the weight must be greater.
So the minimum possible weight of ED is 7, minimum possible weight of
1 2 5 14
3 4 6 23
10 12 18 25
31 ∞ ∞ ∞
When an element is removed from a Young tableau, other elements should be moved into
its place so that the resulting table is still a Young tableau (unfilled entries may be filled
in with a ∞). The minimum number of entries (other than 1) to be shifted, to remove 1
from the given Young tableau is
Explanation:
When 4 is moved in place of 2, it is replaced by smallest adjacent
Initially
1 2 5 which is46
2
14 5
14
3 4 6 10 12 18 25
10 12 18 25 3 6
23 31 ∞ 6∞ ∞
31 ∞ ∞ ∞ When 6 23
is moved in place of 4, it is replaced by smallest
adjacent which is
When 1 is removed, it is replaced by the smallest adjacent
18.
which is 2. 2 4 5 14
2 2 5 14 3 6 18 23
3 4 6 23 10 12 18 2
5
10 12 18 25 31 ∞ ∞ ∞
When 18 is moved in place of 6, it is replaced by smallest
31 ∞ ∞ ∞ adjacent which is 25.
When 2 is moved in place of 1, it is replaced by smallest adjacent 4 5
2 14
which
2 4is 4 5 3 6
14 10 12 25 25
18
31 ∞ ∞ 23 ∞
3 4 6 When 25 is moved in place of 18, it is replaced by smallest
10 12 18 25
23 adjacent which is
31 ∞ ∞ ∞ ∞.
2 4
5 14
3 6 Solution
18 23 5
Shifted numbers are 2, 4, 6, 10 12
25 ∞
18, 25
31 ∞
∞ ∞
Question 341
Suppose P, Q, R, S, T are sorted sequences having lengths 20, 24, 30, 35, 50
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 .
Solution 341
We first merge 20 and 24 and get a list of 44 using 43 worst case comparisons.
Then we merge 30 and 35 into a list of 65 using 64 worst
case comparisons. Then we merge 50 and 44 into a list of 94 using 93
comparisons. Finally we merge 94 and 65 using 158 comparisons. So total number
of comparisons is 43 + 64 + 93 + 158 which is 358.
Question 342
below is
Solution 342
Explanation: Below diagram shows a minimum spanning tree. Highlighted (in
green)
are the edges picked to make the MST.
In the right side of MST, we could either pick edge ‘a’ or ‘b’. In the left side, we
could
either pick ‘c’ or ‘d’ or ‘e’ in MST.
There are 2 options for one edge to be picked and 3 options for another edge to
be
picked. Therefore, total 2*3 possible MSTs.
Question 343
Consider the directed graph shown in the figure below. There are multiple
shortest paths between vertices S and T. Which one will be reported by
Dijstra?s shortest path algorithm? Assume that, in any iteration, the shortest
path to a vertex v is updated only when a strictly shorter path to v is
discovered.
(A) SDT
(B) SBDT
(C) SACDT
(D) SACET
Solution 343
Question 344
An undirected graph G(V, E) contains n ( n > 2 ) nodes named v1 , v2 ,….vn.
Two nodes vi , vj are connected if and only if 0 < |i – j| <= 2. Each edge (vi, vj )
is assigned a weight i
+ j. A sample graph with n = 4 is shown below.
What will be the cost of the minimum spanning tree (MST) of such a graph with
n nodes?
(A) 1/12(11n^2 – 5n)
(B) n^2 – n+1
(C) 6n – 11
(D) 2n + 1
Solution 344
Answer: (B) Total weight= 3 + 4 + 6 = 13
Minimum spanning tree for 2 nodes Minimum spanning tree for 5 nodes
would be would be
(v1) _ (v2) (v1) _ (v2) _ (v4)
Total weight 3 |
Minimum spanning tree for 3 nodes (v3
would be )
(v1) _ (v2) |
Total weight= 3 + 4 + 6 + 8 = 21
Minimum spanning tree for 6 nodes
(v5)
| would be
(v3) (v1) _ (v2) _ (v4) _ (v6)
Total weight= 3 + 4 = 7 |
(v3)
Minimum spanning tree for 4 nodes
|
would be (v1) _ (v2) _ (v4) (v5
| Total
) weight= 3 + 4 + 6 + 8 + 10 = 31
We can observe from above examples that when we add kth node, the weight of spanning
(v3)
tree
increases by 2k-2. Let T(n) be the weight of minimum spanning tree. T(n) can
be written as T(n) = T(n-1) + (2n-2) for n > 2
T(1) = 0 and T(2) = 3
The recurrence can be written as sum of series (2n – 2) + (2n-4) + (2n-6) + (2n-8) +
…. 3 and solution of
Question 345
| (v5)
|
.
.
(more odd numbered nodes)
Wij in the matrix W below is the weight of the edge {i, j}.
What is the minimum possible weight of a spanning tree T in this graph
(A) 7
(B) 8
(C) 9
(D) 10
Solution 346
Answer (D)
To get the minimum spanning tree with vertex 0 as leaf, first remove 0th row and
0th column and then get the minimum spanning tree (MST) of
the remaining graph. Once we have MST of the remaining graph, connect the MST
to vertex 0 with the edge with minimum weight (we have two options as there are
(A) 7
(B) 8
(C) 9
(D) 1
0
Solution 347
Answer (B)
Path: 1 -> 0 -> 4 -
>2
Weight: 1 + 4 + 3
Question 348
Which one of the following is NOT the sequence of edges added to the
Dijkstra’s single source shortest path algorithm when run from vertex a
in
In Longest common subsequence problem, there are two cases for X[0..i]
and Y[0..j]
Let A1, A2, A3, and A4 be four matrices of dimensions 10 x 5, 5 x 20, 20 x 10, and
10 x 5, respectively. The minimum number of scalar
multiplications required to find the product A1A2A3A4 using the basic matrix
multiplication method is
A. 1500
B. 2000
C. 500
D. 100
Solution 352
lxmxn. Then, The number of scalar multiplications required in the following sequence of
Question 353
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 11 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 Vopt. 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
Solution 353
Question 354
Now, to find directed spanning tree of the above graph as per definition given in
question, r = 5 is given,
(i)To reach node 4, from 5 : (5, 4) = 1 way
(ii)To reach node 3, from {5, 4}: (5, 3), (4, 3) = 2 ways
(iii) To reach node 2, from {5, 4, 3}: (5, 2), (4, 2), (3, 2) = 3 ways
(iv) To reach node 1, from {5, 4, 3, 2}: (5, 1), (4, 1), (3, 1), (2, 1) = 4 ways
From (i), (ii), (iii), (iv),
Total no. of ways to reach node 4, 5, 2, 1
From node 5 = 1 × 2 × 3 × 4 = 24 ways
So, there are 24 directed spanning trees for given graph.
Question 355
based on:
paradigm.
Solution 355
Answer: (C)
Answer: (C)
Explanation: Prim’s Algorithm is a greedy algorithm where greedy choice is to pick minimum
weight edge from cut that divides already picked vertices and vertices yet to be picked.
Merge Sort is clearly divide and conquer which follows all steps of divide and conquer. It
first divides the array in two halves, then conquer the two halves and finally combines the
conquered results.
Hamiltonian circuit is a NP complete problem, that can be solved using Backtracking
Question 357
An algorithm to find the length of the longest monotonically increasing sequence of numbers
in an array A[0 :n-1] is given below.
Let Li denote the length of the longest monotonically increasing sequence starting at index i
in the array.
Answer: (A)
Question 358
(A) N
(B) N^2
(C) NlogN
(D) N(logN)^2
Solution 358
Answer: (C)
Explanation: The number of comparisons that a comparison sort algorithm requires increases in
proportion to Nlog(N), where N is the number of elements to sort. This bound is asymptotically
tight:
Given a list of distinct numbers (we can assume this because this is a worst-case analysis),
there are N factorial permutations exactly one of which is the list in sorted order. The sort
algorithm must gain enough information from the comparisons to identify the correct
permutations. If the algorithm always completes after at most f(N) steps, it cannot distinguish
more than 2^f(N) cases because the keys are distinct and each comparison has only two
possible outcomes. Therefore,
(B) Backtracking
(C) Greedy
Answer: (A)
Explanation: According to Kruskal’s Minimum Spanning Tree using Now, there are 3 edges between these
components to connect them.
According to Kruskal’s algorithm, we will include minimum weights edges first if there is no
cycle resultant.
But, we need only one edge to form spanning tree, and we have 3 options for one edge.
Explanation:
M2 will be the adjacency matrix of the graph H derived from G as follow: H(a,b)
So basically there is an edge between a,b if there is some vertex c st. there
original graph.
Question 362
Assume that multiplying a matrix G1 of dimension p×q with another matrix G2 of dimension q×r
requires pqr scalar multiplications. Computing the product of n matrices G1G2G3 … . . Gn
can be done by parenthesizing in different ways. Define GiGi+1 as an explicitly computed pair
for a given paranthesization if they are directly multiplied. For example, in the matrix
multiplication chain G1G2G3G4G5G6 using parenthesization (G1(G2G3))(G4(G5G6)), G2G3 and
G5G6 are only explicitly computed pairs.
Consider a matrix multiplication chain F1F2F3F4F5, where matrices F1,F2,F3,F4 and F5 are of
dimensions 2×25,25×3,3×16,16×1 and 1×1000, respectively. In the parenthesization of
F1F2F3F4F5 that minimizes the total number of scalar multiplications, the explicitly computed
pairs is/are
Four matrices M1, M2, M3 and M4 of dimensions pxq, qxr, rxs and sxt
respectively can be multiplied is several ways with different number of total
scalar multiplications. For example,
when multiplied as ((M1 X M2) X (M3 X M4)), the total number of multiplications
is pqr + rst + prt. When multiplied as (((M1 X M2) X M3) X M4), the total number
of scalar multiplications is
pqr + prs + pst.
If p = 10, q = 100, r = 20, s = 5 and t = 80, then the number of scalar
multiplications needed is (A) 248000
(B) 44000
Solution 363
Answer: (C)
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 X[m] and Y[n] of lengths m and n respectively, with
indexes of X and Y starting from 0.
We wish to find the length of the longest common sub-sequence(LCS) of X[m] and Y[n] as l(m,n),
where an incomplete recursive definition for the function l(i,j) to compute the length of The LCS
of X[m] and Y[n] 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) expr1 ≡ l(i-1, j) + 1
(B) expr1 ≡ l(i, j-1)
(C) expr2 ≡ max(l(i-1, j), l(i, j-1))
(D) expr2 ≡ max(l(i-1,j-1),l(i,j))
Solution 364
Answer: (C)
Explanation: In Longest common subsequence problem, there are two cases
for X[0..i] and Y[0..j]
1) The last characters of two strings match.
The length of lcs is length of lcs of X[0..i-1] and Y[0..j-1]
2) The last characters don't match.
The length of lcs is max of following two lcs values
a) LCS of X[0..i-1] and Y[0..j]
b) LCS of X[0..i] and Y[0..j-1]
Question 365
Answer (B)
X[I, j] (2 <= i <= n and ai <= j <= W), is true if any of the following is
we get (j – ai) + ai as j
Question 366
(A) X[1, W]
(C) X[n, W]
Answer (C)
If we get the entry X[n, W] as true then there is a subset of
{a1, a2, .. an}
that has sum as W.
Question 367
Consider the following C program that attempts to locate an element x in an array Y[] using
binary search. The program is erroneous.
1. f(int Y[10], int x) {
2. int i, j, k;
3. i = 0; j = 9;
4. do {
5. k= (i + j) /2;
6. if( Y[k] < x) i = k; else j = k;
7. } while(Y[k] != x && i < j);
8. if(Y[k] == x) printf ("x is in the array ") ;
9. else printf (" x is not in the array ") ;
10. }
Answer (C)
The above program doesn’t work for the cases where element to be searched is
the last element of Y[] or greater than the last element
(or maximum element) in Y[]. For such cases, program goes in an infinite
loop because i is assigned value as k in all iterations, and i never becomes
equal to or greater than j. So while condition never becomes
false.
Question 368
Consider the following C program that attempts to locate an element x in an array Y[] using binary
search. The program is erroneous.
1. f(int Y[10], int x) {
2. int i, j, k;
3. i = 0; j = 9;
4. do {
5. k= (i + j) /2;
6. if( Y[k] < x) i = k; else j = k;
7. } while(Y[k] != x && i < j);
8. if(Y[k] == x) printf ("x is in the array ") ;
9. else printf (" x is not in the array ") ;
10. }
The correction needed in the program to make it work properly is
(A) Change line 6 to: if (Y[k] < x) i = k + 1; else j = k-1;
(B) Change line 6 to: if (Y[k] < x) i = k - 1; else j = k+1;
(C) Change line 6 to: if (Y[k] <= x) i = k; else j = k;
(D) Change line 7 to: } while ((Y[k] == x) && (i < j));
Solution 368
Answer (A)
Below is the corrected function f(int
Y[10], int x) {
int i, j, k;
i = 0; j = 9;
do {
k = (i + j) /2;
if( Y[k] < x) i = k + 1; else j = k -
1;
} while(Y[k] != x && i < j);
integers:
The number of nodes in the left subtree and right subtree of the root
respectively is
(A) (4, 7)
(B) (7, 4)
(C) (8, 3)
(D) (3, 8)
Solution 369
Solution B
Question 370
Answer: b
Explanation: An insertion algorithm consists of N-1 passes when an array of N
elements is given.
Question 371
Answer: a
Explanation: Insertion sort is similar to that of a binary heap algorithm because of
the use of temporary variable to swap .
Question 372
Answer: d
Explanation: The average case analysis of a tight bound algorithm is mathematically achieved
to be O(N2).
Question 373
Answer: a
Explanation: The total number of pairs in a list L is N(N-1)/2. Thus, an average list has half
this amount, or N(N-1)/4 inversions.
Question 374
What is the running time of an insertion sort algorithm if the input is pre-sorted?
a) O(N2)
b) O(N log N)
c) O(N)
d) O(M log N)
Solution 374
Answer: c
Explanation: If the input is pre-sorted, the running time is O(N), because the test in the inner
for loop always fails immediately and the algorithm will run quickly.
Question 375
Answer: b
Explanation: The number of passes is given by N-1. Here, N=6.
Therefore, 6-1=5 passes.
Question 376
For the following question, how will the array elements look like after second pass?
34, 8, 64, 51, 32, 21
a) 8, 21, 32, 34, 51, 64
b) 8, 32, 34, 51, 64, 21
c) 8, 34, 51, 64, 32, 21
d) 8, 34, 64, 51, 32, 21
Solution 376
Answer: d
Explanation: After swapping elements in the second pass, the array will look like, 8, 34, 64,
51, 32, 21.
Question 377
Answer: a
Explanation: Arranging a pack of cards mimics an insertion sort. Database scenario is an
example for merge sort, arranging books is a stack and real-time systems uses quick sort.
Question 378
Which of the following options contain the correct feature of an insertion sort algorithm?
a) anti-adaptive
b) dependable
c) stable, not in-place
d) stable, adaptive
Solution 378
Answer: d
Explanation: An insertion sort is stable, adaptive, in-place and incremental in nature
Question 379
Which of the following sorting algorithms is the fastest for sorting small arrays?
a) Quick sort
b) Insertion sort
c) Shell sort
d) Heap sort
Solution
379
Answer: b
Explanation: For sorting small arrays, insertion sort runs even faster than quick sort. But, it is
impractical to sort large arrays
Question 380
For the best case input, the running time of an insertion sort algorithm is?
a) Linear
b) Binary
c) Quadratic
d) Depends on the input
Solution 380
Answer: b
Explanation: The worst case input for an insertion sort algorithm will be an array
sorted in reverse order and its running time is quadratic
Question 381
The given array is arr = {1, 2, 4, 3}. Bubble sort is used to sort the array elements. How
many iterations will be done to sort the array?
a) 4
b) 2
c) 1
d) 0
Solution 381
Answer: a
Explanation: Even though the first two elements are already sorted, bubble sort
needs 4 iterations to sort the given array.
Question 382
The given array is arr = {1,2,4,3}. Bubble sort is used to sort the array elements. How many
iterations will be done to sort the array with improvised version?
a) 4
b) 2
c) 1
d) 0
Solution 382
Answer: b
Explanation: Only 2 elements in the given array are not sorted, hence only 2 iterations are
required to sort them.
Question 383
What is the best case efficiency of bubble sort in the improvised version?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
Solution 383
Answer: c
Explanation: Some iterations can be skipped if the list is sorted, hence efficiency improves to
O(n).
Question 384
Which of the following is the most commonly used data structure for implementing Dijkstra’s
Algorithm?
a) Max priority queue
b) Stack
c) Circular queue
d) Min priority queue
Solution 384
Answer: d
Explanation: Minimum priority queue is the most commonly used data structure for
implementing
Dijkstra’s Algorithm because the required operations to be performed in Dijkstra’s Algorithm
match with specialty of a minimum priority queue.
Question 385
The maximum number of times the decrease key operation performed in Dijkstra’s algorithm will
be equal to
a) Total number of vertices
b) Total number of edges
c) Number of vertices – 1
d) Number of edges – 1
Solution 386
Answer: b
Explanation: If the total number of edges in all adjacency list is E, then there
will be a total of E number of iterations, hence there will be a total of at
most E decrease key operations.
Question 387
What is running time of Dijkstra’s algorithm using Binary min- heap method?
a) O(V)
b) O(VlogV)
c) O(E)
d) O(ElogV)
Solution 387
Answer: d
Explanation: Time required to build a binary min heap is O(V). Each decrease key operation
takes O(logV) and there are still at most E such operations. Hence total running time is
O(ElogV).
Question 388
Given pseudo code of Dijkstra’s Algorithm.
//Initialise single source(G,s)
S=0
Q=V[G]
While Q != 0
Do u=extract-min(Q)
S=S union {u}
For each vertex v in adj[u]
Do relax(u,v,w)
Answer: b
Explanation: In the normal execution of Dijkstra’s Algorithm, the while loop gets executed V
times. The change in the while loop statement causes it to execute only V – 1 times.
Question 389
. Consider the following graph.
a) 8
b) 9
c)4
d)6
Solution 389
Answer: d
Explanation: The minimum cost to reach f vertex from b vertex is 6 by having vertices g and e
as intermediates. b to g, cost is 1
g to e, cost is 4
e to f, cost is 1
hence total cost 1+4+1=6.
Question 390
. In the given graph, identify the shortest path having minimum cost to reach vertex E if A is the
source vertex
a) a-b-e
b) a-c-e
c) a-c-d-e
d) a-c-d-b-e
Solution 390
Answer: b
Explanation: The minimum cost required to travel from vertex A to E is via vertex C A to C,
cost= 3
C to E, cost= 2
Hence the total cost is 5.
Question 391
Answer: d
Explanation: Bellmann ford algorithm is used for finding solutions for single source
shortest path problems. If the graph has no negative cycles that are reachable from the
source then the algorithm produces the shortest paths and their weights.
Question 393
Answer: d
Explanation: Bellmann Ford algorithm runs in time O(VE), since the initialization takes O(V)
for each of V-1 passes and the for loop in the algorithm takes O(E) time. Hence the total
time taken by the algorithm is O(VE).
Question 394
How many times the for loop in the Bellmann Ford Algorithm gets executed?
a)V times
b)V-1
c)E
d)E-1
Solution 394
Answer: b
Explanation: The for loop in the Bellmann Ford Algorithm gets executed for V-1 times.
After making V-1 passes, the algorithm checks for a negative weight cycle and returns
appropriate boolean value.
Question 395
Consider the following graph. What is the minimum cost to travel from node A to node C?
a) 5
b) 2
c) 1
d) 3
Solution 395
Answer: b
Explanation: The minimum cost to travel from node A to node C is 2. A-D, cost=1
D-B, cost=-2 B-C, cost=3
Hence the total cost is 2
Question 396
In the given graph, identify the path that has minimum cost to travel from node a to node
f
a) a-b-c-f
b) a-d-e-f
c) a-d-b-c-f
d) a-d-b-c-e-f
Solution 396
Answer: d
Explanation: The minimum cost taken by the path a-d-b-c-e-f is 4. a-d, cost=2
d-b, cost=-2 b-c, cost=1
c-e, cost= 2 e-f, cost=1
Hence the total cost is 4.
Question 397
Answer: c
Explanation: When the total weight of the graph sums up to a negative number then the
graph is said to have a negative weight cycle. Bellmann Ford Algorithm provides no solution
for such graphs.
Question 398
Answer: a
Explanation: In Bellmann Ford Algorithm the shortest paths are calculated in bottom up
manner which is similar to other dynamic programming problems.
Question 399
Answer: d
Explanation: A problem that can be solved using dynamic programming possesses
overlapping subproblems as well as optimal substructure properties.
Question 400
Answer: b
Explanation: Optimal substructure is the property in which an optimal solution is found for
the problem by constructing optimal solutions for the subproblems.
Question 401
Choose the recursive formula for the Fibonacci series.(n>=1)
a) F(n) = F(n+1) + F(n+2)
b) F(n) = F(n) + F(n+1)
c) F(n) = F(n-1) + F(n-2)
d) F(n) = F(n-1) – F(n-2).
Solution 401
Answer: d
Explanation: When the speed of access depends on the location previously accessed,
Fibonacci search is better compared to binary search as it performs well on those locations
which have lower dispersion. Fibonacci search won’t work on unsorted arrays. The input
should be a sorted array or array should be sorted before Fibonacci search.
Question 403
Answer: b
Explanation: A recursive approach is easier to understand and contains fewer lines of code.
Question 404
Given an array arr = {45,77,89,90,94,99,100} and key = 99; what are the mid
values(corresponding array elements) in the first and second levels of recursion?
a) 90 and 99
b) 90 and 94
c) 89 and 99
d)89 and 94
Solution 404
Answer: a
Explanation: At first level key =
90 At second level key= 99
Here 90 and 99 are mid values.
Question 405
Answer: b
Explanation: Using the divide and conquer master theorem.
Question 406
Answer: d
Explanation: In Binary search, the elements in the list should be sorted. It is applicable only
for ordered list. Hence Binary search in unordered list is not an application.
Question 407
Answer: b
Explanation: Since ‘mid’ is calculated for every iteration or recursion, we are diving the array
into half and then try to solve the problem.
Question 408
Answer: b
Explanation: T(n) = T(n/2) + theta(1)
Using the divide and conquer master theorem, we get the time complexity as O(log
Question 409
In general, which of the following methods isn’t used to find the factorial of a number?
a) Recursion
b) Iteration
c) Dynamic programming
d) Non iterative / recursive
Solution 409
Answer: d
Explanation: In general we use recursion, iteration and dynamic programming to find the
factorial of a number. We
can also implement without using iterative / recursive method by using tgammal() method.
Most of us never use it generally.
Question 410
Consider the following recursive implementation to find the factorial of a number. Which of the lines
should be inserted to complete the below code?
int fact(int n)
{ if( )
return 1;
return n * fact(n - 1); }
int main()
{ int n = 5;
int ans =
fact(n);
printf("%d",an
s); return 0; }
a) n = 0
b) n != 0
c) n == 0
d) n == 1
Solution 410
Answer: c
Explanation: The line “n == 0” should be inserted to complete the above code.
Note: “n == 1” cannot be used because it does not take care of the case when n = 0, i.e when
we want to find the factorial of 0.
Q411>
Consider the following recursive implementation to find the factorial of a number. Which of the lines is the
base case?
int fact(int n)
{ if(n ==
0) return
1;
return n * fact(n - 1);
}
int main()
{ int n = 5;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) return 1
b) return n * fact(n-1)
c) if(n == 0)
d) if(n == 1)
Solution 411
Answer: c
Explanation: The line “if(n == 0)” is the base case.
Q412>
Master’s theorem is used for?
a) solving recurrences
b) solving iterative relations
c) analysing loops
d) calculating the time
Solution 412
Answer: a
Explanation: Master’s theorem is a direct method for solving recurrences. We can solve any
recurrence that falls under any one of the three cases of master’s theorem. exity of any code
Question 413
What is the result of the recurrences which fall under first case of Master’s theorem (let the
recurrence be given by T(n)=aT(n/b)+f(n) and f(n)=nc?
a) T(n) = O(n^logba)
b) T(n) = O(nc log n)
c) T(n) = O(f(n))
d) T(n) = O(n2)
Solution 413
Answer: a
Explanation: In first case of master’s theorem the necessary condition is that c <
logba. If this condition is true then T(n) = O(n^logba).
Question 414
What is the result of the recurrences which fall under second case of Master’s
theorem (let the recurrence be given by T(n)=aT(n/b)+f(n) and f(n)=nc?
a) T(n) = O(nlogba)
b) T(n) = O(nc log n)
c) T(n) = O(f(n))
d)T(n) =
O(n2)
Solution 414
Answer: b
Explanation: In second case of master’s theorem the necessary condition is that c = logba. If
this condition is true then T(n) = O(nc log
Question 415
Under what case of Master’s theorem will the recurrence relation of binary search fall?
a) 1
b) 2
c) 3
d) It cannot be solved using master’s theorem
Solution 415
Answer: b
Explanation: The recurrence relation of binary search is given by T(n) =
T(n/2) + O(1). So we can observe that c = Log ba so it will fall under case 2
of master’s theorem.
Question 416
Which of the following methods can be used to find the largest and smallest
element in an array?
a)Recursion
b)Iteration
c)Both recursion and iteration
d)No method is suitable
Solution 416
Answer: c
Explanation: Both recursion and iteration can be used to find the largest and
smallest element in an array.
Question 417
Answer: c
Explanation: The rule is to not put a disk over a smaller one. Putting a smaller disk over
larger one is allowed.
Question 418
Answer: c
Explanation: As there are 2 recursive calls to n-1 disks and one constant time
operation so the recurrence relation will be given by T(n) = 2T(n-1)+c.
Question 419
What is the running time of the Huffman algorithm, if its implementation of the priority queue is
done using linked lists?
a) O(C)
b) O(log C)
c) O(C log C)
d) O(C2)
Solution 419
Answer: d
Explanation: If the implementation of the priority queue is done using linked lists, the
running time of Huffman algorithm is O(C2).
Question 420
Answer: c
Explanation: Greedy algorithm is used to solve this problem. We first sort
items according to their value/weight ratio and then add item with
highest ratio until we cannot add the next item as a whole. At the end, we
add the next item as much as we can.
Question 421
Answer: c
Explanation: Out of 128 characters in an ASCII set, roughly, only 100
characters are printable while the rest are non-printable
Question 423
Answer: b
Explanation: In Huffman encoding, data is always stored at the leaves of a
tree inorder to compute the codeword effectively.
Question 424
Answer: d
Explanation: The relation between number of nodes(N) and
leaves(L) is N=2*L-1.
Question 425
Answer: d
Explanation: Dynamic programming, Recursion, Brute force can be
used to solve the longest palindromic subsequence problem.
Question 426
.If a problem can be broken into subproblems which are reused several times, the problem
possesses
property.
a) Overlapping subproblems
b) Optimal substructure
c) Memoization
d) Greedy
Solution 426
Answer: a
Explanation: Overlapping subproblems is the property in which value of
a subproblem is used several times.
Question 427
Answer: b
Explanation: The top-down approach uses the memoization technique
which stores the previously calculated values. Due to this, the time
complexity is decreased but the space complexity is increased
Question 428
Answer: d
Explanation: The fractional knapsack problem is solved using a greedy
algorithm
Question 429
Answer: c
Explanation: The longest common subsequence problem has both, optimal
substructure and overlapping subproblems. Hence, dynamic programming
should be used the solve this problem
Question 430
Answer: c
Explanation: Floyd Warshall Algorithm can be applied in directed graphs.
From a given directed graph, an adjacency matrix is framed and then all
pair shortest path is computed by the Floyd Warshall Algorithm.
Question 431
Which of the following problems can’t be solved using recursion?
a)Factorial of a number
b)Nth fibonacci number
c)Length of a string
d)Problems without base case
Solution 431
Answer: d
Explanation: Problems without base case leads to infinite recursion call. In
general, we will assume a base case to avoid infinite recursion call.
Problems like finding Factorial of a number, Nth Fibonacci number and
Length of a string can be solved using recursion.
Question 431
Answer: d
Explanation: The program prints the numbers from 10 to 1
Question 433
What is the base case for the following
code? void my_recursive_function(int
n)
{ if(n == 0)
return;
printf("%d
",n);
my_recursive_function(n-1);
}
int main()
{
my_recursive_function(
10); return 0;
}
a) return
b) printf(“%d “, n)
c) if(n == 0)
Solution 433
Answer: c
Explanation: For the base case, the recursive function is not called. So,
“if(n == 0)” is the base case.
Question 434
How many times is the recursive function called, when the following code is
executed? void my_recursive_function(int n)
{ if(n == 0)
return;
printf("%d
",n);
my_recursive_function(n-1);
}
int main()
{ my_recursive_function(
10); return 0;
}
a) 9
b) 10
c) 11
d) 12
Solution 434
Answer: c
Explanation: The recursive function is called 11 times
Question 435
Answer: c
Explanation: The above code prints the numbers from 1 to 10.
Question 436
Answer: a
Explanation: Since selection sort is an in-place sorting algorithm, it does
not require additional storage.
Question 437
Answer: a
Explanation: Since the input array is not sorted, bubble sort takes 5
iterations and selection sort takes 4(n-1) iterations.
Question 438
Which of the following is not a variant of merge sort?
a) in-place merge sort
b) bottom up merge sort
c) top down merge sort
d) linear merge sort
Solution 438
Answer: d
Explanation: In-place, top down and bottom up merge sort are different
variants of merge sort. Whereas linear merge sort is not a possible
variant as it is a comparison based sort and the minimum time
complexity of any comparison based sort is O(n log n).
Question 439
Consider the following heap after buildheap phase. What will be its
corresponding array?
a) 26,53,41,97,58,59,31
b) 26,31,41,53,58,59,97
c) 26,41,53,97,31,58,59
d) 97,53,59,26,41,58,31
Solution 439
Answer: d
Explanation: Constructing a max heap using the elements 97,53,59,26,41,58,31 will
cause the heap to look like that.