0% found this document useful (0 votes)
35 views905 pages

Pds-Algo Pyqs

The document contains a series of questions and solutions related to C programming concepts, including structures, unions, pointers, and compiler behavior. Each question presents a code snippet or declaration, followed by multiple-choice answers and explanations for the correct answer. The content is aimed at testing knowledge of C programming and understanding of memory management, syntax, and semantics.

Uploaded by

Tejas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views905 pages

Pds-Algo Pyqs

The document contains a series of questions and solutions related to C programming concepts, including structures, unions, pointers, and compiler behavior. Each question presents a code snippet or declaration, followed by multiple-choice answers and explanations for the correct answer. The content is aimed at testing knowledge of C programming and understanding of memory management, syntax, and semantics.

Uploaded by

Tejas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 905

Question 1

Assume that size of an integer is 32 bit. What is the output of following


program? #include<stdio.h>
struct st
{
int x;
static int y;
};
int main()
{
printf("%d", sizeof(struct st));
return 0;
}
A. 4
B. 8
C. Compiler Error
D. Runtime Error
Solution 1

In C, struct and union types cannot have static members. In


C++, struct types are allowed to have static members, but
union cannot have static
members in C++ also.

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)

A. An array, each element of which is a pointer to a structure of type node


B.A structure of 2 fields, each field being a pointer to an array of 10 elements
C. A structure of 3 fields: an integer, a float, and an array of 10 elements
D. An array, each element of which is a structure of type node.
Solution 2

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

A structure cannot contain a member of its own type because if this is


allowed then it becomes impossible for compiler to know size of such
struct. Although a pointer of same type can be a member because pointers of
all types are of same size and compiler can calculate size of struct

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

characters of arr are set as 0. O is ASCII value of '\0'. When we do "t.arr[1]

= 'G'", arr[]becomes "\0G\0\0". When we print a string using


"%s", the

printf function starts from the first character and keeps printing till it finds a

\0. Since the first character itself is \0, nothing is printed.


Solution A
Question 6

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

The typedef usage is incorrect. Basically, we can’t use yet to be typedef-ed


data type inside while applying typedef itself. Here, NODEPTR is yet to be
defined (i.e. typedef-ed) and we are using NODEPTR inside the struct
itself.
Solution B
Question 7

Pick the best statement for the below program:


#include "stdio.h"

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

In C, designators can be used to provide explicit initialization. For


an array, elements which aren’t initialized explicitlyin program are set
as ZERO. That’s why correct answer is C.
Question 8

Consider the following C


program :
#include <
stdio.h > int
main () {
int arr [] = {1,2,3,4,5,6,7,8,9,0,1,2,5}, *ip =
arr+4;

printf ("%d\n",

ip[1]); return 0; _. (GATE


CSE
}
The number that will be displayed on execution of the
Solution 8
Solution 6

ip is an integer pointer and the initial assignment sets it to the element at array

index 4 i.e. 5.
(holds address of ar index 4)
The next statement refers to the 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.

Option (A) is correct.


Question 10

Consider the following C program.


#include < stdio.h >
void mystery(int *ptra, int *ptrb)
{
int *temp;
temp = ptrb;
ptrb = ptra;
ptra = temp;
}
.
int main() {
int a=2016, b=0, c=4, d=42;
mystery(&a, &b); if (a < c)
mystery(&c, &a);
mystery(&a, &d); printf("%d\n", a);
}
The output of the program is
Solution 10
The mystery about mystery function is it does not affect values in main. As in C,
parameters are passed by value- even if they are pointer. So, here
the pointer values are exchanged within the function only. (we can use ∗ operator
to exchange the values at the location of the pointers and this will affect the values
in main).

So, NO CHANGES in a, b, c, d And


ANSWER is 2016
Question 11
The output of the following C program is .

void f1(int a, int b)

int c;
c=a; a=b; b=c;
}

void f2(int *a, int *b)


{
int c;
c=*a; *a=*b; *b=c;
}
int main(){
int a=4, b=5, c=6; f1(a,b);
f2(&b, &c);
printf(“%d”,c-a-b);
}
Solution 11

void f1 ( int a, int b) { //This code is call by value


// hence no effect of actual values when run. int c;
c = a; a = b;
b = c;
}
void f2 ( int * a, int * b)//*a=
{ address of b
//and *b = address of c

int c; //int c = garbage


c = * a; //c = value at address a = 5;
*a = *b; //*a = Exchange original
// variable value of c to b = b= 6
*b = c; //*b = c = 5;
}

int main () {
int a = 4, b = 5, c = 6;
f1 ( a, b); This has no effect on actual values
// of a ,b since Call by value.
f2 (&b, &c); Here change will be happen.
At this point int a = 4, b = 6, c = 5;
printf ("%d", c - a - b); = (5-4)-6 = 1-6 = -5
Question 12

What does the following fragment of C-program print?

char c[ ] = "GATE2011";

char *p = c;

printf("%s", p + p[3] - p[1]);

A. GATE2011

B. E2011

C. 2011

D. 01
Solution 12

The correct option is D 2011

P + P[3] - P[1] = 2000 + 69 - 65

= 2004


2011 string will be printed.

(From 2004 Address)


Question 13

What does the following C statement declare?

int (*f)(int *);

A. A function that takes an integer pointer as argument and returns an integer

B. A function that takes an integer as argument and returns an integer pointer


C. A pointer to a function that takes an integer pointer as argument and returns

an integer

D.A function that takes an integer pointer as argument and returns a function

pointer
Solution 13
Solution C
Steps to read the statement:-

1)Convert C declaration to postfix format and read from left to right.

2)To convert expression to postfix, start from innermost parenthesis, If innermost


parenthesis is not present then start from declarations name and go right first. When
first ending parenthesis encounters then go left. Once the whole parenthesis is
parsed then come out from parenthesis.
3)Continue until complete declaration has been parsed.

At First, we convert the following given declaration into postfix:


int ( * f) (int * )
Since there is no innermost bracket, so first we take declaration name f, so print “f”
and then go to the right, since there is
nothing to parse, so go to the left. There is * at the left side, so print “*”.Come out
of parenthesis. Hence postfix notation of given declaration can be written as
follows:
f * (int * ) int
Meaning: f is a pointer to function (which takes one argument of int pointer type)
returning int .
Question 14
The most appropriate matching for the following pairs

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

it. Hence, lost memory

Y: n is freed and so pointer is now pointing to an invalid memory making it


a Dangling pointer.

Z: p is not initialized. P = malloc(sizeof(char)); should have been


used before assigning a to *p
Question 15
What is printed by the following ANSI C program?
#include <stdio.h>
int main(int argc,
char *argv[])
{ char a = 'P';
char b = 'x';
char c = (a & b) + '*';
char d = (a | b) $$-$$ '$$-$$';
char e = (a ^ b) +
'+'; printf("%c %c
%c\n", c, d, e);
return 0; .
}
A. z K encoding
ASCII S B. 122 75 83
for relevant C. * − +
characters
D. P x + is given below :
Solution 15
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.

a = ‘P’ ===> a = Ascii value of (‘P’)


= 65+15 = 80 ==> a = b = ‘x’ ===> b =
Ascii value of (‘x’) = 97+23 = 120 ==> b =
a&b = [ apply & logic on corresponding bits ] =

a&b + ‘*’ = (0111 1010)2 = 64+32+16+8+2 [ add corresponding bits ], [ simply


‘*’ = 42 = 80+42 =
= 122
122 ]
print character ( 122 ) = small ‘z’
a | b= [ apply | logic on corresponding bits ] = ‘-’ = 45
a|b - ‘-’ = 120-45 = 75 = 65 + 10
print character ( 75 ) = Capital ‘K’
a^b = [ apply ^ logic on corresponding bits ] = ‘+’ = 43
a^b + ‘+’ = 40+43 = 83 = 65 + 18
print character ( 83 ) = Capital ‘S’
Question 16
Consider the following ANSI C program:
int main() {

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

Calculating fun(2), fun(3) and fun(4)


fun(2) = 1 + fun(1)*fun(1) = 1 + 1*1 =
2
fun(3) = 1 + 2*fun(1)*fun(2) = 1 + 2*1*2 =
5 fun(4) = 1 + 2*fun(1)*fun(3) +
fun(2)*fun(2)
= 1 + 2*1*5 + 2*2 = 15
Download Exampreptool ( EPT App)
https://play.google.com/store/apps/details?id=com.ept.requestteacher

For important Questions & Answers with video solutions

(Prepared by rankers: Soumya Ratul Hymavati Divyanshu)

Note: If any doubt in any question post with subject & question number in EPT App.
Question 18
Consider the following program in C language:

#include < stdio.h > main()


{
int i;
int *pi = &i;
scanf("%d", pi);
printf("%d\n", i + 5);
}
Which one of the following statements is TRUE?
A.Compilation fails.
B. Execution results in a run-time error.
C.On execution, the value printed is 5 more than the address of variable i.
Solution 18
int i; //i is declared

int*pi = &i; //pi is a pointer variable

//and is assigned the address of i

scanf("%d",pi); //i is overwritten with the value

//we provided because pi is pointing to i earlier

printf("%d\n", i+5) //it will print the value stored in i+5


INPUT = 3 ; OUTPUT = 8

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?

1)Static allocation of all data areas by a compiler makes it impossible to


implement recursion.

2)Automatic garbage collection is essential to implement recursion.

3)Dynamic allocation of activation records is essential to implement recursion.

4)Both heap and stack are essential to implement recursion.

A.1 and 2 only


B.2 and 3 only
C.3 and 4 only
D.1 and 3 only
Solution 20
Answer:(D)

Explanation: 1) Static allocation of all data areas by a compiler makes it impossible to


implement recursion. True, dynamic allocate of memory is required for function call
stack as number of calls is not known advance for recursive functions.
2)Automatic garbage collection is essentialto implement recursion. False,
Automatic garbage collection is not essential.
3)Dynamic allocation of activation records is essential to
implement recursion. True, as number of calls or number of activation records is not
known advance for recursive functions.
4)Both heap and stack are essentialto implement recursion. Heap is not
needed for function calls. It is generally used for dynamic memory allocation by user
(or programmer).
Question 21
Let A be a square matrix size n×n. Consider the following pseudocode. What is the expected output?
C = 100;
for i = 0 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 = 0 to n do
for j = 1 to n do
output(A[ i ][ j ]);
A The matrix A itself
B. Transpose of the matrix A
C.Adding 100 to the upper diagonal elements and subtracting 100 from lower diagonal
elements of
D None of these A
Solution 21

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

Suppose n and p are unsigned int variables in a C program. We wish to


set p to nC3. If n is large, which one of the following statements is most

likely to set p correctly?

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

Explanation: As n is large, the product n*(n-1)*(n-2) will go out of the range(overflow)


and it will return a value different from what is expected. Therefore, option (A) and (D)
are eliminated.

So we consider a shorter product n*(n-1).


n*(n-1) is always an even number. So the subexpression ” n * (n-1) / 2 ” in

option B would always produce an integer, which means no precision loss in this

subexpression. And when we consider ” n*(n-1)/2*(n-2) “, it will always give a number

which is a multiple of 3. So dividing it with 3 won’t have any loss .


Question 24

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 24

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.
Question 25

Which languages necessarily need heap allocation in the runtime

environment?

A Those that support recursion

B. Those that use dynamic scoping


C.Those that allow dynamic data structures

D Those that use global variables


Solution 25

Answer:
(C)
Explanation: Heap allocation is needed for dynamic data
structures like
tree, linked list, etc.
Question 26

A common property of logic programming languages and functional

languages is:
A both are procedural languages

B both are based on l-calculus

C. both are declarative

D. both use Horn-clauses


Solution 26

Answer : both are declarative


Major logic programming language families include Prolog, Answer set
programming (ASP) and Datalog. In all of these languages, rules are written
in the form of clauses

Prolog is a Declarative Language .


Functional programming is a declarative programming paradigm, which

means programming is done with expressions or declarations instead of

statements.
Question 27

The goal of structured programming is to

A have well indented programs


B. be able to infer the flow of control from the compiled code
C. be able to infer the flow of control from the program text
D. avoid the use of GOTO statements
Solution 27
Answer is (C).
The goal of structured programming is to able to infer the flow of control from the
program text . It means user can execute the code according to his requirement. C
and Pascal are good example of structured programming. In structured
programming control passes one instruction to another instruction in sequential

manner.
Avoiding the use of GOTO statements is not the goal of structured programming, it
(avoiding the use of GOTO) is one of the requirements for a program to be

structured.
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)

Explanation: P: Functional Programming is declarative in nature, involves expression


evaluation, & side effect free.

Q: Logic is also declarative but involves theorem proving.


R: Object oriented is imperative statement based & have abstract

(general) data types.


S: Imperative: The programs are made giving commands & follows definite
procedure & sequence
Question 29

Which of the following statements is FALSE?


A. In statically typed languages, each variable in a program has a fixed

type

B. In un-typed languages, values do not have any types

C. In dynamically typed languages, variables have no types


D. In all statically typed languages, each variable in a program is
associated with values of only a single type during the execution of the
program
Solution 29

Answer is (C).

In dynamically typed languages variables do have type-


just that it is inferred during runtime
Question 30

The results returned by function under value-result and reference


parameter passing conventions

A Do not differ
B Differ in the presence of loops
C Differ in all cases

D May differ in the presence of exception


Solution 30
Solution D.
May differ in the presence of exceptions.
In call by reference, the called function is working with the memory
location of the passed variables. So, any update to the variables are
immediately effective.

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.

So, during a function execution if an exception happens, in call-by-value- result,


Question 31
What is printed by the following ANSI C program? (GATE
CSE 2022)
#include <stdio.h>
int main(int argc, char *argv[ ]) {
int a[3][3][3] = {{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}};
int i = 0, j = 0, k = 0; for(i = 0; i < 3; i++) {
for(k = 0; k < 3; k++) printf("%d"",a[i][j][k]);
printf("\n");
}
return 0;
}
(A)
123
10 11 12
19 20 21

(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:

a is a 3D array with the value

{{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}};

For i=0, j=0, and k=0,1 and 2 the


output=1 2 3

For i=0, j=0, and k=0,1 and 2 the

output=10 11 12 For i=0, j=0, and k=0,1


Question 32
Consider the following three functions :

[P1] int *g(void) { intx=10; return (& x); }

[P2] int *g(void) { int *px; *px=10; return px; }


[P3] int *g(void) { int *px px=(int*)malloc (size of (int)); *px=10; return px; }
Which of the above three functions are likely to cause problems
with pointers ?

(A) Only P3

(B) Only P1 and P3

(C) Only P1 and P2

(D) P1, P2 and P3


Solution 32

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

n = 10 given but not passed to D. In D, n = 3 & W n( ) increments by 1. So n = 1+ n


= 4.
Question 34

Consider the following declaration of a two-dimensional array in C :


Char a[100][100]

Assuming that the main memory is byte-addressable and that array is stored starting from

memory address 0, the address of a [40] [50] is


(A) 4040
(B) 4050
(C) 5040
(D) 5050
Solution 34
Char a[100] [100]
1 char require 1 byte
Total required 10000 bytes.
Memory format is byte addressable
a[0][0]….. a[0][50]….. a[0][99]

…………………………………….

a[50][0] …a[50][50] …a[50][99]

……………………………………..

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

Let T (n) be the number of different binary search trees on


n distinct
elements. Then n T(k -1)T(x), where
T(n) = Σ x is
k=
1
(A) n - k + 1 (B) n - k (C) n - k − 1 (D) n -
k−2
Solution 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

The goal of structured programming is to


(A) have well indented programs
(B) be able to infer the flow of control from the compiled code
(C) be able to infer the flow of control form the program text
(D) avoid the use of GOTO statements
Solution 37

Structured programming :- It is way of programming using the sub structure


method, i.e splitting the programs into sub sections. Structured programming
prevents confusing transfer of control of avoiding the use of GOTO statements.
Hence (D) is correct option
Question 38
Consider the following C
function void swap (int a, int
b) {
int temp;

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

Here the function takes the arguments by value.


" Option (A) sends parameter by value but only the local variable a & b will

be exchanged but not the actual variables x & y so incorrect.

" Option (B) is incorrect sending address of x & y .

" Option (C) swap (x,y) is usable there is no need to return.


" Option (D) is the opposite statement of option (A), it says that the values

are passed by value so won’t swap so the option is correct.

Hence (D) is correct option.


Question 39
Output of following
program? #include
int main()
<stdio.h>
{
int i = 5;
printf("%d %d %d", i++, i++, i++);
return 0;

}
Run on IDE

A 765

B. 5 6 7

C 777

D Compiler Dependent
Solution 39

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.


Question 40
What is the meaning of using extern before function declaration?For example

following function sum is made extern

extern int sum(int x, int y, int z)

return (x + y + z);

}
A. Function is made globally available

B.extern means nothing, sum() is same without extern keyword.

C.C Function need not to be declared before its use


D. Function is made local to the file.
Solution 40

extern keyword is used for global variables. Functions are global


anyways,
so adding extern doesn't add anything
Option b is correct
answer
Question 41
Consider the following C-program:
void foo(int n, int sum){
int k = 0, j = 0;
if (n == 0) return;
k = n % 10;
j = n / 10;
sum = sum + k; foo (j, sum); printf ("%d,", k);
}

int main (){


int a = 2048, sum = 0;
foo (a, sum);
printf ("%dn", sum);
getchar();}
What does the above program print?
.
A 8, 4, 0, 2, 14
B. 8, 4, 0, 2, 0
C. 2, 0, 4, 8, 14
D. 2, 0, 4, 8, 0
Solution 41

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

after foo(), so one more 0 is printed after all digits of n.

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

>value=5; 2: using uninitialized


Z: char *p; *p =
pointers
’a’;
3. lost memory is:

(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

example of memory leak


Y -> Trying to retrieve value after freeing it so dangling pointer.
Z -> Using uninitialized pointers
Question 43
Consider the following C-program:
double foo (double); /* Line 1 */

int main()

{ double
da, db;
// input
da db =
foo(da);

double
foo(double a){
return a;
The above code compiled without any error or warning. If Line 1 is deleted, the above code
will show:
A.no compile warning or error
B.some compiler-warnings not leading to unintended results
C.some compiler-warnings due to type-mismatch eventually leading to unintended results
D.compiler errors
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.

• Correct ans is option D


Question 44
The value of j at the end of the execution of the following C
program. int incr(int i){
static int count
= 0; count =
count + i; return
(count);
}
main(){
int i,j;
for (i = 0; i <=4;
i++) j = incr(i);
}
A. 10
B. 4
C. 6
Solution 44

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.

The memory requirement for variable t, ignoring alignment

considerations, is (GATECS 2000)


(a) 22 bytes
(b)14 bytes
(c) 18 bytes
(d)10 bytes
Solution 45

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)

int funcf (int { int y;

x); int funcg y=

(int y); funcg(x);

main(){ return (y);


}
int x = 5, y = 10, count;
for (count = 1; count <= 2; + funcg(int x){
+count){ static int y = 10;
y += funcf(x) + funcg(x); y += 1; return
(y+x);
printf ("%d ", y); }

}
}
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);

1st call- funcg(x); // y = 11 y+x= 16. 2nd call funcg(x); // y=


12 y+x= 17. First iteration-> main()->y = 16+17 +10 = 43 Second

iteration-> main() y= 18+19 +43 =80


Question 47
What is the output printed by the following program?
#include<stdio.h>
int f(int n, int k)
{
if (n == 0)
return 0;
else if (n % 2)

return f(n/2, 2*k) + k; else return f(n/2, 2*k) - k;


}
int main ()
{
printf("%d", f(20, 1));
return 0;
}

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

i is integer and *p is value of a pointer to short.


1)Option 1 is wrong because we are passing "*S" as second argument check that S
is not a pointer variable .So error
2) Second option is we are trying to store the value of f(i,s) into i but look at
the function definition outside main it has no return type. It is simply void so that
assignment is wrong. So error
3)Option 3 is wrong because of the same reason why option 1 is wrong
4) So option d is correct.
Question 49
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 49

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

f (x1, x2, …, xn) = x1’f(x1, x2, …, xn) + x1f(x1, x2, …, xn)

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,

x2, …, 0) + 0.f(x1, x2, …, 1) RHS =f(x1, x2, …, 0)

Case 2: taking xn=1 RHS = 0.f(x1, x2, …, 0) + 1.f(x1, x2,

…, 1) RHS =f(x1, x2, …, 1) In both cases RHS=LHS, so, (C)

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 first iteration: i = 0: a = cos(pi * 0/2) a = cos(0) = 1, condition true print 1


Second iteration: i = 1 a = cos (pi/2) a = 0, so else part would print 0 Third
iteration: i = 2 a = cos(pi) a = -1, since any value other than 0 inside if
statement returns true, print 1 Output: 101 Option (C) is correct
Question 53
Consider the following C program
#include
main()
{
float sum = 0.0, j =1.0, i = 2.0;
while(i/j > 0.001) {
j = j + 1;
sum = sum + i/j;
printf ( "%fn", sum );
}
}
How many lines of output does this program produce?
A. 0-9 lines of output

B.10-19 lines of output

C 20-29 lines of output


Solution 53
program wil produce more than 29 lines of output.
Let's analyze the program:
The program enters a while loop with the condition i/j > 0.001.
Inside the loop, j is incremented by 1, and sum is updated
by adding i/j. The printf statement prints the current value of
sum.
Since the condition for the loop to continue is i/j > 0.001, the loop wil continue until i/j
becomes less than or equal to 0.001.
Initial y, i is 2.0 and j is 1.0, so i/j is 2.0/1.0, which is greater than 0.001.

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

In C, parameters are always

A. Passed by value

B. Passed by reference

C Non-pointer variables are passed by value and pointers are passed by


reference

D. Passed by value result


Solution 55

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

Heap allocation is required for languages.

A that support recursion


B. that support dynamic data structures

C. that use dynamic scope rules

D. None of the above


Solution 56

Memory is taken from heap for dynamic


allocation.

So, option (B) is correct.


Question 57

What are x and y in the following macro


definition?

macro Add
x,y Load y

Mul x

Store y

end

macro
A Variables
B. Identifiers

C.Actual
Solution 57

Correct option is (C)

Actual parameters:-

A parameter is a special kind of variable, used in a subroutine to refer to one of

the pieces of data provided as input to the subroutine.

The variable or expression corresponding to a formal parameter that appears in

the function or method call in the calling environment.At the time of the call each

actual parameter is assigned to the corresponding formal parameter in the

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

Is true and using macro we can do


this.
Question 59

A programming language not supporting either recursion or pointer


type does not need the support of dynamic memory allocation.

A TRUE

B FALSE
Solution 60

False The language can have dynamic data types which requires

dynamically growing memory when data type size increases.


Question 61
Consider the following pseudo code, where x and y are
positive integers. begin
q :=
0
r :=
x

while r ≥ y
do begin
r := r - y
q := q + 1
end
end

The post condition that needs to be satisfied after the program


terminates is A {r = qx + y 𝖠 r < y}
B {x = qy + r 𝖠 r < y}
Solution 61
Correct Option: B

The loop terminates when r<y. So, r<y is one post condition.
In each iteration q is incremented by 1 and y is subtracted from r. Initial

value of 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

j is changed inside the recursion.


Question 63

Consider the following function

double f (double x) {

if ( abs (x * x –3) < 0. 01) return x;

else return f (x / 2 + 1.5/x);


}

Give a value q (to 2 decimals) such that f(q) will return q:


Solution 63

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

same copy of x, but different copies of c.

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.

So the value of expression x^4 becomes 9^4 which is 6561.


Question 65
Which of the following are true?
I.A programming language which does not permit global variables of any kind and has no
nesting of
procedures/functions, but permits recursion can be implemented with static storage
allocation
II.Multi-level access link (or display) arrangement is needed to arrange activation
records only if the programming language being implemented has nesting of
procedures/functions
III. Recursion in programming languages cannot be implemented with dynamic storage
allocation
IV.Nesting procedures/functions and recursion require a dynamic heap allocation scheme and
cannot be
implemented with a stack-based allocation scheme for activation records
V.Programming languages which permit a function to return a function as its result cannot be
implemented with a stack-based storage allocation scheme for activation records
A II and V only
Solution 65
Answer:
(A)
Explanation: I. Recursion cannot be implemented with Static Storage Allocation. Static allocation
means, compiler has to decide size for function calls. In case of recursion, it is not possible for compiler to
decide as depth of recursion depends on recursion parameter which may be an input from user also.

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

The Answer: No Option is correct.


Question 67
The following program fragment is written in a programming language that allows global variables and does
not allow nested declarations of functions.global int i = 100, j = 5;
void P(x)
{ int i
= 10;
print(x +
10); i =
200;
j = 20;
print
(x);
}
main() {
P(i + j);
}

If the programming language uses static scoping and call by 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);

print

x;

print

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

and variables y and z of func1 points to address of


variable x. Therefore,

y=y+4⟹y=10+4=14
and
z=x+y+z⟹z=14+14+3=31
z will be stored back in x. Hence, x=31 and y will remain as it
is. (y=3)
Answer is 31,
3
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.

therefore o/p will be 4, which is not in any option.


Question 70
The most appropriate matching for the following pairs

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

Y: n is freed and so pointer is now pointing to an invalid memory making it a


Dangling pointer.

Z: p is not initialized. P = malloc(sizeof(char)); should have been used


before assigning a to *p
Question 71
What is printed by the following ANSI C program?
#include <stdio.h>
int main(int argc, char *argv[]) {
char a = 'P';
char b = 'x';
char c = (a & b) + '*';
char d = (a | b) $$-$$ '$
$-$$'; char e = (a ^ b)
+ '+'; printf("%c %c
%c\n", c, d, e);
return 0;
}
ASCII encoding for relevant characters is
given below :
A. z K S

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.

a = ‘P’ ===> a = Ascii value of (‘P’) =


a & b == 80[ ==>
65+15 applya&=logic
b = on
‘x’ corresponding
===> b bits
= ]=
Ascii value
‘*’ = 42 = of (‘x’)
a&b +=‘*’97+23 = 120
= (0111 ==>
1010)2 =b =
64+32+16+8+2 = [ add corresponding bits ], [ simply 80+42
122 = 122 ]
print character ( 122 ) = small ‘z’
a|b = [ apply | logic on corresponding bits ] =
‘-’ = 45
a|b - ‘-’ = 120-45 = 75 = 65 + 10
print character ( 75 ) = Capital ‘K’

a^b= [ apply ^ logic on corresponding bits ] =

‘+’ = 43

a^b + ‘+’ = 40+43 = 83 = 65 + 18


print character ( 83 ) = Capital ‘S’
Question 72
Given the programming constructs:
(i) assignment
(ii)for loops where the loop parameter cannot be changed within the loop
(iii)if-then-else
(iv)forward go to
(v)arbitrary go to
(vi)non-recursive procedure call
(vii)recursive procedure/function call
(viii)repeat loop,

which constructs will you not include in a programming language such that it should be

possible to program the terminates (i.e., halting) function in the same programming

language.
A. (ii), (iii), (iv)
B. (v), (vii), (viii)
C. (vi), (vii), (viii)
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

implemented on this processor?

A Pointers
B. Arrays

C. Records

D. Recursive procedures with local variable


Solution 73
Pointer access requires indirect addressing which can be simulated with indexed
addressing or register indirect addressing but not with direct and immediate
addressing. An array and record access needs a pointer access. So, options (A), (B)
and (C) cannot be implemented on such a processor.

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.

So, options (A), (B), (C) and (D) are correct.


Question 74

Faster access to non-local variables is achieved using an array of pointers to


activation records called a
A stack
B heap
C
display

D activation tree
Solution 74
Correct Option: C
Properties of
displays

Use a pointer array to store the activation records along the


static chain.

Fast access for non-local but may be complicated to maintain.

Calling a subprogram in the same level – simply

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?

A Passing a constant value as a parameter


B Passing the address of an array as a parameter
C Passing an array element as a parameter

D Passing an array following statements is true


Solution 75
Correct Option: C

Passing an array element as a parameter is the

answer. Consider this function call


{
Output:
....
a[] = call-by-
reference:8
{0,1,2,3,4};
i = 0; call-by-name:0
In Call-by-name, each occurrence of the formal parameter is
fun(a[i]); replaced by the a
argument text. So, the function fun will be
}print a[0]; executed like:
fun(int x) {
{
int i = 1;
int i = a[i] = 8; //a[1] is changed to 8 and
1; x = } not a[0]

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

anticipated number of keys in a slot is always computed as (number of

keys)/(number of slots). So, option B is the correct answer.


Question 77

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

In double hashing scheme, the probe sequence is determined


by (ℎ1(k)+iℎ2(k))mod m, where i denotes the index in probe sequence

and m denotes the hash table size.

Given ℎ1(k) and ℎ2(k)

, 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

Given a hash table 𝑇 with 25 slots that stores 2000 elements,


the load
factor for 𝑇 is .
Solution 78

load factor = (no. of elements) / (no. of table slots) =


2000/25 = 80
Question 79

Consider the following two statements:

i.A hash function (these are often used for computing digital signatures) is an

injective function.

ii.encryption technique such as DES performs a permutation on the elements of

its input alphabet.


Which one of the following options is valid for the above two statements?
A Both are false
B Statement (i) is true and the other is
false
C Statement (ii) is true and the other is
false
Solution 79
Answer: (C)
Explanation:InjectiveFunci
on:

A function F(X) is said to be injective if it has one-to-one mapping.

Statement 1: Hash function is an injective function


Statement 2: DES Encryption technique performs a permutation on the elements of its input alphabet
1)Generally, a hash function H(X) is mapping from a larger set to a predefined output set
For example, let H(X) = (X)%5
The above function H(X) is not injective because Let X1 =
10, X2 = 15
H(10) = H(15) = 0
As the output of H(X1) = H(X2) where X1!= X2 => H(X) is many-to-one function.
Statement 1 is false.
2)In DES encryption scheme, it performs P-Box permutation.
Statement 1 is false,
Question 80

A hash table contains 10 buckets and uses linear probing to resolve

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

location would the key value 142 be inserted?

A. 2

B. 3

C. 4

D. 6
Solution 80
43 in loc 3

165 in loc 5

62 in loc 2

123 in loc 4 ( collission and next free space)

142 in loc 6 (collision in 2, and 3,4,5 already occupied)


Hence ans D
Question 81

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)

Explanation:Hash function given is mod(10).

9679, 1989 and 4199 all these give same hash value i.e 9

1471 and 6171 give hash value 1


Question 82

An advantage of chained hash table (external hashing) over the open

addressing scheme is
A Worst case complexity of search operations is less
B Space used is less
C Deletion is
easier
D None of the
above
Solution 82

Answer : In Open Addressing scheme sometimes though element is present


we can't delete it if empty bucket comes in between while

searching for that element.


External hashing scheme is free from this limitations .
Hence, Option c is correct answer.
Question 83
Consider a dynamic hashing approach for 4-bit integer keys:
1.There is a main hash table of size 4.
2.The 2 least significant bits of a key is used to index into the main hash table.
3.Initially, the main hash table entries are empty.
4.Thereafter, when more keys are hashed into it, to resolve collisions, the set of all keys
corresponding to a main hash table entry is
organized as a binary tree that grows on demand.
5.First, the 3rd least significant bit is used to divide the keys into left and right subtrees.
6.to resolve more collisions, each node of the binary tree is further sub-divided into left
and right subtrees based on 4th least significant bit.
7.A split is done only if it is needed, i. e. only
when there is a collision. Consider the following
state of the hash table.
Which of the following sequence of key insertions can cause the above state of the hash table
(assume the keys are in decimal
A 10, 9, 6, 7, 5, 13
B 5, 9, 4, 13, 10, 7
C 9, 5, 13, 6, 10, 14
D 9, 5, 10, 6, 7, 1
Solution 83
Answer: (C)

Explanation: Sequence given in option (A) is not possible, because of entry 4 (=


0100) which is not in final hash table.

Sequence given in option (B) is not possible, because of entry 1 (=0001) and

9 (=1001) resolving collision on 0 side based on third LSB.


Sequence given in option (C) is the correct sequence to get given final hash table.

Sequence given in option (D) is not possible, because of entry 6 (=0110), 10

(=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

the first 3 slots are unfilled after the first 3 insertions?

A (97 × 97 × 97)/1003
B (99 × 98 × 97)/1003

C (97 × 96 × 95)/1003

D (97 × 96 × 95)/(3! × 1003)


Solution 85

Answer: (A)
Explanation:

Simple Uniform hashing function is a hypothetical hashing function that evenly

distributes items into the slots of a hash table. Moreover, each item to be hashed has

an equal probability of being


placed into a slot, regardless of the other elements already placed.
Probability that the first 3 slots are unfilled after the first 3
insertions = (probability that first item doesn\'t go in
any of the first 3 slots)*
(probability that second item doesn\'t go in any of the first
3 slots)* (probability that third item doesn\'t go in any of
Question 86
A hash table of length 10 uses open addressing with hash function h(k)=k mod
10, and linear probing. After inserting 6 values into an empty hash
table, the table is as shown belowWhich one of the following choices gives a
possible order in which the key values could have been inserted in the table?

A 46, 42, 34, 52, 23, 33

B 34, 42, 23, 52, 33, 46

C 46, 34, 42, 23, 52, 33

D 42, 46, 33, 23, 34, 52

.
Solution 86

Answer (C)
The sequence (A) doesn’t create the hash table as the element 52

appears before 23 in this sequence.


The sequence (B) doesn’t create the hash table as the element 33
appears before 46 in this sequence.
The sequence (C) creates the hash table as 42, 23 and 34 appear before 52 and
33, and 46 appears before 33.
The sequence (D) doesn’t create the hash table as the element 33
appears before 23 in this sequence.
Question 87
Solution 87

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

= T(n^(1/a^k)) + k log_b(n)) Option


Question 88
A hash table of length 10 uses open addressing with hash function h(k)=k mod
10, and linear probing. After inserting 6 values into an empty hash
table, the table is as shown belowHow many different insertion sequences of the
key values using the same hash function and linear probing will result in the hash
table shown abo

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

52 and 33, and 46 must appear before 33.


Total number of different sequences = 3! x 5 = 30
In the above expression, 3! is for elements 42, 23 and 34 as they can
appear in any order, and 5 is for element 46 as it can appear at 5 different places.
Question 89

The keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted into an initially empty hash
table of length 10 using open addressing with hash function h(k) = k

mod 10 and linear probing. What is the resultant hash table?


Solution 89

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

43 36 92 87 11 4 71 13 14 is inserted into an initially empty hash table, the


bins of which are indexed from zero to ten. What is the index of the bin into
which the last record is inserted?
A. 2
B. 4
C. 6
D. 7
Solution 90

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

new key hashed collides with an existing one exceed 0.5.

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)

=1−Probability that there was no collision in the first n hashes


=1−1.19/20.18/20…(20−n+1)/20.
So, we need,
0.5 < 1 −1 .19/20 . 18/20…(20−n+1)/20.
⟹19/20.18/20…(20−n+1)/20 < 0.5.

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

highest order in the polynomial will also get squared.


Option B: It is not true in cases when f(n) is a polynomial function. Option C: An
exponential function may be increasing or decreasing, so this condition may
not always be true.

Option D: It need not be true for a function that is decreasing.


Question
94
Consider the following recurrence:
f(1) = 1;
f(2n) = 2f(n) − 1, for n ≥1;
f(2n + 1) = 2f(n) + 1, for n ≥ 1;
Then, which of the following statements is/are
TRUE? A f( 2^n − 1) = 2n − 1

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

= T(n^(1/a^k)) + k log_b(n)) Option


Question 95

The equality above remains correct if X is


replace by

(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

Sum of the cubes of the first

natural numbers is given by (n(n+1)/2)^2


which is Θ(n^4)
. So, I, III and IV are correct. II is wrong.
∴ (C) is correct.
Question 96

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

What is the time complexity of Bellman-Ford single-source shortest path


algorithm on a complete graph of n vertices?

A. Θ(n^2)
B. Θ(n^2 logn)
C. Θ(n^3)

D Θ(n^3 logn)
Solution 98

Answer: (C)

Explanation: Time complexity of Bellman-Ford algorithm is O(VE) where V is


number of vertices and E is number of edges. For a complete graph with
n vertices, V = n, E = O(n^2). So overall time complexity becomes
O(n^3)
Question 99

Let W(n) and A(n) denote respectively, the worst case and average case running
time of an algorithm executed on an input of size n. Which of the

following is ALWAYS TRUE?

A. A(n)=Ω(W(n))

B. A(n)=Θ(W(n))
C. A(n)=O(W(n))
D. A(n)=0(W(n))
Solution 99

Answer: (C)

Explanation: The worst case time complexity is always greater than or


same as the average case time complexity.
The term written in Big O notation can always asymptotically same or
greater than the term on the other side.
Question 100
Two alternate packages A and B are available for processing a database having 10k
records. Package A requires 0.0001n^2 time units and package B
requires 10n log_10 n time units to process n records. What is the smallest
value of k for which package B will be preferred over A?

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

Consider the following segment of C-code:


int j, n;
j=1;
while(j <=
n) j = j * 2;

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.

For example, for n=5 we have the following (4)

comparisons: 1 <= 5 (T)


2 <= 5 (T)
4 <= 5 (T)
8 <= 5 (F)
FLOOR(log_2 n)+2 = FLOOR(log_2 5) + 2 = FLOOR(2.3) + 2 = 2 +
2=4
Question 102

Consider the following C-program fragment in which i, j and n are integer


variables. for (i = n, j = 0; i >0; i /= 2, j += i);
Let val(j) denote the value stored in the variable j after termination of the for loop.
Which one of the following is true?
(A) val(j) = Θ(logn)
(B) vaI(j) = Θ(sqrt(n))
(C) val(j) = Θ(n)
(D) val(j) = Θ(nlogn)
(E) A
(F) B
(G) C
(H) D
Solution 102

Answer: (C)

Explanation: The variable j is initially 0 and value of j is sum of values of i. i is


initialized as n and is reduced to half in each iteration.

j = n/2 + n/4 + n/8 + .. + 1 = Θ(n)

Note the semicolon after the for loop, so there is nothing in the body.
Question 103

The time complexity of computing the transitive closure of a binary relation on a


set of elements is known to be:

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.

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
Question 104

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

one pointer for moving (the next pointer).


In the worst case, for searching an element in the singly linked list, we will have to
traverse the whole list (the case when the required element is either the last
element or is not present in the list).
So, in the worst case for a list of length n, we will have to go to each node for
comparison and thus, we would be needing ‘n’ comparisons.

Thus, D is the correct choice.


Question 105

Faster access to non-local variables is achieved using an array of pointers to


activation records called a
A stack
B heap
C
display

D activation tree
Solution 105
Correct Option: C
Properties of
displays

Use a pointer array to store the activation records along the


static chain.

Fast access for non-local but may be complicated to maintain.

Calling a subprogram in the same level – simply

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?

A Passing a constant value as a parameter


B Passing the address of an array as a parameter
C Passing an array element as a parameter

D Passing an array following statements is true


Solution 106
Correct Option: C
Passing an array element as a parameter is the answer.
Consider this function call
{
....
a[] = {0,1,2,3,4};
i = 0;
fun(a[i]);
print a[0];
}
fun(int x)
{
int i = 1;
x = 8;
}
Output:
call-by-reference:8
call-by-name:0
In Call-by-name, each occurrence of the formal parameter is replaced by the
actual argument text. So, the function fun will be executed like:
{
int i = 1;
a[i] = 8; //a[1] is changed to 8 and not a[0]
}
Question 107

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?

A f(n) = O(g(n)) and g(n) ≠ O(f(n))

B. g(n) = O(f(n)) and f(n) ≠ O(g(n))

C. f(n) ≠ O(g(n)) and g(n) ≠ O(f(n))

D. f(n) = O(g(n)) and g(n) = O(f(n))


Solution 107
Answer: (B)
Explanation:
Any constant power of Logn is asymptotically smaller than n.
Proof:
Given f(n) =n^2 Logn and g(n) = n (logn)^10
In these type of questions, we suggest you to first cancel out the
common factor in both the function.
After removing these, we
left with f(n) = nare
and g(n) = (logn)^9. Removing a factor of nlogn from
both functions.
Now n is very very large asymptotically as compared to any constant integral power of (logn)
which we can verify by substituting very
large value say 2100.
f(2100) = 2100 = 1030 and g(2100) = 1009 = 1018.
Always remember to substitute very large values of n in order to compare both these functions.
Otherwise you will arrive at wrong
conclusions because if f(n) is asymptotically larger than g(n) that means after a particular
value of n, f(n) will always be greater that g(n).
Question 108

The concatenation of two lists is to be performed on 0(1) time. Which of the


following implementations of a list should be used?

A.Singly linked list

B. Doubly linked list

C.Circular doubly linkedlist

D.Array implementation of list


Solution 108

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

Consider the following three functions.

f1 = 10^n, f2 = n^logn, f3 = n^√n


Which one of the following options arranges the functions in the increasing
order of asymptotic growth rate? A
f1 , f2, f3
B f2, f1, f3 C
f3, f2, f1 D
f2, f3, f1
Solution 109

Answer: (D)

Explanation: On comparing power of these given functions : f1 has


n in power.
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 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.

So the recurrence relation will be –


A(n) = 5A(n/2) + O(1) (O(1) because rest of the statements have O(1)
complexity.) Solving this recurrence relation using Master theorem –
a = 5 , b= 2 , f(n) =O(1) , nlogb a= nlog2 5 (case 1 master theorem)
A(n) =nlogb a
value of log 25 is 2.3219, so, the best option is option a
Question 111
An algorithm performs (logN)^1/2 find operations, N insert operations,
(logN)^1/2 delete operations, and (logN)^1/2 decrease-key operations on a set
of data items with keys drawn

from a linearly ordered set. For a delete operation, a pointer is provided to the

record that must be deleted. For the decrease-key operation, a pointer is provided

to the record that has its key


decreased. Which one of the following data structures is the most suited for the
algorithm to
use, if the goal is to achieve the best total asymptotic complexity
considering all the operations?
(A) Unsorted array
Solution 111
Answer: (A)

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.

Since number of insertion operations is asymptotically higher, unsorted array is


Question 112
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;
}
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)
Answer: (D)

Explanation:
int fun1 (int n)
{
int i, j, k, p, q = 0;

// This loop runs Θ(n) time


for (i = 1; i < n; ++i)
{
p = 0;

// This loop runs


Θ(Log n) times for
(j=n; j > 1; j=j/2)
++p;
// Since above loop runs Θ(Log n) times, p = Θ(Log n)
// This loop runs Θ(Log p) times which loglogn
for (k=1; k < p; k=k*2)
++q;
}
return q;
}
T(n) = n(logn + loglogn)
T(n) = n(logn) dominant
But please note here we are return q which lies in loglogn so ans should be T(n) =
nloglogn
Question 113

Let f(n) = n and g(n) = n(1+sin n), where n is a positive integer. Which of

the following statements is/are correct?

I. f(n) = O(g(n))

II. f(n) = Ω(g(n))

(A) Only I

(B) Only II

(C) Both I and II

(D) Neither I nor II


Solution 113

Answer: (D)

Explanation: The value of sine function varies from -1 to 1. For sin = -1 or any
other negative value, I becomes false.

For sin = 1 or any other positive value, II becomes false.


Question 114

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)

(D) none of the above, as the tree cannot be uniquely determined.


Solution 115

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

The minimum number of comparisons required to determine if an integer

appears more than n/2 times in a sorted array of n integers is

(A) Θ(n)

(B) Θ(logn)

(C) Θ(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

conquer technique,lets say it is i.

The Last occurrence of an element can be found out in O(log(n)) time using divide and

conquer technique,lets say it is j.


Now number of occurrence of that element(count) is (j-i+1). Overall time complexity = log
n +log
Question 117

Assume the following C variable declaration


int *A [10], B[10][10];
Of the following expressions which will not give compile-time errors if used as left
hand sides of assignment statements in a C program?
I. A[2]
II. A[2][3]
III. B[1]
IV. B[2][3]
Solution 117

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

An n x n array v is defined as follows V [i, j] = i - j for all i, j, 1≤ i ≤ n,1≤ j ≤ n.


The sum of the elements of the array v is ?
A.0
B.n-1
C. n2-3n+2
D. n2(n+1)/2

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

B. &A[0][0][0] + w(y * z * p + z*q + 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

Let A be a two dimensional array declared as follows:Assuming that each integer


takes one memory location, the array is stored in row-major order and the first
element of the array is stored at location 100, what is the address of the element
A[i][j]?
A: array[1.........10][1.........15] of integers
A. 15i+j+84 B. 15j+i+84 C. 10i+j+89 D. 10j+i+89
Solution 123

Solution: A

A[LB1 ...UB1,LB2 ...UB2]


BA = Base address.
C = size of each element. Row major order.
Loc(a[i][j])=BA+[(i−LB1)(UB2 −LB2 +1)+(j−LB2)]∗C. Column Major order
Loc(a[i][j])=BA+[(j−LB2)(UB1 −LB1 +1)+(i−LB1)]∗C. Substituting the values.;
Question 124

What is printed by the following ANSI C program?


#include <stdio.h>
Int main() {
int x = 1, z[2] = {10, 11};
int *p = NULL; p = &x;
*p = 10;
p = &z[1];
*(&z[0] + 1) += 3;
printf("%d, %d, %d\n", x, z[0], z[1]); return 0
Solution 124
Solution : 10 10 14
Explanation:
●x is initialized to 1, and then a pointer p is created and the address of x.
●The value of x is then changed to 10 using the pointer p.
●p is reassigned to the address of z[1], which is the second element in the z array.
●The value of z[0] (which is 10) is incremented by 3 using pointer
arithmetic,
specifically by adding 1 to the address of z[0] (i.e., &z[0]) and then dereferencing
the
resulting pointer and adding 3 to it.
●The final values of x, z[0], and z[1] are printed using printf statement. Therefore,
the output will be 10, 10, 14
Question 125

Consider the following C program :


#include < stdio.h >
int main () {
int arr [] = {1,2,3,4,5,6,7,8,9,0,1,2,5}, *ip = arr+4; printf ("%d\n", ip[1]); return 0;
}
The number that will be displayed on execution of the program is
Solution 125

Solution: 6
Explanation:

The array arr is initialized with 13 integers.


●A pointer variable ip is declared and initialized to the memory location of the fifth
element of the array arr (i.e., arr+4).
●The expression ip[1] is used to access the integer value stored in the memory
location that is one integer after the memory location pointed
to by ip. This location contains the integer 6.
●The integer value 6 is printed using printf statement. Therefore, the output will be
6.
Question 126

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

Disadvantages of linked list representation of binary trees over arrays?


a) Randomly accessing is not possible
b) Extra memory for a pointer is needed with every element in the list
c) Difficulty in deletion
d) Random access is not possible and extra memory with every element
Solution 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

Consider the following C program. #include <stdio.h> int main() {


int A[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int *p = A;
p += 3;
printf("%d\n", (*p));
p -= 2; printf("%d\n", (*p)); return 0;
}
What does the program output?
(A) 3 1 (B) 3 2 (C) 6 1 (D) 6 2
Solution 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

Using what formula can a parent node be located in an array?


a) (i+1)/2
b) (i-1)/2
c) i/2
d) 2i/2
Solution 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

Consider the following program: #include


<stdio.h> int main() {
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr + 2;printf("%d\n", *ptr++);
printf("%d\n", (*ptr)++); printf("%d\n", *ptr); return 0;
}
What is the output of the
program?
Solution 137
Solution: 3
4
5
Explanation:

int arr[] = {1, 2, 3, 4, 5} initializes an integer array with values 1, 2, 3,


4, 5.
int *ptr = arr + 2 initializes a pointer ptr to point to the third element of the array,
i.e., 3.
printf("%d\n", *ptr++) prints the value at the memory location pointed to by ptr,
which is 3, and then increments ptr to point to the next element of the array, i.e.,
4.
printf("%d\n", (*ptr)++) prints the value at the memory location pointed to by ptr,
which is 4, and then increments the value stored in that memory location to
5.
printf("%d\n", *ptr) prints the value at the memory location pointed to by ptr, which
is 5.
Question 138

Consider the following program: #include


<stdio.h>
void increment (int **p) {
(**p)++;
}
int main() {
int i = 10;
int *ptr = &i;
increment(&ptr);
printf("%d", *ptr);
return 0;
}

What is the output of


the program?
Solution 138
Solution 11.
Explanation:
The function increment() takes a pointer to a pointer to an integer as
argument. In the main() function, an integer variable i is declared and its
address is assigned to a pointer variable ptr. Then, the address of ptr is
passed as an argument to the function increment().
In the function increment(), the pointer to pointer p is dereferenced twice
using the ** operator to obtain the value of the integer
variable i, and then it is incremented by 1 using the ++
operator. As a result, the value of i becomes 11. Back in the
main() function, the value of i is printed using the pointer
ptr, and the output is 11.
Question 139

Consider the following C program: #include <stdio.h>

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

Solution The output of the corrected

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

Solution: Since the matrix A is stored in row-major order in a contiguous block of


memory, we can access its (i,j)th element using the following formula:
A[i][j] = *(A + i*n + j)
Here, A is a pointer to the first element of the matrix A, which is of typeint[n][n]. The
expression (int )A casts the pointer to a pointer of
type int, which points to the first element of the matrix. The (i*n + j) term calculates
the offset of the (i,j)th element relative to the first element, taking into account the
row-major ordering of the elements. Finally, the * operator dereferences the resulting
pointer to give the value of the (i,j)th element.
Question 141

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;
}

What is the output of the program?

.
Solution 141

The output of the program is 1101214.


Here is the explanation:
printf("%d", (*p)++);: The value of *p is 1, and the post-increment operator ++
increments it to 2. The expression evaluates to 1, so the first printf statement
outputs 1
printf("%d", ++(*q));: The value of *q is 9, and the pre-increment operator ++
increments it to 10. The expression evaluates to 10, so the second printf
statement outputs 10.
printf("%d", (*p) + (*q));: The value of *p is 2 and the value of *q is 10. The
expression (*p) + (*q) evaluates to 12, so the third printf statement outputs 12.
printf("%d", ++(*p) + ++(*q));: The value of *p is 3 and the value of *q is 11.
The first ++(*p) expression increments *p to 2 and evaluates to
3. The second ++(*q) expression increments *q to 10 and evaluates to 11. The
sum of 3 and 11 is 14, so the fourth printf statement outputs 14.
Question 142

What is the output of the following C code?

#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

Which of the following is true about pointers in C?

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

What is the output of the following C code?

#include<stdio.h> int main() {


char str[]="Hello";
char *p=str;
printf("%c\n",*++p);
return 0;
}

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.

Hence, the correct option is (b) e.


Question 145

Let P be a singly linked list, Let Q be the pointer


to an intermediate node x in the list.What is the
worst-case time complexity of the best known
algorithm to delete the node x from the list?
A. O(N )
B. O(log2 N )
C. O(logN )
D.O(NlogN)
Solution 145
Solution A
To delete a node Q from a singly linked list, we need to modify the next pointer of
th e node that precedes Q to point to the node that follows Q.However, in a singly
linked list, we cannot traverse the list backwards from a given node, so we need to
start from the beginning of the list to find the node that precedes Q. Therefore,
the worst-case time complexity of the best known algorithm to delete the node Q
from the list is O(n), where n is the length of the list. This is because we may need
to traverse the entire list to find the node thatprecedes Q.
However, if we have a pointer to the node that precedes Q, the
deletionoperation can be performed in O(1) time complexity, since we can
simply modify the next pointer of that node to skip over Q. But, if we do not
have a pointer to the node that precedes Q, we need to start from the beginning
of the list and traverse the list to find it, which takes O(n) time complexity in the
worst case.
Question 146

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;

while (current != NULL)


{
temp = current->prev;
current->prev = current->next; current->next = temp;
current = current->prev;
}

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

A. 2 <-> 1 <-> 4 <-> 3 <-> 6 <->5


B. 5 <-> 4 <-> 3 <-> 2 <-> 1 <->6
C. 6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1
Solution 148

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. Merge Sort


Both Merge and Insertion sort can be used for linked lists.
Question 150
Output of the following function to start pointing to the first node of the
following linked list? 1->2->3->4->5->6 void fun(struct node* start)
{
if(start == NULL) return;
printf("%d ", start->data);

if(start->next != NULL ) fun(start->next->next); printf("%d ", start->data);


}
Run-on IDE
A. 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 150

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;

Node *move_to_front(Node *head)


{
Node *p, *q;
if ((head == NULL: ||(head->next == NULL)) return head;
q = NULL; p = head; while (p-> next !=NULL)
{
q = p;
p = p->next;
}
return head;
}
A.q = NULL ; p -> next = head ; head = p ;
B.q -> next = NULL ; head = p ; p -> next = head ;
C.head = p ; p -> next = q ; q -> next = NULL ;
D.q -> next = NULL ; p -> next = head ; head = p ;
Solution 151

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

Solution: D. union, intersection


For example, we have two linked lists. We have to fetch every node first
and check it into the second node. So complexity will become O(n^2).
Question 153
Can we create a doubly linked list using one pointer with every node?
A.Not, possible
B.Yes, possible
C.I can’t say anything
D.May
Solution 153

Solution: B. Yes, possible


By storing XOR of addresses of previous and next nodes.
The technique involves storing the XOR of the addresses of the previous
and
next nodes in a single pointer field in each node. With this technique, we
can traverse the list in both directions, just like in a traditional doubly
linked list.
Added as fact not a popular Approach
Question 154

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: c. Delete the last element.


Question 155

Consider the function f defined below.


struct item
{
int data;
struct item * next;
};

int f(struct item *p)


{
return (
(p == NULL) ||
(p->next == NULL) ||
(( p->data <= p->next->data) && f(p->next))
);
}
A.not all elements in the list have the same data value.
B.the elements in the list are sorted in non-decreasing order of data value
C.he elements in the list are sorted in non-increasing order of data value
D.None of the above
Solution 155

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

A circularly linked list is used to represent a Queue. A single variable p


is used to access the Queue. To which node should p point such that
both the operations enQueue and deQueue can be performed in
constant time?
A.Rear Node
B.Front Node
C. Not possible with single pointer
D. Node next to front
Solution 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

What is a complete binary tree?


a) Each node has exactly zero or two children
b) A binary tree, which is completely filled, with the possible exception of
the bottom level, which is filled from right to left
c) A binary tree, which is completely filled, with the possible exception of
the bottom level, which is filled from left to right
d) A tree In which all nodes have degree 2
Solution 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

In a full binary tree if number of internal nodes is I, then number of leaves


L are?
a) L = 2*I
b) L = I + 1
c) L = I – 1
d) L = 2*I – 1
Solution 160
Answer: b
Explanation: Number of Leaf nodes in full binary tree is equal to 1
+ Number of Internal Nodes i.e L = I + 1
Question 161

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

The post-order traversal of a binary tree is O P Q R S T. Then possible pre-


order traversal will be ________
a) T Q R S O P
b) T O Q R P S
c) T Q O P S R
d) T Q O S P R
Solution 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

A full binary tree can be generated using ______


a) post-order and pre-order traversal
b) pre-order traversal
c) post-order traversal
d) in-order traversal
Solution 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

The pre-order and in-order are traversals of a binary tree are T M L N P O Q


and L M N T O P Q. Which of following is post-order traversal of the tree?
a) L N M O Q P T
b) N M O P O L T
c) L M N O P Q T
d) O P L M N Q T
Solution 167
Answer: a
Explanation: The tree generated by using given pre-order and in-
order traversal is

Thus, L N M O Q P T will be the post-order traversal.


Question 168

What is the space complexity of the in-order traversal in the recursive


fashion? (d is the tree depth and n is the number of nodes)
a) O(1)
b) O(nlogd)
c) O(logd)
d) O(d)
Solution 168

Answer: d
Explanation: In the worst case we have d stack frames in the
recursive call, hence the complexity is O(d).
Question 169

What is the output of the following Java code?


public class array { public static void main(String args[]) { int []arr =
{1,2,3,4,5}; System.out.println(arr[2]); System.out.println(arr[4]); } }
a) 3 and 5
b) 5 and 3
c) 2 and 4
d) 4 and 2
Solution 169

Answer: a
Explanation: Array indexing starts from 0.
Question 170

What is the output of the following Java code?


public class array { public static void main(String args[]) { int []arr =
{1,2,3,4,5}; System.out.println(arr[5]); } }
a) 4
b) 5
c) ArrayIndexOutOfBoundsException
d) InavlidInputException
Solution 170

Answer: c
Explanation: Trying to access an element beyond the limits of an
array gives ArrayIndexOutOfBoundsException.
Question 171

When does the ArrayIndexOutOfBoundsException occur?


a) Compile-time
b) Run-time
c) Not an error
d) Not an exception at all
Solution 171

Answer: b
Explanation: ArrayIndexOutOfBoundsException is a run-time
exception and the compilation is error-free
Question 172

Which of the following concepts make extensive use of arrays?


a) Binary trees
b) Scheduling of processes
c) Caching
d) Spatial locality
Solution 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

What are the advantages of arrays?


a) Objects of mixed data types can be stored
b) Elements in an array cannot be sorted
c) Index of first element of an array is 1
d) Easier to store elements of same data type
Solution 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

Process of inserting an element in stack is called ____________


a) Create
b) Push
c) Evaluation
d) Pop
Solution 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

3. In a stack, if a user tries to remove an element from an empty


stack it is called _________
a) Underflow
b) Empty collection
c) Overflow
d) Garbage Collection
Solution 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

Entries in a stack are “ordered”. What is the meaning of this statement?


a) A collection of stacks is sortable
b) Stack entries may be compared with the ‘<‘ operation
c) The entries are stored in a linked list
d) There is a Sequential entry that is one by one
Solution 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

Which of the following is not the application of stack?


a) A parentheses balancing program
b) Tracking of local variables at run time
c) Compiler Syntax Analyzer
d) Data Transfer between two asynchronous process
Solution 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

Consider the usual algorithm for determining whether a sequence of


parentheses is balanced. Suppose that you run the algorithm on a
sequence that contains 2 left parentheses and 3 right parentheses (in
some order). The maximum number of parentheses that appear on the
stack AT ANY ONE TIME during the computation?
a) 1
b) 2
c) 3
d) 4 or more
Solution 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

What is the value of the postfix expression 6 3 2 4 + – *?


a) 1
b) 40
c) 74
d) -18
Solution 180

Answer: d
Explanation: Postfix Expression is (6*(3-(2+4))) which results -18
as output.
Question 181

Here is an infix expression: 4 + 3*(6*3-12). Suppose that we are using the


usual stack algorithm to convert the expression from infix to postfix
notation. The maximum number of symbols that will appear on the stack
AT ONE TIME during the conversion of this expression?
a) 1
b) 2
c) 3
d) 4
Solution 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

The data structure required to check whether an expression contains a


balanced parenthesis is?
a) Stack
b) Queue
c) Array
d) Tree
Solution 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

The postfix form of A*B+C/D is?


a) *AB/CD+
b) AB*CD/+
c) A*BC+/D
d) ABCD+/*
Solution 183

Answer: b
Explanation: Infix expression is (A*B)+(C/D)
AB*+(C/D)
AB*CD/+. Thus postfix expression is AB*CD/+.
Question 184

Convert the following infix expressions into its equivalent postfix


expressions.
(A + B ⋀D)/(E – F)+G
a) (A B D ⋀ + E F – / G +)
b) (A B D +⋀ E F – / G +)
c) (A B D ⋀ + E F/- G +)
d) (A B D E F + ⋀ / – G +)
Solution 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

Convert the following Infix expression to Postfix form using a stack.


x + y * z + (p * q + r) * s, Follow usual precedence rule and assume that
the expression is legal.
a) xyz*+pq*r+s*+
b) xyz*+pq*r+s+*
c) xyz+*pq*r+s*+
d) xyzp+**qr+s*+
Solution 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

Which of the following is not the type of queue?


a) Ordinary queue
b) Single ended queue
c) Circular queue
d) Priority queue
Solution 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

What would be the asymptotic time complexity to insert an element at the


front of the linked list (head is known)?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Solution 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

Consider the following definition in c programming language.


struct node
{ int data;
struct node * next;
}
typedef struct node NODE;
NODE *ptr;
Which of the following c code is used to create new node?
a) ptr = (NODE*)malloc(sizeof(NODE));
b) ptr = (NODE*)malloc(NODE);
c) ptr = (NODE*)malloc(sizeof(NODE*));
d) ptr = (NODE)malloc(sizeof(NODE));
Solution 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

Linked list data structure offers considerable saving in _____________


a) Computational Time
b) Space Utilization
c) Space Utilization and Computational Time
d) Speed Utilization
Solution 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

In the worst case, the number of comparisons needed to search a singly


linked list of length n for a given element is?
a) log2 n
b) n⁄2
c) log2 n – 1
d) n
Solution 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

Which of the following is not a disadvantage to the usage of array?


a) Fixed size
b) There are chances of wastage of memory space if elements inserted in
an array are lesser than the allocated size
c) Insertion based on position
d) Accessing elements at specified positions
Solution 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

What is the time complexity of inserting at the end in dynamic arrays?


a) O(1)
b) O(n)
c) O(logn)
d) Either O(1) or O(n)
Solution 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

Which of these is not an application of a linked list?


a) To implement file systems
b) For separate chaining in hash-tables
c) To implement non-binary trees
d) Random Access of elements
Solution 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

Which of the following is false about a doubly linked list?


a) We can navigate in both the directions
b) It requires more space than a singly linked list
c) The insertion and deletion of a node take a bit longer
d) Implementing a doubly linked list is easier than singly linked list
Solution 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

What is a memory efficient double linked list?


a) Each node has only one pointer to traverse the list back and forth
b) The list has breakpoints for faster traversal
c) An auxiliary singly linked list acts as a helper list to traverse through the
doubly linked list
d) A doubly linked list that uses bitwise AND operator for storing addresses
Solution 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

How do you calculate the pointer difference in a memory efficient double


linked list?
a) head xor tail
b) pointer to previous node xor pointer to next node
c) pointer to previous node – pointer to next node
d) pointer to next node – pointer to previous node
Solution 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

What differentiates a circular linked list from a normal linked list?


a) You cannot have the ‘next’ pointer point to null in a circular linked list
b) It is faster to traverse the circular linked list
c) You may or may not have the ‘next’ pointer point to null in a circular
linked list
d) Head node is known in circular linked list
Solution 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

5. Which of the following application makes use of a circular linked list?


a) Undo operation in a text editor
b) Recursive function calls
c) Allocating CPU to resources
d) Implement Hash Tables
Solution 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

Which of the following is false about a circular linked list?


a) Every node has a successor
b) Time complexity of inserting a new node at the head of the list is O(1)
c) Time complexity for deleting the last node is O(n)
d) We can traverse the whole circular linked list by starting from any point
Solution 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

What does ‘stack underflow’ refer to?


a) accessing item from an undefined stack
b) adding items to a full stack
c) removing items from an empty stack
d) index out of bounds exception
Solution 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

Array implementation of Stack is not dynamic, which of the following


statements supports this argument?
a) space allocation for array is fixed and cannot be changed during run-
time
b) user unable to give the input for stack operations
c) a runtime exception halts execution
d) improper program compilation
Solution 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

Which of the following array element will return the top-of-the-stack-


element for a stack of size N elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[N-2]
d) S[N+1]
Solution 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

A normal queue, if implemented using an array of size MAX_SIZE, gets full


when?
a) Rear = MAX_SIZE – 1
b) Front = (rear + 1)mod MAX_SIZE
c) Front = rear + 1
d) Rear = front
Solution 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

What does the following function do?


public Object some_func()throws emptyStackException
{
if(isEmpty())
throw new emptyStackException("underflow");
return first.getEle(); }
a) pop
b) delete the top-of-the-stack element
c) retrieve the top-of-the-stack element
d) push operation
Solution 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

What does ‘stack overflow’ refer to?


a) accessing item from an undefined stack
b) adding items to a full stack
c) removing items from an empty stack
d) index out of bounds exception
Solution 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

What is the need for a circular queue?


a) effective usage of memory
b) easier computations
c) to delete elements based on priority
d) implement LIFO principle in queues
Solution 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

What is/are the disadvantages of implementing tree using normal arrays?


a) difficulty in knowing children nodes of a node
b) difficult in finding the parent of a node
c) have to know the maximum number of nodes possible before creation of
trees
d) difficult to implement
Solution 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

number of leaves in such a tree with n internal nodes is:

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

the number of internal nodes. Let us see following for example

k=3

Number of internal nodes n = 4 Number of leaf nodes = (k-1)*n+ 1


= (3-1)*4 + 1

=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

B: B1, B2, B3 C: C1, C2

Measure group A and group B. Two cases arise:


1. They are equal. One more measurement is needed to find the heavy
coin in group C. Total two measurements needed in this case.
2.They are not equal. Find the heavy group, say A. Pick any two coins from this group,
say A1 and A3. Measure A1 and A3 in the pan balance. Two cases arise:
1. They are equal. A2 is the heavy coin. Total two measurements needed.

2. They are not equal. It is known which of A1 or A3 is heavy. Total two

measurements needed.
So, the above observations says that in any case, 2 measurements are enough
to find the heavy coin.
Question 232

The minimum number of comparisons required to determine if an


integer

appears more than n/2 times in a sorted array of n integers is


A. θ(n)
B. θ(logn)
C. θ(nlogn)
D. θ(1)
Solution 232
whenever there exists an element which is present in the array :
more than n/2 times, then definitely it will be present at the middle
index

position; in addition to that it will also be present at anyone of

the neighbourhood indices namely i−1 and i+1


No matter how we push that stream of More than n/2 times of elements
of same value around the Sorted Array, it is bound to be present at the
middle index + atleast anyone of its neighbourhood once we got the
element which should have occurred more that n/2 times we count its
total occurences in O(logn) time.
Question 233
Consider the following C
function. float f(float x, int y)
{
float p, s; int i;
for (s=1, p=1, i=1; i < y; i ++)
{
p*= x/i;
s+=p;
}
return s;
}
For large values of y, the return value of the function f best approximates
(GATE CS 2003)
A. x^y
B. e^x
C. ln(1 + x)
D. x^x
Solution 233

The function f() is implementation of Taylor's Series to calculates e^x

e^x = 1 + x + x^2/2! + x^3/3! + ---

More is the value of y more precise value of e^x will be returned by


f()
Question 234

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

how many races are required to get the top 3 horses.


A. 5

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

second fastest horse of the group which belongs to second fastest

horse of 6th race. The fastest and second fastest of 7th race are the 2nd and 3rd

fastest among all 25.


Question 235

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 235
Answer: (A)

Explanation:

Option A: It always holds because if we square the input variable, then the highest

order in the polynomial will also get squared.

Option B: It is not true in cases when f(n) is a polynomial function. Option C: An

exponential function may be increasing or decreasing, so


this condition may not always be true.

Option D: It need not be true for a function that is decreasing.


Question 236

Which of the following is the best possible time complexity to get


Nth

Fibonacci number with O(1) extra space


A. Time complexity T(n) is T(n-1) + T(n-2) which is exponential
B. O(n)
C. O(Logn)
D. O(n^2)
Solution 236
Using Binet’s formula

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

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 : (Hint :
Use a heap data structure)

A. O(n log log n)


B. θ(n log n)
C. Ω(n log n)
D. Ω(n3/2)
Solution
238

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

removes digits from n starting from left.


Question 240
Consider the following C program
main()
{
int x, y, m, n;
scanf ("%d %d", &x, &y);
/* Assume x > 0 and y > 0 */ A. x ÷ y using repeated subtraction
m = x; B. x mod y using repeated
n = y; subtraction
while (m! = n) C. the greatest common divisor of x
{ and y
if (m > n) D. the least common multiple of x
and y
m = m - n; else
n = n - m;
}
print f ("% d", n);
}
The program computes
Solution 240

Answer:
(C)

Explanation: The given program is iterative implementation


of Euclid's
Algorithm for GCD
Question 241
What does the following algorithm approximate? x
= m;
y = 1;
while (x - y > e)
{
x = (x + y)/2; y = m/x;
}
print(x);
(Assume m > 1, e > 0).
A.log m
B.m^2
C. m^1/2
D. m^1/3
Solution 241

Answer:
(C)

Explanation: The given code is implementation of Babylonian


method for
square root
Question 242

In a permutation a1.....an of n distinct integers, an inversion is a pair (ai,


aj) such that i < j and ai > aj. If all permutations are equally likely, what
is

the expected number of inversions in a randomly chosen permutation

of 1.....n ?
A. n(n - 1)/2
B. n(n - 1)/4
C. n(n + 1)/4
D. 2n[log2 n]
Solution 242

There are n(n-1)/2 pairs such that i < j.

For a pair (ai, aj), probability of being inversion is 1/2.

Therefore expected value of inversions = 1/2 * (n(n-


1)/2)
= n(n-1)/4
Question 243

The cube root of a natural number n is defined as the largest natural


number m such that m3 ≤ n. The complexity of computing the cube root
of

n (n is represented in binary notation) is:

A. O(n) but not O(n^0.5)


B. O(n^0.5) but not O((log n)^k) for any constant k > 0

C O((log n)^k) for some constant k > 0, but not O ((log log n)^m) for

any constant m > 0


D. O((log log n)^m) for some constant k > 0.5, but not O((log log n)^0.5)
Solution 243

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

Room1 - As Room2 - Bs Room3 - As now A ends (Ae) and now


Room3 is free Room3-Ds now A ends (Ae) and Room1 is free
Room1-Es Room4-Fs
now B ends Room2 is free now D ends Room3 is free Room2-Gs
now E ends Room1 free now F ends Room4 free Room1-Hs now
G and H ends.
Totally used 4 rooms
Question 245
Consider the following pseudo code, where x and y are positive
integers. begin
q := 0
r := x
while r >= y do
begin
r := r – y q := q + 1
end end
The post condition that needs to be satisfied after the program
terminates is
A.{r = qx + y 𝖠 r < y}
B.{x = qy + r 𝖠 r < y}
C. {y = qx + r 𝖠 0 < r < y}
D. { q + 1 < r– y 𝖠 y > 0}
Solution 245
The given pseudo code does following for given x and y which positive integers.
1)It initializes r as x.
2)It repeatedly subtracts y from r until r becomes
smaller than y. For every subtraction, it increments count q.
3)Finally r contains remainder, i.e., x%y and q contains
⌊x/y⌋
See below pseudo code with comments. begin
q := 0 // q is going to contain floor(x/y) r := x
// r is going to contain x % y

// Repeatedly subtract y from x.


while r >= y do
begin
r := r – y
q := q + 1 end
end
SOLUTION B
Question 246

The time complexity of computing the transitive closure of a


binary relation
on a set of elements is known
to be: A O (n)
B. O (n log n)
C. O (n^3/2)
D. O (n^3)
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.

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.

Floyd-Warshall algorithm is Dynamic Programming.

Binary search is a Divide and Conquer.

Backtracking is Depth-first search


Question 249

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 = 0, z = 1 mod 8 = 1, since c[0] = 1, z = 1*2 mod 8 = 2.

For i = 1, z = 2*2 mod 8 = 1, since c[1] = 0, z remains 4.

For i = 2, z = 16 mod 8 = 0

Once z becomes 0, none of the statements inside DOSOMETHING() can make it


non-zero.
Question 250
The following function computes XY for positive integers X and Y.
int exp(int X, int Y)
{
int res = 1, a = X, b = Y;
while ( b != 0 )
{
if ( b%2 == 0)
{
a = a*a;
b = b/2;
}
else
{
res = res*a;
b = b-1;
}
}
return res;
}
Which one of the following conditions is TRUE before every iteration of the loop
Solution 250
We can solve this question taking any two values for X and Y. Suppose X= 2 and Y= 5,
now this code will calculate Looking at each iteration separately Before iteration 1 –
X=2 Y= 5 a=2 , b=5, res=1 Iteration 1 – since b%2 !=0 we go to else part
Therefore after iteration 1, X=2, Y=5, a=2, b=4, res=2 Iteration 2 – since b%2=0 we
go to if part Therefore after iteration 2 , X=2, Y=5, a=4, b=2, res=2 Iteration 3 –
since b%2=0 we go to if part Therefore after iteration 3 , X=2, Y=5, a=16, b=1,
res=2 Iteration 4 – since b%2!=0 we go to else part Therefore after iteration 4 ,
X=2, Y=5, a=16, b=0, res=32 Now putting the values of X, Y , a, b, res in the
equations given in options after each iteration we can see only equation c is correct.
This solution is contributed by Parul sharma. Another solution In option C

Before Iteration 1: X^Y=64 res ∗

(a^b)=64 Before Iteration 2:


Question 251

The concatenation of two lists is to be performed on 0(1) time. Which


of
the following implementations of a list should be
used?
A. Singly linked list

B. Doubly linked list

C. Circular doubly linked list

D. Array implementation of list


Solution 251

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 252

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

overlap of X and Z be k units. Which of the following is true?

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

D. None of the above


Solution 252
Answer: (D)

Explanation: On comparing power of these given


functions : f1 has n in power.

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

Let H be a binary min-heap consisting of n elements implemented as an


array. What is the worst case time complexity of an optimal algorithm
to

find the maximum element in H?

A. Θ(1)
B. Θ(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

the following statements is/are correct?

I. f(n) = O(g(n))

II. f(n) = Ω(g(n))

(A) Only I

(B) Only II

(C) Both I and II

(D) Neither I nor II


Solution 256

Answer: (D)

Explanation: The value of sine function varies from


-1 to 1. For sin = -1 or any other negative value, I
becomes false. For sin = 1 or any other positive
value, II becomes false.
Question 257
Consider the following functions: F(n) = 2n

G(n) = n!

H(n) = nlogn

Which of the following statements about the asymptotic behaviour of f(n), g(n),

and h(n) is true?


A f(n) = O (g(n)); g(n) = O(h(n))

B. f(n) = Ω(g(n)); g(n) = O(h(n))

C. g(n) = O (f(n)); h(n) = O(f(n))

D. h(n) = O (f(n)); g(n) = Ω(f(n))


Solution 257

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

An array of 25 distinct elements is to be sorted using quicksort. Assume that the


pivot element is chosen uniformly at random. The probability that the pivot
element gets placed in the worst possible location in the first round of
partitioning (rounded off to 2 decimal places) is
Solution 260

Given an array of 25 distinct elements, and pivot element is chosen


uniformly randomly. So, there are only 2 worst case position in the pivot

element is either first (or) last.

Therefore, required probability is,

= 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:

(A) Θ(n log n), Θ(n log n) and Θ(n^2)

(B) Θ(n^2), Θ(n^2) and Θ(n Log n)

(C) Θ(n^2), Θ(n log n) and Θ(n log n)

(D) Θ(n^2), Θ(n log n) and Θ(n^2)


Solution 262
Answer: (D)

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?

In the recurrence equations given in the options below, c is a constant.

A T(n) = 2T(n/2) + cn

B T(n) = T(n - 1) + T(1) + 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

and recursive call is made for the following:

a) For subarray on left of pivot which is of size n -1 in worst case.

b) For subarray on right of pivot which is of size 0 in worst case.


Question 264

An unordered list contains n distinct elements. The number of comparisons to find an


element in this list that is neither maximum nor

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

7. Using 3 comparisons, we can find that the middle element is 10.


Question 265
Consider the following array of elements.

〈89,19,50,17,12,15,2,5,7,11,6,9,100〉

The minimum number of interchanges needed to convert it into a max- heap

is
A. 4

B. 5

C. 2

D. 3
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

traversal of the heap after the insertion of the elements is:

A 10, 8, 7, 3, 2, 1, 5

B 10, 8, 7, 2, 3, 1, 5

C 10, 8, 7, 1, 2, 3, 5

D 10, 8, 7, 5, 3, 2, 1
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

What is the number of swaps required to sort n elements using selection

sort, in the worst case?

(A) Θ(n)

(B) Θ(n log n)

(C) Θ(n2 )

(D) Θ(nn2 log n)


Solution 267
Answer (A)
Here is Selection Sort algorithm for sorting in ascending order.
1.Find the minimum value in the list
2.Swap it with the value in the first position
3.Repeat the steps above for the remainder of the list (starting at
the second position and advancing each time)

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

algorithm. Once we have connected components, we can count


them.
Question 269

Which of the following sorting algorithms has the lowest worst-case


complexity?
A Merge sort

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

In a binary max heap containing n numbers, the smallest element can be

found in time (GATE CS 2006)

(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

to the right of it in X. The best algorithm to find all leaders in an array.

(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

(C) Solves it using divide and conquer in time Theta(nlogn)

(D) Solves it in time Theta(n^2)


Solution 271
Answer: (B)
Follow the below steps to implement the idea:

We start from the last index position. The last position is always a leader, as there are no

elements towards its right.

And then we iterate on the array till we reach index position = 0.

Each time we keep a check on the maximum value

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

We will iterate on the stack and print the values


Question 272

The tightest lower bound on the number of comparisons, in the worst

case, for comparison-based sorting is of the order of

(A) N

(B) N^2

(C) NlogN

(D) N(logN)^2
Solution 272
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,
2^f(N) >= N! or equivalently f(N) >= log(N!).
Since log(N!) is Omega(NlogN), the answer is NlogN.
Question 273

In a heap with n elements with the smallest element at the root, the 7th

smallest element can be found in time

(A) Θ(n log n)

(B) Θ(n)

(C) Θ(log n)

(D) Θ(1)
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

exchanges required in the worst case is:

(A) n-1

(B) n

(C) n+1

(D) None of the above


Solution 274

Answer: (D)

Explanation: When we have ‘i’ numbers stored in an array, we have to


swap all positive numbers with negative and in worst case positive
numbers will be i/2.
Question 275

Give the correct matching for the following


pairs:
A. O(log n) 1. Selection
B. O(n) sort
2. Insertion sort
C. O(nlog
n) 3. Binary
D. O(n^2) search
4. Merge sort
codes:

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

C. Quicksort using the last element as pivot

D. Merge sort
Solution 276

Answer: (C)

Explanation: Since, given array is almost sorted in ascending order, so

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)

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)


Simple Solution One way to solve this is to try for small values and rule
out options. a0 = 0
a1 = 0
a2 = 1 ["11"]
a3 = 3 ["011", "110", "111"]
a4 = 8 ["0011", "0110", "0111", "1101",
"1011", "1100", "1110", "1111"]

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

The number of possible min-heaps containing each


value from
{1,2,3,4,5,6,7}. exactly once is .
Solution 278
Total number of min or max heap tree with 1 to N elements are using recurrence
relation: T(N) =(N-1)Ck * T(k) * T(N-k-1), where k = number of nodes on left subtree
T(1) = 1
T(2) = 1
T(3) = 2
T(4) = 3C2 * T(2) * T(1) = 3
T(5) = 4C3 * T(3) * T(1) = 8
T(6) = 5C3 * T(3) * T(2) = 20
T(7) = 5C3 * T(3) * T(3) = 80

So, answer is 80.


Question 279

A complete binary min-heap is made by including each integer in [1, 1023]


exactly once. The depth of a node in the heap is the length of the path from the
root of the heap to that node. Thus, the root is at depth 0. The maximum depth at
which integer 9 can appear is
Solution 279

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

insertion, the new heap is

(A) 40, 30, 20, 10, 15, 16, 17, 8, 4, 35

(B) 40, 35, 20, 10, 30, 16, 17, 8, 4, 15

(C) 40, 30, 20, 10, 35, 16, 17, 8, 4, 15

(D) 40, 35, 20, 10, 15, 16, 17, 8, 4, 30


Solution 281
Answer: (B)

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

finding the correct position then we need to do Θ(LogLogn) comparisons.


Question 284

Let H be a binary min-heap consisting of n elements implemented as an array.


What is the worst case time complexity of an optimal algorithm to

find the maximum element in H?

A. Θ(1)

B. Θ(logn)

C. Θ(n)

D. Θ(nlogn)
Solution 284

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 285

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

I encountered this problem while preparing for my exams.


Given two arrays of numbers a1,..., an and b1,....,bn where each number is 0 or 1,
the fastest
algorithm to find the largest span (i,j) such that , ai + ai+1 +....+aj = bi + bi+1
+....+bj or report that there is not such span.

(A) Takes O(3^n) and omega(2^n) time if hashing is permitted.


(B)Takes O(n^3) and omega(n^2.5) and time in the key
comparison mode (C)Takes theta(n) time and space
(D)Takes O(square-root(n)) time only if the sum of 2n elements is an even number.
Solution 286
The O(n) approach can be improved by sequentially placing the elements at their
correct position. The criteria of finding the target index remains same.
The main thing here to realize is that if we swap the current element with an element with
greater index, then
we can end up traversing on this element which has been placed at its correct position.

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 :

(Hint : Use a heap data structure)

(A) O(n log log n)

(B) θ(n log n)

(C) Ω(n log n)

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

(P) T(n) = T(n-1) + logn = log 1 + log 2 + log 3 + … + log n


= log(1*2*3…*n) = log(n!) = nlogn = O(nlogn) - choice is (v)
Therefore, none option matches.
Question 289

The average number of key comparisons done in a successful sequential

search in a list of length n is


(A) log n
(B) (n-1)/2

(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

For average comparison


= (n(n+1)/2) / n
= (n+1)/2
Option (D) is correct.
Question 290

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

Explanation: According to largest Sum Contiguous subarray is from index 2

to 11,

Max (S(i, j))

= S(2, 11)

= 6 + 3 + (-1) + (-2) + 13 + 4 + (-9) + (-1) + 4 + 12

= 29

So, answer is 29.


Question 291

Which one of the following correctly determines the solution of the

recurrence relation with T(1) = 1?

T(n) = 2T(n/2) + Logn

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

T(1) = 1 Subtracting 1 from 2, we get below


T(2^k) = - k + 2 + 4 ......2^(k-2) + 2^(k-1)
Substitute n = 2^k
+ 2^k +
T(2^k) =k+
2^(k+1)
2T(2^(k-1))
= - k + 2 * (1 + 2 + 4 + ..... 2^k)
T(2^k) = k + 2(k-1) + 4T(2^(k-2))
= -k + [2*(2^k - 1)] / [2-1]
= k + 2(k-1) + 4(K-2) + 8T(2^(k-3))
= k + 2(k-1) + 4(K-2) + 8(k-3) + 16T(2^(k- T(n) ==-Logn
-k + + 2*(n -=>
[2*(2^k 1)] T(n) =
4)) - 1) Θ(n)
= k + 2(k-1) + 4(K-2) + 8(k-3) + ...... +
2^kT(2^(k-k))
= k + 2(k-1) + 4(K-2) + 8(k-3) + .......+
Question 292

The minimum number of arithmetic operations required to evaluate the


polynomial P(X) = X^5 + 4X^3 + 6X + 5 for a given value of X using only

one temporary variable is .


Solution 292
P(X) = x^5 + 4x^3 +
6x + 5

=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

Let T be a temporary variable to store intermediate

results. 1. T = (x) * (x)


2. T = T + 4
3. T = (x) * (T)
4. T = (x) * (T)
5. T = T + 6
6. T = (x) * T
7. T = T + 5
Question 293

You have an array of n elements. Suppose you implement quicksort by


always choosing the central element of the array as the pivot. Then the

tightest upper bound for the worst case performance is

(A) 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)

Explanation: When first element or last element is chosen as pivot, Quick


Sort‘s worst case occurs for the sorted arrays.

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

Randomized quicksort is an extension of quicksort where the pivot is chosen


randomly. What is the worst case complexity of sorting n numbers

using randomized quicksort?

(A) 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

for the randomised quicksort. And time complexity of worst case of

quicksort is O(n²) that is proven already. So, option (C) is correct.


Question 297

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)

b) n < t (n) < nlog n

c) n log n < t (n) < nC2

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

A sorting technique is called stable if:

A It takes O(nlog n)time

B. It maintains the relative order of occurrence of non-distinct elements

C. It uses divide and conquer paradigm

D. It takes O(n) space


Solution 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

Which of the following sorting algorithms has the lowest


worst-case
complexity
? A
Merge sort
B. Bubble sort
C. Quick sort
D. Selection sort
Solution 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

The correct option is C O(m+n)

The number of comparisons required in the worst case is


0(m + n).
Question 301
Consider the following statements:

I. The smallest element in a max-heap is always at a leaf node

II. The second largest element in a max-heap is always a child of


the root node

III. A max-heap can be constructed from a binary search tree in


Θ(n) time
IV. A binary search tree can be constructed from a max-heap in
Θ(n) time

Which of the above statements are TRUE?

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

The minimum number of comparisons required to find the


minimum and

the maximum of 100 numbers is


Solution 302
Explanation: Steps to find minimum and maximum element out of n numbers:

1. Pick 2 elements(a, b), compare them. (say a > b)

2. Update min by comparing (min, b)

3. Update max by comparing (max, a)


Therefore, we need 3 comparisons for each 2 elements, so total number of
required
comparisons will be (3n)/2 – 2, because we do not need to update min or max
in the very first step.

Recurrence relation will be:

T(n) = T(⌈n/2⌉)+T(⌊n/2⌋)+2 = 2T(n/2)+2 = ⌈3n/2⌉-2

By putting the value n=100, (3*100/2)-2 = 148 which is answer.


Question 303
Consider the following pseudo code. What is the total number of multiplications
to be performed?

D=2
for i = 1 to n do

for j = i to n do

for k = j + 1 to n do D =

D*3

A Half of the product of the 3 consecutive integers.

B.One-third of the product of the 3 consecutive integers.

C.One-sixth of the product of the 3 consecutive integers.


Solution 303
Answer: (C)
Explanation: The statement “D = D * 3” is executed n*(n+1)*(n-1)/6 times. Let us see how.
For i = 1, the multiplication statement is executed (n-1) + (n-2) + .. 2 + 1 times.

For i = 2, the statement is executed (n-2) + (n-3) + .. 2 + 1 times


………………………..
……………………….
For i = n-1, the statement is executed once.
For i = n, the statement is not executed at all

So overall the statement is executed following times


[(n-1) + (n-2) + .. 2 + 1] + [(n-2) + (n-3) + .. 2 + 1] + … +1+0

The above series can be written as


S = [n*(n-1)/2 + (n-1)*(n-2)/2 + … . . + 1]
The sum of above series can be obtained by trick of subtraction the series
from standard Series S1 = n2 + (n-1)2 + .. 12. The sum of this standard
series is n*(n+1)*(2n+1)/6

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.

Multi - Dequeue (Q)

m=k;

while ((Q is not empty) and (m > 0))

Dequeue

(Q); m = m

-1;
}

What is the worst case time complexity of a sequence of n queue operations on an initially empty
queue?

A. Θ(n)
Solution 304

The correct option is A

Θ(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

for worst case when n = k time complexity will be Θ(n)


Question 305

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

(A) O(n log n)

(B) O(n^2 log n)

(C) O(n^2 + log n)

(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

involved will be,

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

comparison takes O(n) time now.


Question 306

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

C. Quicksort using the last element as pivot

D. Merge sort
Solution 306

Answer: (C)

Explanation: Since, given array is almost sorted in ascending


order, so
Insertion sort will give its best case with time complexity of
order O(n).
Question 307

The running time of an algorithm is represented by the


following

recurrence relation:

if n <= 3 then T(n) = n

else T(n) = T(n/3) + cn

Which one of the following represents the time complexity of


the
algorithm?
A B theta(nlogn). C D theta(n^2logn)
theta(n). theta(n^2).
Solution 307
Answer: (A)
Explanation:

T(n) = cn + T(n/3)

= cn + cn/3 + T(n/9)

= cn + cn/3 + cn/9 + T(n/27)

Taking the sum of infinite GP series. The value of T(n) will be less

than this sum.


T(n) <= cn(1/(1-1/3))

<= 3cn/2

or we can say
cn <= T(n) <= 3cn/2

Therefore T(n) = (n)

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

time complexity of the quick sort?

(A) θ(n)

(B) θ(n*log(n))

(C) θ(n^2)

(D) θ(n^2 log n)


Solution 308

Answer: (B)

Explanation:

The recursion expression becomes T(n) = T(n/4) + T(3n/4) + cn

After solving the above recursion, we get θ(n*log(n)).


Question 309
Consider the Quicksort algorithm. Suppose there is a procedure for finding a pivot
element which splits the list into two sub-lists each of which

contains at least one-fifth of the elements. Let T(n) be the number of

comparisons required to sort n elements. Then

(A) T(n) <= 2T(n/5) + n

(B) T(n) <= T(n/5) + T(4n/5) + n

(C) T(n) <= 2T(4n/5) + n

(D) T(n) <= 2T(n/2) + n


Solution 309

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

determined. Which of the following is TRUE about the number of comparisons

needed?

A At least 2n –c comparisons, for some constant c, are needed.

B. At most 1.5n –2 comparisons are needed.

C. At least n log2 n comparisons are needed.

D. None of the above.


Solution 310
Maximum and minimum of an array by comparing in pairs:

If n is odd then initialize min and max as the first element.

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

maximum and minimum with max and min respectively.


Time Complexity: O(n)

Auxiliary Space: O(1) as no extra space was needed.

The total number of comparisons: Different for even and odd n, see below: If n is

odd: 3*(n-1)/2

If n is even: 1 Initial comparison for initializing min and max,


Question 311

Consider the following


recurrence:

Which one of the following is


true?

(A) T(n) = theta(loglogn)

(B) T(n) = theta(logn)

(C) T(n) = theta(sqrt(n))

(D) T(n) = theta(n)


Solution 311
.
Answer: = ………….
(B) 2^kT(n^(1/2k)) + (1)
k
Explanation:
n^(1/2k)
Using the= 2
Base
Background Required – Recurrence Solving using Substitution case,
Method. Taking log on both
Answer – B sides log2n = 2k
Unrolling the
recursion, k = log2log2n
T(n) = From (1),
2T(n^(1/2)) + 1 T(n) = log2n +
= 2^2T(n^(1/4)) log2log2n
+2 = Theta(log2n)
= 2^3T(n^(1/8)) +
Here log2n : log(base
3
2) n
.
. k steps
Question 312

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

complexity of this modified QuickSort.

(A) O(n^2 Logn)

(B) O(n^2)

(C) O(n Logn Logn)

(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

and half in the right.

Thus after partition algorithm the array will be divided into two equal parts of

n/2 elements each.

Hence the resultant recurrence relation would be-


T(n) = O(n) (for selecting median) + O(n) (for partition) + T(n/2) + T(n/2)

T(n) = O(n) + 2T(n/2)


Question 313
Suppose T(n) = 2T (n/2) + n, T(0) = T(1) = 1

Which one of the following is FALSE?

(A) T(n) = O(n2)

(B) T(n) = θ(n log n)

(C) T(n) = Ω(n2)

(D) T(n) = O(n log n)


Solution 313
Question 314

Let T(n) be a function defined by the


recurrence T(n) = 2T(n/2) + √n for n ≥ 2 and
T(1) = 1

Which of the following statements is TRUE?

(A) T(n) = θ(log n)


(B) T(n) = θ(√n)
(C) T(n) = θ(n)
(D) T(n) = θ(n log n)
Solution 314

Answer:
(C)
Explanation: n(logba) = n which is = n^(1-.5) = O(sqrt n)

then by applying case 1 of master method we get T(n) =


Θ(n)
Question 315

Quicksort is run on two inputs shown below to sort in ascending order taking the
first element as pivot,
(i) 1, 2, 3,......., n

(ii) n, n-1, n-2,......, 2, 1

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

(D) We cannot say anything for arbitrary n


Solution 315
Answer: (C)

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

number of comparisons for both given inputs. Option (C) is correct.


Question 316

The recurrence relation that arises in relation with the complexity of


binary

search is:

(A) T(n) = 2T(n/ 2) + k , where k is constant

(B) T(n) = T(n / 2) + k , where k is constant

(C) T(n) = T(n / 2) + log n

(D) T(n) = T(n / 2) + n


Solution 316

Answer: (B)

Explanation: Binary Search is a linear searching algorithm and takes

O(log n) when array is sorted. Refer: Binary Search

T(n) = T(n / 2) + k , where k is constant produces a complexity of O(log


n)
Question 317

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 :

(Hint : Use a heap data structure)

(A) O(n log log n)

(B) θ(n log n)

(C) Ω(n log n)

(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

Find a solution to the following recurrence


equation

T(n) = T(n - 1)+ n

T(1) = 1
Solution 318

T(n) = T(n-1) + n T(n-1) = T(n-2) + n-1 T(n-2) = T(n-3) + n-2

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)

For base case:

n - k = 1 so we can get T(1)

=> k = n - 1
substitute in (1)

T(n) = T(1) + (n-1)n - (n-1)(n-2)/2

Which you can see is of Order n2 => O(n2).


Question 319

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

The algorithm will take maximum time when:


The array is already sorted in same order.(Here,ascending order)

The array is already sorted in reverse order.

All elements are same in the array(Here,we have n distinct

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

Total number of characters in the message = 100.


Each character takes 1 byte. So total number of bits needed = 800.

After Huffman Coding, the characters can be represented with: f: 0


c: 100
d: 101
a: 1100
b: 1101
e: 111
Total number of bits needed = 224
Hence, number of bits saved = 800 - 224 = 576
Question 321

What is the time complexity of Huffman


Coding?
A. O(N)
B. O(NlogN)
C. O(N(logN)^2)
D. O(N^2)
Solution 321

O(nlogn) where n is the number of unique characters. If there are


n nodes, extractMin() is called 2*(n – 1) times. extractMin() takes
O(logn) time as it
calls minHeapify(). So, overall complexity is
O(nlogn).
Question 322

Which of the following is true about Kruskal and Prim MST algorithms? Assume
that Prim is implemented for adjacency list representation using

Binary Heap and Kruskal is implemented using union by rank.

A. Worst case time complexity of both algorithms is same.

B. Worst case time complexity of Kruskal is better than Prim

C. Worst case time complexity of Prim is better than Kruskal

D. None of these
Solution
322

Solution
A
Question 323

You have an array of n elements. Suppose you implement quicksort by


always choosing the central element of the array as the pivot. Then the

tightest upper bound for the worst case performance is

(A) 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)

Explanation: When first element or last element is chosen as pivot, Quick


Sort‘s worst case occurs for the sorted arrays.

In every step of quick sort, numbers are divided as per the following
recurrence.

T(n) = T(n-1) + O(n)


Question 325

Which of the following is true about Huffman Coding.


A. Huffman coding may become lossy in some cases
B. Huffman Codes may not be optimal lossless codes in some cases
C. In Huffman coding, no code is prefix of any other code.
D. All of the above
Solution 325

Huffman coding is a lossless data compression algorithm. The codes


assigned to input characters are Prefix Codes, means the codes are assigned
in such a way that the code assigned to one character is not prefix of code
assigned to any other character. This is how Huffman Coding makes sure
that there is no ambiguity when decoding.

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?

A. 0, 10, 110, 1110, 11110, 11111

B. 11, 10, 011, 010, 001, 000

C. 11, 10, 01, 001, 0001, 0000

D. 110, 100, 010, 000, 001, 111


Solution 326
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
/ \
/ \
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,

1/32, 1/32 respectively. What is the average length of Huffman codes?

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

Consider the undirected graph below:Using Prim's algorithm to construct a


minimum spanning tree starting with node A, which one of the following
sequences of edges represents a possible order in which the edges would be
added to construct the minimum spanning tree?

A. (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

The number of permutations of the characters in LILAC so that no


character appears in its original position, if the two L’s are

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

Consider a graph G=(V, E), where V = { v1,v2,…,v100 }, E={ (vi, vj) ∣


1≤ii,

vj) is ∣i–j∣. The weight of minimum spanning tree of G is


Solution 331
There are 100 vertices numbered from 1 to 100. Edges are presents in this graphs
E={ (vi, vj) ∣ 1≤i1, v2), (v2, v3), ..... (v99, v100) will have minimum weight, i.e., 1
for each edge. As we know that, there are 99 edges are possible in minimum
spanning tree of 100-vertices graph.Therefore, these edges (v1, v2), (v2,
v3), ..... (v99, v100) will be spanning tree for given graph. These are 99 edges
with 1 cost of each. The weight of minimum spanning tree of G is 99*1 = 99.
Option (A) is correct.
Question 332
Define Rn to be the maximum amount earned by cutting a rod of length n meters
into one or more pieces of integer length and selling them. For i>0, let p[i] denote
the selling price of a rod whose length is i meters. Consider the array of prices:
p[1]=1, p[2]=5, p[3]=8, p[4]=9, p[5]=10, p[6]=17, p[7]=18

Which of the following statements is/are correct about R7?

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,

= 1×3 + 2×3 + 3×2 + 2×2 +


2×2

= 23

Correct Option B
Question 334

Which of the following standard algorithms is not a Greedy algorithm?

A. Dijkstra's shortest path algorithm

B. Prim's algorithm

C. Kruskal algorithm

D. Bellman Ford Shortest path algorithm


Solution 334

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

spanning tree of G is: (GATE CS 2006)

(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

Weight of the minimum spanning tree


= 2|2 – 1| + 2|3 – 2| + 2|4 – 3| + 2|5 – 4| … .
+ 2| n – (n-1) |
Question 336

To implement Dijkstra’s shortest path algorithm on unweighted graphs so


that it runs in linear time, the data structure to be used is:
A Queue

B. Stack

C. Heap

D. B-Tree
Solution 336
Answer(A)

The shortest path in an un-weighted graph means the smallest number of

edges that must be traversed in order to reach the destination in the


graph. This is the same problem as solving the weighted version where all
the weights happen to be 1. If we use Queue (FIFO) instead of Priority
Queue (Min Heap), we get the shortest path in linear time O(|V| + |E|).

Basically we do BFS traversal of the graph to get the shortest paths.


Question 337

Let G = (V, G) be a weighted undirected graph and let T be a Minimum Spanning


Tree (MST) of G maintained using adjacency lists. Suppose a
new weighed edge (u, v) ∈ V×V is added to G. The worst case time
complexity of determining if T is still an MST of the resultant graph is

(A) Θ(∣E∣ + ∣V∣)

(B) Θ(∣E∣.∣V∣)

(C) Θ(E∣ log ∣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.

Later we need to check still T is a minimum spanning tree or not, So we need


to check all vertices whether there is any cycle present after adding a new
All vertices need to traverse to confirm minimum spanning tree after adding
edge.
new edge then
time complexity is O(V).
Question 338

Consider the weighted undirected graph with 4 vertices, where the weight of edge {i, j} g is
given by the entry

Wij in the matrix


W

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

Explanation: Let vertices be 0, 1, 2 and 3.

x directly connects 2 to 3. The shortest path (excluding x) from 2 to 3


is

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

CD is 16 and minimum possible weight of AB is 10.

Therefore minimum possible sum of weights is 69


Question 340
A Young tableau is a 2D array of integers increasing from left to right and from top to
bottom. Any unfilled entries are marked with ∞, and hence there cannot be any entry to the
right of, or below a ∞. The following Young tableau consists of unique entries.

1 2 5 14
3 4 6 23
10 12 18 25

31 ∞ ∞ ∞
When an element is removed from a Young tableau, other elements should be moved into
its place so that the resulting table is still a Young tableau (unfilled entries may be filled
in with a ∞). The minimum number of entries (other than 1) to be shifted, to remove 1
from the given Young tableau is
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

Explanation: To merge two lists of size m and n, we need to do m+n-1 comparisons


in worst case. Since we need to merge 2 at a time, the
optimal strategy would be to take smallest size lists first. The reason for picking
smallest two items is to carry minimum items for repetition in merging.

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

The number of distinct minimum spanning trees for the weighted


graph

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

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.
The length of the path from v5 to v6 in the MST of previous question
with n = 10 is
(A) 11
(B) 25
(C) 31
(D) 41
Solution 345
Answer: (C)
Any MST which has more than 5 nodes will have the same distance between v5 and v6 as the basic
structure of all MSTs (with more than 5 nodes) would be following.

(v1) _ (v2) _ (v4) _ (v6) _ . . (more even numbered nodes)


|
(v3)

| (v5)
|
.
.
(more odd numbered nodes)

Distance between v5 and v6 = 3 + 4 + 6 + 8 + 10 = 31


Question 346
Consider a complete undirected graph with vertex set {0, 1, 2, 3, 4}. Entry

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

such that vertex 0 is a leaf node in the tree T?

(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

two 1s in 0th row).


Question 347
Consider a complete undirected graph with vertex set {0, 1, 2, 3, 4}. Entry Wij
in the matrix
W below is the weight of the edge {i, j}.
What is the minimum possible weight of a path P from vertex 1 to vertex 2 in
this graph such that P contains at most 3 edges?

(A) 7
(B) 8
(C) 9
(D) 1
0
Solution 347

Answer (B)
Path: 1 -> 0 -> 4 -
>2
Weight: 1 + 4 + 3
Question 348

Consider the following graph:

Which one of the following is NOT the sequence of edges added to the

minimum spanning tree using Kruskal’s algorithm?


(A) (b,e)(e,f)(a,c)(b,c)(f,g)(c,d)
(B) (b,e)(e,f)(a,c)(f,g)(b,c)(c,d)
(C) (b,e)(a,c)(e,f)(b,c)(f,g)(c,d)
(D) (b,e)(e,f)(b,c)(a,c)(f,g)(c,d)
Solution 348
Answer:(D)

Explanation: In the sequence (b, e) (e, f) (b, c) (a, c) (f, g)


(c, d) given

option D, the edge (a, c) of weight 4 comes after (b, c) of weight 3.


In Kruskal’s Minimum Spanning Tree Algorithm, we first sort all edges, then
consider edges in sorted order, so a higher weight edge
cannot come before a lower weight edge.
Question 349

Dijkstra’s single source shortest path algorithm when run from vertex a
in

the below graph, computes the correct shortest path distance to

(A) only vertex a

(B) only vertices a, e, f, g, h

(C) only vertices a, b, c, d

(D) all the vertices


Answer: (D)
Explanation: Dijkstra’s single source shortest path is not guaranteed to work for graphs with negative weight edges, but it
works for the given
graph.
Let us see…
Let us run the 1st pass
b1
b is minimum, so shortest distance to b is 1.

After 1st pass, distances are


c 3, e -2.
e is minimum, so shortest distance to e is -2

After 2nd pass, distances


are c 3, f 0.
f is minimum, so shortest distance to f is 0

After 3rd pass, distances


are c 3, g 3.
Both are same, let us take g. so shortest distance to g is 3.

After 4th pass, distances


are c 3, h 5
c is minimum, so shortest distance to c is 3

After 5th pass, distances are


h -2
Question 350
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 350

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 351
Consider two strings A = "qpqrr" and B = "pqprqrp". Let x be the length of
the longest common subsequence (not necessarily contiguous) between A
and B and let y be the number of such longest common subsequences

between A and B. Then x + 10y = .


Solution 351
//The LCS is of length 4. There are 3 LCS of length 4 "qprr", "pqrr" and
qpqr A subsequence is a sequence that can be derived from
another sequence by selecting zero or more elements from it, without
changing the order of the
remaining elements. Subsequence need not be contiguous. Since the
length of given strings A = “qpqrr” and B = “pqprqrp” are very small,
we don’t need to build a 5x7 matrix and solve it using dynamic
programming. Rather we can solve it manually just by brute force. We
will first check whether there exist a subsequence of length 5 since
min_length(A,B) = 5. Since there is no subsequence , we will now
Question 352

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

We have many ways to do matrix chain multiplication because matrix multiplication is


associative. In other words, no matter how we parenthesize the product, the result of
the matrix chain multiplication obtained will remain the same. Here we have four
matrices A1, A2, A3, and A4, we would have: ((A1A2)A3)A4 = ((A1(A2A3))A4) = (A1A2)
(A3A4) = A1((A2A3)A4) = A1(A2(A3A4)). However, the
order in which we parenthesize the product affects the number of simple arithmetic
operations
needed to compute the product, or the efficiency. Here, A1 is a 10 × 5 matrix, A2 is a 5
x 20 matrix, and A3 is a 20 x 10 matrix, and A4 is 10 x 5. If we multiply two matrices
A and B of order l x m and m x n respectively,then the number of scalar
multiplications in the multiplication of A and B will be

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

Let G (V, E) be a directed graph, where V = {1, 2, 3, 4, 5} is the set of


vertices and E is the set of directed edges, as defined by the following
adjacency matrix A.

A[i][j] = 1 indicates a directed edge from node i to node j. A directed spanning


tree of G, rooted at r ∈ V, is defined as a subgraph T of G such that the
undirected version of T is a tree, and T contains a directed path from r to
every other vertex in V. The number of such directed spanning trees rooted
at vertex 5 is .
Solution 354

According to given adjacency matrix, the


graph will be as following

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

The Floyd-Warshall algorithm for all-pair shortest paths computation is

based on:

(A) Greedy paradigm.

(B) Divide-and-Conquer paradigm.

(C) Dynamic Programming paradigm.

(D)neither Greedy nor Divide-and-Conquer nor Dynamic Programming

paradigm.
Solution 355
Answer: (C)

Explanation: Floyd Warshall Algorithm is a Dynamic Programming based algorithm. It finds


all pairs shortest paths using following recursive nature of problem.
For every pair (i, j) of source and destination vertices respectively, there are two possible
cases.
1)k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i]
[j] as it is.
2)k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j]
as dist[i][k] + dist[k][j].
The following figure is taken from the Cormen book. It shows the above optimal
substructure property in the all-pairs
shortest path problem.
Question 356
List-
IA. Prim’s algorithm for minimum spanning tree

B. Floyd-Warshall algorithm for all pairs


shortest paths
C. Mergesort
D. Hamiltonian circuit
List-II
1. Backtracking
2. Greed method
3. Dynamic programming
4. Divide and conquer
Codes:
ABC
D (a) 3 2
41
(b) 1 2 4 3
(c) 2 3 4 1
Solution 356

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.

Floyd-Warshall algorithm for all pairs shortest paths is a Dynamic Programming


algorithm where we keep updating the distance matrix in bottom up manner.

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.

Which of the following statements is TRUE?


(A)The algorithm uses dynamic programming paradigm
(B)The algorithm has a linear complexity and uses branch and bound
paradigm
(C)The algorithm has a non-linear polynomial complexity and uses branch
and bound paradigm
(D)The algorithm uses divide and conquer paradigm.
Solution 357

Answer: (A)
Question 358

The tightest lower bound on the number of comparisons, in the


worst

case, for comparison-based sorting is of the order of

(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,

2^f(N) >= N! or equivalently f(N) >= log(N!).


Question 359

Which one of the following algorithm design techniques is used in


finding

all pairs of shortest distances in a graph?

(A) Dynamic programming

(B) Backtracking

(C) Greedy

(D) Divide and Conquer


Solution 359

Answer: (A)

Explanation: Floyd Warshall Algorithm is the All Pairs Shortest Path


problem which uses Dynamic Programming to find shortest distances
between every pair of vertices in a given edge weighted directed Graph.
Option (A) is correct.
Question 360
Consider the following undirected graph with edge weights
as shown:

The number of minimum-weight spanning trees of the


graph is
.
Solution 360

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.

Hence, number of spanning trees are 3.


Question 361

Let G=(V,E) be an undirected unweighted connected graph. The diameter of G is


defined as:

Let M be the adjacency matrix of G.


Define graph G2 on the same set of vertices with adjacency matrix N, where

Which one of the following statements is true?


(A) diam(G2)≤⌈ diam(G)/2⌉
(B) ⌈ diam(G)/2⌉2)< diam(G)
(C) diam(G2) = diam(G)
(D) diam(G)< diam(G2)≤2 diam(G)
Solution 361
Answer: (A)

Explanation:

M2 will be the adjacency matrix of the graph H derived from G as follow: H(a,b)

= 1 iff (there exists a vertex c st. G(a,c) = 1 and G(c,b) = 1)

So basically there is an edge between a,b if there is some vertex c st. there

is an edge (a,c) and an edge (c,b) in G.


When we do G𝖴H in the resulting graph diameter reduces to 0.5 of the

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

(A) F1F2 and F3F4 only


(B) F2F3 only
(C) F3F4 only
(D) F1F2 and F4F5 only
Solution 362
Answer: (C)

Explanation: Matrix F5 is of dimension 1 X 1000, which is going to cause very


much multiplication cost. So evaluating F5 at last is optimal.

Total number of scalar multiplications are 48 + 75 + 50 + 2000 = 2173 and


optimal parenthesis is ((F1(F2(F3 F4)))F5).

As concluded, F3, F4 are explicitly computed pairs.


Question 363

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)

Explanation: It is basically matrix chain multiplication problem. We get


minimum number of multiplications using ((M1 X (M2 X M3)) X M4).

Total number of multiplications = 100x20x5 (for M2 x M3) + 10x100x5


+ 10x5x80 = 19000.
Question 364

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

The subset-sum problem is defined as follows. Given a set of n positive integers, S


=
{a1 ,a2 ,a3 ,…,an} and positive integer W, is there a subset of S whose elements
sum
to W? A dynamic program for solving this problem uses a 2-dimensional Boolean
array X, with n rows and W+1 columns. X[i, j],1 <= i <= n, 0 <= j <= W, is TRUE
if and only if there is a subset of {a1 ,a2 ,...,ai} whose elements sum to j. Which
of the following is valid for 2 <= i <= n and ai <= j <= W?
(A) X[i, j] = X[i – 1, j] V X[i, j -ai]
(B) X[i, j] = X[i – 1, j] V X[i – 1, j – ai]
(C) X[i, j] = X[i – 1, j] V X[i, j – ai]
(D) X[i, j] = X[i – 1, j] V X[i -1, j – ai]
Solution 365

Answer (B)

X[I, j] (2 <= i <= n and ai <= j <= W), is true if any of the following is

true 1) Sum of weights excluding ai is equal to j, i.e., if X[i-1, j] is true. 2)

Sum of weights including ai is equal to j, i.e., if X[i-1, j-ai] is true so that

we get (j – ai) + ai as j
Question 366

In previous question, which entry of the array X, if TRUE, implies that

there is a subset whose elements sum to W?

(A) X[1, W]

(B) X[n ,0]

(C) X[n, W]

(D) X[n -1, n]


Solution 366

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. }

On which of the following contents of Y and x does the

program fail? (A) Y is [1 2 3 4 5 6 7 8 9 10] and x < 10


(B) Y is [1 3 5 7 9 11 13 15 17 19] and x < 1
(C) Y is [2 2 2 2 2 2 2 2 2 2] and x > 2
(D) Y is [2 4 6 8 10 12 14 16 18 20] and 2 < x < 20 and x is even
Solution 367

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

if(Y[k] == x) printf ("x is in the array

") ; else printf (" x is not in the array


Question 369
A binary search tree is generated by inserting in order the following

integers:

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

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

respectively is
(A) (4, 7)

(B) (7, 4)

(C) (8, 3)

(D) (3, 8)
Solution 369

Solution B
Question 370

How many passes does an insertion sort algorithm consist of?


a) N
b) N-1
c) N+1
d) N2
Solution 370

Answer: b
Explanation: An insertion algorithm consists of N-1 passes when an array of N
elements is given.
Question 371

Which of the following algorithm implementations is similar to that of an


insertion sort?
a)Binary heap
b)Quick sort
c)Merge sort
d)Radix sort
Solution 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

What is the average case running time of an insertion sort algorithm?


a) O(N)
b) O(N log N)
c) O(log N)
d) O(N2)
Solution 372

Answer: d
Explanation: The average case analysis of a tight bound algorithm is mathematically achieved
to be O(N2).
Question 373

What is the average number of inversions in an array of N distinct


numbers?
a) N(N-1)/4
b) N(N+1)/2
c) N(N-1)/2
d) N(N-1)/3
Solution 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

What will be the number of passes to sort the elements using


insertion sort? 14, 12,16, 6, 3, 10
a)6
b)5
c)7
d)1
Solution 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

Which of the following real time examples is based on insertion sort?


a)arranging a pack of playing cards
b)database scenarios and distributes scenarios
c)arranging books on a library shelf
d)real-time systems
Solution 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

What is the time complexity of Dijikstra’s algorithm?


a) O(N)
b) O(N3)
c) O(N2)
d)O(log
N)
Solution 385
Answer: c
Explanation: Time complexity of Dijkstra’s algorithm is O(N2) because of the use of doubly
nested for loops. It depends on how the table is manipulated.
Question 386

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)

What happens when “While Q != 0” is changed to “while Q>1”?


a) While loop gets executed for v times
b) While loop gets executed for v-1 times
c) While loop gets executed only once
d) While loop does not get executed
Solution 388

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.

If b is the source vertex, what is the minimum cost to reach f vertex?

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

Dijkstra’s Algorithm is the prime example for


a) Greedy algorithm
b) Branch and bound
c) Back tracking
d) Dynamic programming
Solution 391
Answer: a
Explanation: Dijkstra’s Algorithm is the prime example for greedy algorithms because greedy
algorithms generally solve a problem in stages by doing what appears to be the best thing at
each stage.
Question 392

Bellmann ford algorithm provides solution for problems.


a) All pair shortest path
b) Sorting
c) Network flow
d) Single source shortest path
Solution 392

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

What is the running time of Bellmann Ford Algorithm?


a) O(V)
b) O(V2)
c) O(ElogV)
d) O(VE)
Solution 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

A graph is said to have a negative weight cycle when?


a) The graph has 1 negative weighted edge
b) The graph has a cycle
c) The total weight of the graph is negative
d) The graph has 1 or more negative weighted edges
Solution 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

Bellmann Ford Algorithm is an example for


a)Dynamic Programming
b)Greedy Algorithms
c)Linear Programming
d)Branch and Bound
Solution 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

Which of the following is/are property/properties of a dynamic programming problem?


a) Optimal substructure
b) Overlapping subproblems
c) Greedy approach
d) Both optimal substructure and overlapping subproblems
Solution 399

Answer: d
Explanation: A problem that can be solved using dynamic programming possesses
overlapping subproblems as well as optimal substructure properties.
Question 400

If an optimal solution can be created for a problem by constructing optimal


solutions for its subproblems, the problem possesses_______property.
a) Overlapping subproblems
b) Optimal substructure
c) Memoization
d) Greedy
Solution 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: c Explanation: None.


Question 402

Which of the following is not an advantage of Fibonacci Search?


a) When the element being searched for has a non uniform access storage
b) Can be used in magnetic tapes
c) Can be used for large arrays which do not fit in the CPU cache or in the RAM
d)It can be applied efficiently on unsorted
arrays
Solution 402

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

What is the advantage of recursive approach than an iterative approach?


a) Consumes less memory
b) Less code and easy to implement
c) Consumes more memory
d) More code has to be written
Solution 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

What is the worst case complexity of binary search using recursion?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2
Solution 405

Answer: b
Explanation: Using the divide and conquer master theorem.
Question 406

Which of the following is not an application of binary search?


a)To find the lower/upper bound in an ordered sequence
b)Union of intervals
c)Debugging
d)To search in unordered list
Solution 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

Binary Search can be categorized into which of the following?


a) Brute Force technique
b) Divide and conquer
c) Greedy algorithm
d) Dynamic programming
Solution 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

What is the time complexity of binary search with iteration?


a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
Solution 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

Which of the following is NOT a rule of tower of hanoi puzzle?


a) No disk should be placed over a smaller disk
b) Disk can only be moved if it is the uppermost disk of the stack
c) No disk should be placed over a larger disk
d) Only one disk can be moved at a time
Solution 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

Recurrence equation formed for the tower of hanoi problem is given


by_______
a) T(n) = 2T(n-1)+n
b) T(n) = 2T(n/2)+c
c) T(n) = 2T(n-1)+c
d) T(n) = 2T(n/2)+n
Solution 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

Fractional knapsack problem is solved most efficiently by which of the


following algorithm?
a)Divide and conquer
b)Dynamic programming
c)Greedy algorithm
d)Backtrack
ing
Solution 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

What is the objective of the knapsack problem?


a) To get maximum total value in the knapsack
b) To get minimum total value in the knapsack
c) To get maximum weight in the knapsack
d) To get minimum weight in the knapsack
Solution
421
Answer: a
Explanation: The objective is to fill the knapsack of some given volume
with different materials such that the value of selected items is
maximized.
Question 422

How many printable characters does the ASCII


character set consists of?
a) 120
b) 128
c) 100
d) 98
Solution 422

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

In Huffman coding, data in a tree always occur?


a) roots
b) leaves
c) left sub trees
d) right sub trees
Solution 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

In a full binary tree if there are L leaves, then total number of


nodes N are?
a) N = 2*L
b) N = L + 1
c) N = L – 1
d) N = 2*L – 1
Solution 424

Answer: d
Explanation: The relation between number of nodes(N) and
leaves(L) is N=2*L-1.
Question 425

Which of the following methods can be used to solve the longest


palindromic subsequence problem?
a)Dynamic programming
b)Recursion
c)Brute force
d)Dynamic programming,
Recursion, Brute force
Solution 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

When a top-down approach of dynamic programming is applied to a problem, it


usually _______
a) Decreases both, the time complexity and the space complexity
b) Decreases the time complexity and increases the space complexity
c) Increases the time complexity and decreases the space complexity
d) Increases both, the time complexity and the space complexity
Solution 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

Which of the following problems is NOT solved using dynamic programming?


a) 0/1 knapsack problem
b) Matrix chain multiplication problem
c) Edit distance problem
d) Fractional knapsack problem
Solution 428

Answer: d
Explanation: The fractional knapsack problem is solved using a greedy
algorithm
Question 429

Which of the following problems should be solved using dynamic


programming?
a)Mergesort
b)Binary search
c)Longest common subsequence
d)Quicksort
Solution 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

Floyd Warshall’s Algorithm can be applied on


a) Undirected and unweighted graphs
b) Undirected graphs
c) Directed graphs
d) Acyclic graphs
Solution 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

What is the output of 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) 10
b) 1
c) 10 9 8 … 1 0
d) 10 9 8 … 1
Solution 432

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

What does the following recursive


code do? void
my_recursive_function(int n)
{ if(n ==
0) return;
my_recursive_function(n
-1); printf("%d ",n);
}
int main()
{ my_recursive_function(
10); return 0;
}
a) Prints the numbers from 10 to 1
b) Prints the numbers from 10 to 0
c) Prints the numbers from 1 to 10
d) Prints the numbers from 0 to 10
Solution 435

Answer: c
Explanation: The above code prints the numbers from 1 to 10.
Question 436

What is the advantage of selection sort over other sorting techniques?


a) It requires no additional storage space
b) It is scalable
c) It works best for inputs which are already sorted
d) It is faster than any other sorting technique
Solution 436

Answer: a
Explanation: Since selection sort is an in-place sorting algorithm, it does
not require additional storage.
Question 437

The given array is arr = {3,4,5,2,1}. The number of iterations in


bubble sort and selection sort respectively are _
a)5 and 4
b)4 and 5
c)2 and 4
d)2 and 5
Solution 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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy