You are on page 1of 1877

GATE

Overflow Book
April 2016

GATE Overflow

Copyright GATE Overflow. All rights reserved.

April 2016

1 of 1876

GATE Overflow

April 2016

This book was created programatically by GATE


Overflow on Apr 30, 2016. If you feel any doubt
regarding the answer, click on the question link
and give a comment on the site. Studying all
these questions might get you 60 marks in GATE
but that might not be enough for an IIT. So, read
standard books, solve exercise questions and use
these questions for cementing the concepts and
aim 75+. At least if you are not getting solution
to a given problem first refer standard book. If
any error is found on any question it shall be
updated
at http://gateoverflow.in/corrections.
Also please update the book on next release
which will be with in 3 months as more questions
are being added and many corrections going on.

Copyright GATE Overflow. All rights reserved.

2 of 1876

GATE Overflow

April 2016

GATE Overflow was started just a year ago and


a lot of people have dedicated their time and
effort in bringing this book now. Initiated by
Omesh Pandita and Arjun Suresh as a Q/A
platform for CSE students, Kathleen was
instrumental in geting all previous year GATE
questions here. Then experts like Praven Saini,
Happy Mittal, Sankaranarayanan, Suraj etc.
have contributed a lot to the answers here.
Pragy Agarwal even after topping GATE has
continuously contributed here with his knowledge
as well as in making the contents beautiful with
fine latex skills. We also have to thank the work
by Jothee, Misbah, Ishrat and Nataliyah who
are continuously adding and keeping the
contents here neat and clean. There are also
many toppers of GATE 2015 and probable ones
of GATE 2016 who are contributing a lot here.
The list of all the contributors can be found here
but even that do not include the contributions of
some like Arif Ali in helping design this book,
Arvind Devaraj and others who have provided
guidance and help etc. Last but not the least, we
thank all the users of GATE Overflow.

Copyright GATE Overflow. All rights reserved.

3 of 1876

GATE Overflow

Table of Contents
Algorithms
Ambiguous
Arrays
Asymptotic Notations
Binary Heap
Binary Search
Binary Tree
Connected Components
Decidability
Dfs
Distance Vector Routing
Dynamic Programming
Expectation
Grammar
Graph Algorithms
Graph Search
Greedy Algorithm
Hashing
Heap
Huffman Code
Identify Function
Insertion Sort
Lines Curves
Linked Lists
Loop Invariants
Matrix Chain Ordering
Median
Merge Sort
Minimum
Minimum Spanning Trees
P Np Npc Nph
Programming In C
Quicksort
Radix Sort
Recurrence
Recursion
Reduction
Runtime Environments
Shortest Path
Sorting
Space Complexity
Spanning Tree
Test Cases
Time Complexity
Topological Sort
Transactions
Trees
Compiler Design
Assembler
Code Optimization
Context Free
Dag Representation
Grammar
Intermediate Code
Lexical Analysis
Linking
Live Variable
Macros
Parameter Passing
Parsing
Postfix
Programming In C
Recursion
Register Allocation
Runtime Environments
Static Single Assignment
Syntax Directed Translation
Target Code Generation
CO & Architecture
Addressing Modes
Cache
Cache Memory
Computer Organization

Copyright GATE Overflow. All rights reserved.

April 2016

4 of 1876

GATE Overflow
Data Dependencies
Data Path
Dma
Hardwired Controller
Instruction Format
Interrupts
Io Handling
Io Organization
Machine Instructions
Memory Interfacing
Microprogramming
Page Fault
Pipeline
Virtual Memory
Writeback
Operating System
Ambiguous
Cache Memory
Computer Organization
Computer Peripherals
Concurrency
Context Switch
Dining Philosopher
Disk
Disk Scheduling
Dma
File
File System
Fork
Interrupts
Io Handling
Linking
Memory Allocation
Memory Management
Page Replacement
Process Schedule
Process Synchronization
Resource Allocation
Semaphore
Shell Script
Threads
User Modes
Virtual Memory
Working Set
Databases
B Tree
Concurrency
Database Normalization
Er Diagram
Er Model
Functional Dependencies
Indexing
Multivalued Dependency 4nf
Natural Join
Referential Integrity
Relational Algebra
Relational Calculus
Sql
Transactions
Theory of Computation
Chomsky Normal Form
Closure Property
Context Free
Decidability
Dfa
Finite Automata
Identify Class Language
Minimal State Automata
Myhill Nerode
Pda
Pumping Lemma
Recursive Recursively Enumerable
Regular Expressions
Regular Set
Turing Machine
Computer Networks

Copyright GATE Overflow. All rights reserved.

April 2016

5 of 1876

GATE Overflow
Application Layer Protocols
Bit Stuffing
Bridges
Communication
Congestion Control
Crc Polynomial
Cryptography
Csma Cd
Distance Vector Routing
Encoding
Error Detection
Ethernet
Firewall
Hamming Code
Icmp
Ip Packet
Ipv4
Lan Technologies
Link State Routing
Mac Protocol
Manchester Encoding
Network Flow
Network Layering
Network Protocols
Network Security
Network Switching
Osi Protocol
Routers Bridge Hubs Switches
Routing
Selective Repeat
Serial Communication
Sliding Window
Sockets
Stop And Wait
Subnetting
Tcp
Token Bucket
Udp
Wifi
Digital Logic
Adder
Boolean Algebra
Boolean Expressions
Booths Algorithm
Booths Coding
Canonical Normal Form
Circuit Output
Counter
Flip Flop
Floating Point Representation
Functional Completeness
Gray Code
Half Adder
Ieee Representation
K Map
Logic
Memory Interfacing
Min No Gates
Min Sum Of Products Form
Minimal State Automata
Modular Arithmetic
Multiplexer
Multiplexor
Number Representation
Priority Encoder
Ram
Verbal Ability
Bayes Theorem
Closest Word
English Grammar
Grammatically Incorrect Sentence
Inference
Logical Reasoning
Meaning
Most Appropriate Alternative
Most Appropriate Word

Copyright GATE Overflow. All rights reserved.

April 2016

6 of 1876

GATE Overflow
Number Series
Odd One
Opposite
Passage Reading
Tense
Verbal Reasoning
Word Pairs
Numerical Ability
Bar Charts
Bayes Theorem
Circle
Clock Time
Complex Number
Conditional Probability
Convergence
Cost Market Price
Counting
Data Interpretation
Directions
Distance Time
First Order Logic
Fraction
Functions
Geometry
Growth Rate
Inference
Logical Reasoning
Mean
Modular Arithmetic
Most Appropriate Word
Number Representation
Number Series
Numerical Methods
Odd One
Passage Reading
Percent
Pie Chart
Polynomials
Probability
Proportions
Quadratic Equations
Ratios
Sequence
Sets
Speed
Statistics
System Of Equations
Mathematical Logic
Boolean Expressions
Canonical Normal Form
Differentiability
First Order Logic
Logical Reasoning
Probability
Bayes Theorem
Binomial Distribution
Conditional Probability
Expectation
Exponential Distribution
Greedy Algorithm
Independent Events
Normal Distribution
Poisson Distribution
Probability
Random Variable
Statistics
Uniform Distribution
Set Theory & Algebra
Boolean Algebra
Boolean Expressions
Countable Uncountable Set
Counting
Functions
Generating Functions
Groups
Injective Functions

Copyright GATE Overflow. All rights reserved.

April 2016

7 of 1876

GATE Overflow
Lattice
Lines Curves
Number Series
Partial Order
Pigeonhole
Polynomials
Recurrence
Relations
Ring
Sequence
Sets
Time Complexity
Combinatory
Binary Tree
Combinations
Combinatorics
Counting
Generating Functions
Number Theory
Permutation
Pigeonhole
Recurrence
Graph Theory
Chromatic Number
Combinatorics
Connected Components
Cutvertices&edges
Degree Sequence
Graph Coloring
Graph Connectivity
Graph Isomorphism
Graph Matching
Groups
Permutation
Spanning Tree
Linear Algebra
Cayley Hamilton Theorem
Eigen Value
Matrices
System Of Equations
Vector Space
Calculus
Continuity
Convergence
Counting
Differentiability
Integration
Limits
Maxima Minima
Programming
Activation Records
Arrays
Concurrency
Loop Invariants
Parameter Passing
Pointers
Post Condition
Programming In C
Programming Paradigms
Recursion
Runtime Environments
Stack
Variable Binding
DS
Arrays
Avl Tree
B Tree
Bfs
Binary Heap
Binary Search
Binary Search Tree
Binary Tree
Counting
Graph Algorithms
Hashing
Heap

Copyright GATE Overflow. All rights reserved.

April 2016

8 of 1876

GATE Overflow
Infix Postfix
Linked Lists
Queues
Spanning Tree
Stack
Tree Traversal
Trees
IISc/IITs
NITs
IIITs
Other Colleges
Study Resources
GATE Application
Written Exam

Copyright GATE Overflow. All rights reserved.

April 2016

9 of 1876

GATE Overflow

April 2016

10 of 1876

Algorithms top

1.1 Ambiguous: GATE 2016-2-13 top

gateoverflow.in/39561

Assume that the algorithms considered here sort the input sequences in ascending order. If the input is already in the
ascending order, which of the following are TRUE?
I. Quicksort runs in (n2 ) time
II. Bubblesort runs in (n2 ) 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

gate2016-2

algorithms

sorting

time-complexity

normal

ambiguous

Q = Q can be used instead of Theta


I) Quicksort takes Q(N2) in case of already sorted input. This is true
II) This is false. If no swap happens then bubble sort can stop in single loop. Q(N) is best case. This is false !
iii) Mergesort never takes more than Q(NlogN) This is false
IV) This is true. Insertion sort will finish in Q(N) time in case of sorted input.
Answer D) I and IV

Proof Bubble sort has best case O(N) =>
Ref -> https://en.wikipedia.org/wiki/Bubble_sort, Aduni lecture
Following Photo from Art of Computer Programming , Sorting and Searching (Volume 3)

Now quicksort taking O(N) can happen in some cases but not all cases, so that is why I) should

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

11 of 1876

be considered true. WHereas Bubble sort time complexity in best case is always O(N) . So D is
any time stronger answer than C


-- Akash ( 26265 points)

7 votes

1.2 Arrays: GATE1994_25 top

gateoverflow.in/2521

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

algorithms

arrays

normal

Selected Answer

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


-- ankitrokdeonsns ( 7941 points)

8 votes

our works become simpler when we read the word its in increasing order...keep on adding the 2 consecutive numbers
case 1:the sum is less than given element then continue
case 2:the sum is greater than given element then terminate and return -1
case 3:the sum is equal to given element then terminate and return the position of i and j
-- Bhagirathi Nayak ( 10239 points)

1 votes

1.3 Arrays: TIFR2011-B-30 top

gateoverflow.in/20611

Consider an array A[1...n]. It consists of a permutation of numbers 1....n. Now compute another array B[1...n] as follows:
B[A[i]]:= i for all i. Which of the following is true?
a. B will be a sorted array.
b. B is a permutation of array A.
c. Doing the same transformation twice will not give the same array.
d. B is not a permutation of array A.
e. None of the above.
tifr2011

algorithms

arrays

Selected Answer

Option b) B is a permutation of array A.


Infact, B gives the reverse index of all the elements of array A. Since the array A contains numbers [1. . n] mapped to the
locations [1. . n] and A is a permutation of the numbers [1. . n], the array B will also be a permutation of the numbers [1. . n].
For example:

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

12 of 1876

index

To see that option c is incorrect, let array C be the array attained from doing the same transformation twice, that is,
C[B[i]] = i, i [1. . n]. We get,
index

We can see that C = A, which makes option c incorrect.


-- Pragy Agarwal ( 13675 points)

4 votes

1.4 Arrays: GATE1997_17 top

gateoverflow.in/2277

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


gate1997

algorithms

arrays

normal

1.5 Arrays: GATE1993_12 top

gateoverflow.in/2309

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


gate1993

algorithms

arrays

normal

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

13 of 1876

We have to traverse all elements in array. The code is doing this row wise.
begin
max:=A[0,0], i:=0, j:=0;
while (i < n) do
begin
if A[i, j]>max then max:=A[i, j];
if (j < n) then j:=j+1;
else begin
j:=0;
i:=i++;
end
end
end


-- Arjun Suresh ( 124085 points)

2 votes

1.6 Asymptotic Notations: GATE2015-3_42 top

gateoverflow.in/8501

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

algorithms

asymptotic-notations

normal

Selected Answer

The answer is option D.


Since the value of sin(n) will always range from -1 to +1, hence g(n) can take values 1, n, n^2.
Hence, if g(n) = 1, Statement I is incorrect.
And, if g(n) = n^2, then Statement II is incorrect.
10 votes

-- saurabhrk ( 1273 points)

Answer is D.
Take different values for sinn -0,90,180,270,360 . You will find out that for 0,90 f(n)>g(n) and hence f(n)=omega(g(n))
and at 180,270 g(n) is greater therefor f(n) < g(n) i.e f(n)=Big-oh(g(n)) .therefore nothing is possible
1 votes

-- Gate Sanyasi ( 27 points)

Answer is D.
1 votes

1.7 Asymptotic Notations: GATE2000_2.17 top


Consider the following functions

Copyright GATE Overflow. All rights reserved.

-- ppm ( 549 points)

gateoverflow.in/664

GATE Overflow

April 2016

14 of 1876

f(n) = 3nn
g(n) = 2nlog2 n
h(n) = n!
Which of the following is true?
a. h(n) is O(f(n))
b. h(n) is O(g(n))
c. g(n) is not O(f(n))
d. f(n) is O(g(n))


gate2000

algorithms

asymptotic-notations

normal

Selected Answer


f(n) = 3nn

g(n) = 2nlog2 n

h(n) = n!

n = 256

n = 65536
3 65536256

3 25616

= 3 216256

= 3 2128

= 3 24096

2168

2256 16

= 2128

= 24096

256!

65536!

=O

(( ) ) ((
28

256

= O 22048

=O

216

65536

( )

= O 21M


Case of h(n) is given only by an upper bound but factorial has higher growth rate than exponential.
http://math.stackexchange.com/questions/351815/do-factorials-really-grow-faster-than-exponential-functions
f(n) and g(n) are having same order of growth as f(n) is simply 3 g(n) (we can prove this by taking log also). So, (d) is
correct and all other choices are false.
-- Arjun Suresh ( 124085 points)

7 votes

1.8 Asymptotic Notations: GATE1999_2.21 top


If T1 = O(1), give the correct matching for the following pairs:


(A) M-W N-V O-U P-X

Copyright GATE Overflow. All rights reserved.

(M) Tn = Tn 1 + n
(N) Tn = Tn / 2 + n

(U) Tn = O(n)

(O) Tn = Tn / 2 + nlogn

(W) T = O(n2 )

(P) Tn = Tn 1 + logn

(X) Tn = O(log2 n)

(V) Tn = O(nlogn)

gateoverflow.in/1498

GATE Overflow

April 2016

15 of 1876

(B) M-W N-U O-X P-V


(C) M-V N-W O-X P-U
(D) M-W N-U O-V P-X
gate1999

algorithms

recurrence

asymptotic-notations

normal

Selected Answer

n (n +1 )

(M) T(n) = Sum of first n natural numbers =

= O(n2 )

(N) T(n) = (n) = O(n), third case of Master theorem

(nlogb a +)

(nlog2 1 +)

(f(n) = n =
=
for any c between 0 and 0.5)

(n0 +),

satisfied for any positive 1. Also, af( ) < cf(n)  f( ) < cf(n)  2 < cn, satisfied

(O) T(n) = (nlogn) = O(nlogn), third case of Master theorem


n

(f(n) = nlogn = (nlogb a +) = (nlog2 1 +) = (n0.5+), satisfied for positive = 0.5. Also, af( b ) < cf(n)  f( 2 ) < cf(n)  2 log 2 < cnlogn,
satisfied for c = 0.5)
(P) Like in (M), here we are adding the log of the first n natural numbers. So,
Tn = log1 + log2 + log3 + . . . . logn
= log(1 2 n)
= log(n!)
= nlogn n + 1 (Stirling's Approximation)
= O(nlogn)
-- Arjun Suresh ( 124085 points)

5 votes

M-W, N-U and Both O and P will have V..I guess wrong choices!
-- Shaun Patel ( 5445 points)

3 votes

1.9 Asymptotic Notations: GATE2015-3_4 top


Consider the equality n(i =0 ) i3 = X and the following choices for X
I. (n4 )
II. (n5 )
III. O(n5 )
IV. (n3 )
The equality above remains correct if X is replaced 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
gate2015-3

algorithms

asymptotic-notations

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/8398

GATE Overflow

April 2016

16 of 1876

Sum of the cubes of the first n 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 choice.
-- Arjun Suresh ( 124085 points)

11 votes

Sum of th e cubes of the first n natural numbers is given by (n(n+1)/2)^2 which is (n^4) . So I,III and IV are correct.

So correct choice is C.
-- Raghuveer Dhakad ( 849 points)

1 votes

1.10 Asymptotic Notations: GATE2001_1.16 top

gateoverflow.in/709

Let f(n) = n2 logn and g(n) = n(logn)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))
gate2001

algorithms

asymptotic-notations

time-complexity

normal

Selected Answer

f(n)

g(n)

n = 210

10 * 210 * 210

210 * 10 10

n = 2256

256 * 2 256 * 2256

2256 * 256 10

So, as n is going larger, f(n) is overtaking g(n) and the growth rate of f is faster than that of g. So, g(n) = O(f(n)) and
f(n) O(g(n)).
B choice.
-- Arjun Suresh ( 124085 points)

9 votes

1.11 Asymptotic Notations: GATE2003_20 top


Consider the following three claims
I. (n + k)m = (nm) where k and m are constants
II. 2n +1 = O(2n )
III. 22n +1 = O(2n )
Which of the following claims are correct
A. I and II
B. I and III
C. II and III
D. I, II, and III

gate2003

algorithms

asymptotic-notations

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/910

GATE Overflow

April 2016

17 of 1876

Selected Answer

1) Clearly rate of growth of (n + k)m = nm as k and m are constants


so TRUE

( )

2) 2n +1 = 2 (2n ) = 2n as 2 is a constant here

( )

As 2n +1 is both upper and lower bounded by 2n we can say 2n +1 = O 2n


so TRUE
3) 22n +1 has same rate of growth as 22n
2
22n = 2n

2n is upper bounded by (2n )2 , not the other way round


so FALSE
-- Danish ( 1967 points)

5 votes

1.12 Asymptotic Notations: GATE2004_29 top

gateoverflow.in/1026

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) n2
(c) nlogn
(d) nlog2 n
gate2004

algorithms

sorting

asymptotic-notations

easy

Selected Answer

For comparison-based sorting the asymptotically tight bound for worst case is given by (logn), which means it is the
tightest upper bound (big O) as well as the tightest lower bound (big omega). So, answer is nlogn.
Tightest lower bound of sorting (say S(n)) is nlogn means there is no function f which has an order of growth larger than
nlogn and f(n) = (S(n)) holds.
A usual mistake is to think worst case changes with lower and upper bounds, but that is not the case. Worst case is
defined for the algorithm and it is always the input which causes the algorithm the maximum complexity.
-- Arjun Suresh ( 124085 points)

7 votes

1.13 Asymptotic Notations: GATE2004-IT_55 top


Let f(n), g(n) and h(n) be functions defined for positive inter such that
f(n) = O(g(n)), g(n) O(f(n)), g(n) = O(h(n)), and h(n) = O(g(n)).
Which one of the following statements is FALSE?

A)
B)
C)
D)
gate2004-it

f(n) + g(n) = O(h(n)) + h(n))


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

algorithms

asymptotic-notations

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/3698

GATE Overflow

April 2016

18 of 1876

f(n)=O(h(n)) using transitivity


h(n)=f(n)
f(n) g(n)=O(g(n) h(n) is true
So d is false
-- Pooja ( 22745 points)

2 votes

Answer is (D)
We can verify as : f<=g BUT g!<=f . Therefore f<g
Also g=h as g=O(h) and h=O(g)
-- Sandeep_Uniyal ( 5063 points)

2 votes

I think option a is mis printed And option d is false


-- Bhagirathi Nayak ( 10239 points)

2 votes

1.14 Asymptotic Notations: GATE2008-IT_10 top

gateoverflow.in/3270

Arrange the following functions in increasing asymptotic order:


A. n1/3
B. en
C. n7/4
D. n log9n
E. 1.0000001n

A)
B)
C)
D)
gate2008-it

A, D, C, E, B
D, A, C, E, B
A, C, D, E, B
A, C, D, B, E

algorithms

asymptotic-notations

normal

Selected Answer

A < C and A < D


E < B
and
C, D < E as E is exponential function.
Now, we just need to see if C or D is larger.
In C we have a term n 3/4 and correspondingly in D we have log 9n.
n3/4 is asymptotically larger than log 9n as when n = 10^10^.. (9 times) x, log 9 n returns x, while n 3/4 gives a much
higher value and for all higher value of n, n3/4 is larger than log 9x. So, D < C.
Thus A is correct.
7 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

19 of 1876

1.15 Asymptotic Notations: TIFR2014-B-8 top

gateoverflow.in/27192

Which of these functions grows fastest with n?


a. en /n.
b. en 0.9log n .
c. 2n .
d. (logn)n 1 .
e. None of the above.
tifr2014

algorithms

asymptotic-notations

Selected Answer

Assuming that the base of the log in the question is e.


Let us try to rewrite each of these functions in the form e something, to make the comparison easier.
en
e (lnn)

a.

en /n

b.

en 0.9ln n

c.

2n

= e ln2

d.

(lnn)n 1

= e lnlnn

= e (n lnn)
= e (n 0.9lnn)

( )

= e (nln2)
n1

= e (nlnlnn lnlnn)

Now, if we just compare the exponents of all, we can clearly see that (nlnlnn lnlnn) grows faster than the rest. Note that in
option c. the multiplicative ln2 is a constant, and hence grows slower than the multiplicative lnlnn from option d.
This implies that e (nlnlnn lnlnn) grows the fastest, and hence, (lnn)n 1 grows the fastest.
Thus, option d. is the correct answer.
-- Pragy Agarwal ( 13675 points)

5 votes

1.16 Asymptotic Notations: GATE1996_1.11 top


Which of the following is false?
nlog n

A. 100nlogn = ( 100 )
B. logn = O(loglogn)

( )

C. If 0 < x < y then nx = O ny

( )

D. 2n O nk

gate1996

algorithms

asymptotic-notations

Selected Answer

Answer: B

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/2715

GATE Overflow

April 2016

20 of 1876
-- Rajarshi Sarkar ( 27781 points)

4 votes

1.17 Asymptotic Notations: GATE2011_37 top

gateoverflow.in/2139

Which of the given options provides the increasing order of asymptotic complexity of functions f1 , f2 , f3 and f4 ?
f1 (n) = 2n
f2 (n) = n3 / 2
f3 (n) = nlog2 n
f4 (n) = nlog2 n
(A) f3 , f2 , f4 , f1
(B) f3 , f2 , f1 , f4
(C) f2 , f3 , f1 , f4
(D) f2 , f3 , f4 , f1

gate2011

algorithms

asymptotic-notations

normal

Selected Answer

[EDIT]
answer A
nlog2n < n 3/2 is quite straightforward
also n3/2 < n log 2n and n 3/2 < 2 n
now only n log 2n and 2 n need to be compared
taking log of both (log 2n)2 and n
n > (log2n)2
hence 2 n > n log 2n
5 votes

1.18 Asymptotic Notations: GATE1994_1.23 top


Consider the following two functions:

g1 (n) =

g2 (n) =

n3 for 0 n 10, 000


n2 for n 10, 000
n for 0 n 100
n3 for n > 100

Which of the following is true?


A. g1 (n) is O(g2 (n))
B. g1 (n) is O(n3 )
C. g2 (n) is O(g1 (n))
D. g2 (n) is O(n)

Copyright GATE Overflow. All rights reserved.

-- ankitrokdeonsns ( 7941 points)

gateoverflow.in/2466

GATE Overflow

April 2016

21 of 1876


gate1994

algorithms

asymptotic-notations

normal

Selected Answer

For asymptotic complexity, we assume sufficiently large n. So, g1 (n) = n2 and g2 (n) = n3 . Growth rate of g1 is less than that of
g2 . i.e., g1 (n) = O(g2 (n)).
Options A and B are true here.
-- Arjun Suresh ( 124085 points)

7 votes

answer - A
-- ankitrokdeonsns ( 7941 points)

3 votes

Yes. Both (a) and (b) are correct. n 2 is O(n 3)


-- gatecse ( 9515 points)

2 votes

1.19 Asymptotic Notations: GATE2008_39 top


Consider the following functions:
f(n) = 2n
g(n) = n!
h(n) = nlog n
Which of the following statements about the asymptotic behavior of f(n), g(n) and h(n) is true?
A. 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))

gate2008

algorithms

asymptotic-notations

normal

Selected Answer

g(n) = n! on expanding factorial we get g(n) = O(nn ) :


nn > nlog n
nn > 2n
this condition is violated by option A, B and C by first statements of each Hence, they cannot be said true.
second statement of option D says that g(n) is asymptotically biggest of all.
answer = option D

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/450

GATE Overflow

April 2016

22 of 1876
-- Amar Vashishth ( 17735 points)

3 votes

Answer is D.
1 < loglogn < logn < n e < nc < nlogn < cn < nn < cc^n < n! .
-- Gate Keeda ( 16619 points)

3 votes

f(n)

g(n)

h(n)

n=

210

21024

1024!

210

n=

211

22048

2048!

2121

Increase

21024

1025 1026 2048

221

10

= 2100


So, growth rate is highest for g(n) and lowest for h(n). Option D.
-- Arjun Suresh ( 124085 points)

2 votes

1.20 Asymptotic Notations: TIFR2011-B-27 top

gateoverflow.in/20573

Let n be a large integer. Which of the following statements is TRUE?


A. n1 / log2 n <

log2n < n


B. n1 / 100 < n1 / log2 n <

C. n1 / log2 n < n1 / 100 <

1 / 100

log2n
log2n


D.

1 / log n
1 / 100
log2n < n < n
2


E.

tifr2011

log2n < n

1 / 100

< n1 / log2 n

asymptotic-notations

Let n = 2x. Then, log2 n = x


f(n)

n1 / log2 n

g(n)

log2n

h(n)

n1 / 100

(2 )

x 1 / x

= 2x/ x

log2 (2x )

(2 )

x 1 / 100

2x

2x/ 100

Since exponentials grow faster than polynomials, h(n) > g(n) for large n.
x

Since linear functions grow faster than square roots, 100 >

Since exponentials grow faster than polynomials, 2x >

Copyright GATE Overflow. All rights reserved.

x for large x. Thus, h(n) > f(n) for large n.

x for large x. Thus, f(n) > g(n) for large n.

GATE Overflow

April 2016

23 of 1876

Hence, the relation is,


g(n) < f(n) < h(n)
Thus, option D is correct.
-- Pragy Agarwal ( 13675 points)

2 votes

1.21 Asymptotic Notations: GATE2005_37 top

gateoverflow.in/1373

Suppose T(n) = 2T( 2 ) + n, T(0) = T(1) = 1


Which one of the following is FALSE?

A. T(n) = O(n2 )
B. T(n) = (nlogn)
C. T(n) = (n2 )
D. T(n) = O(nlogn)


gate2005

algorithms

asymptotic-notations

recurrence

normal

Selected Answer

Applying Masters theorem T(n) = (n log n) So, it can't be (n 2)


Hence answer is C.
-- shreya ghosh ( 2801 points)

7 votes

1.22 Binary Heap: GATE2006_10 top

gateoverflow.in/889

In a binary max heap containing numbers, the smallest element can be found in time
(A) O(n)
(B) O(logn)
(C) O(loglogn)
(D) O(1)

gate2006

data-structure

heap

binary-heap

easy

Selected Answer

(A) O(n)
In a max heap, the smallest element is always present at a leaf node. Heap being a complete binary tree, there can be up
n

to 2 leaf nodes and to examine all of them we would need O(n) time.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

24 of 1876
-- Keith Kr ( 5467 points)

5 votes

1.23 Binary Search: GATE2008-85 top

gateoverflow.in/43508

Consider the following C program that attempts to locate an element x in an array Y[ ] using binary search. The program is
erroneous.
f (int Y[10] , int x) {
int u, j, k;
i= 0; j = 9;
do {
k = (i+ j) / 2;
if( Y[k] < x) i = k;else j = k;
} while (Y[k] != x) && (i < j)) ;
if(Y[k] == x) printf(" x is in the array ") ;
else printf(" x is not in the array ") ;
}

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

gate2008

algorithms

binary-search

normal

Ans should be A
if( Y[k] < x) then i = k + 1;

if given element that we are searching is greater then searching will be continued upper half of array
otherwise i=k-1
lower half.

0 votes

1.24 Binary Search: TIFR2012-B-11 top

-- Manojk ( 3327 points)

gateoverflow.in/25140

Consider the following three version of the binary search program. Assume that the elements of type T can be compared
with each other; also assume that the array is sorted.
i, j, k : integer;
a : array [1....N] of T;
x : T;
Program 1 :

i := 1; j := N;
repeat
k := (i + j) div 2;
if a[k] < x then i := k else j := k
until (a[k] = x) or (i > j)
Program 2 :
i := 1; j := N;
repeat
k := (i + j) div 2;
if x < a[k] then j := k - 1;
if a[k] < x then i := k + 1;
until i > j
Program 3 := i := 1; j := N
repeat
k := (i + j) div 2;
if x < a[k] then j := k else i := k + 1
until i > j

A binary search program is called correct provided it terminates with a[k] = x whenever such an element exists, or it
terminates with a[k] x if there exists no array element with value x. Which of the following statements is correct?
a. Only Program 1 is correct
b. Only Program 2 is correct
c. Only Program 1 and 2 are correct.
d. Both Program 2 and 3 are correct
e. All the three programs are wrong

Copyright GATE Overflow. All rights reserved.

GATE Overflow

tifr2012

April 2016

algorithms

25 of 1876

binary-search

first program wont work if array has elements same..it may go into infinite loop .To make it work it properly we have to do
following changes j=k-1 and i=k+1
For second program a[k]==x condition is mussung so it is wrong
Third program is also wrong as j!=k-1 and condition a[k]==x is missing
So ans is e
-- Pooja ( 22745 points)

1 votes

1.25 Binary Search: GATE2008-84 top

gateoverflow.in/394

Consider the following C program that attempts to locate an element x in an array Y[ ] using binary search. The program is
erroneous.

5.

10.

f (int Y[10] , int x) {


int u, j, k;
i= 0; j = 9;
do {
k = (i+ j) / 2;
if( Y[k] < x) i = k;else j = k;
} while (Y[k] != x) && (i < j)) ;
if(Y[k] == x) printf(" x is in the array ") ;
else printf(" x is not in the array ") ;
}

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
gate2008

algorithms

binary-search

normal

Selected Answer

for Q.84
when it is option C the control will continue to iterate as i = 8 and j = 9;
8 +9

again and again i will be assigned k which itself equals 8 as 2 being stored in an integer type variable, will evaluate to 8


for Q.85
to correct the flaw found in Q.84 corrections need to be made at statement 6, Hence, option A is correct.
7 votes

-- Amar Vashishth ( 17735 points)

84. The answer is C.


Binary search fails if all the elements are same.
85. The answer is A.
1 votes

1.26 Binary Search: GATE1996_18 top

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

gateoverflow.in/2770

GATE Overflow

April 2016

26 of 1876

Consider the following program that attempts to locate an element x in an array a[] using binary search. Assume N > 1. The
program is erroneous. Under what conditions does the program fail?
var i,j,k: integer; x: integer;
a: array; [1..N] of integer;
begin i:= 1; j:= n;
repeat
k:(i+j) div 2;
if a[k] < x then i:= k
else j:= k
until (a[k] = x) or (i >= j);
if (a[k] = x) then
writeln ('x is not in the array')
else
writeln ('x is not in the array')
end;



gate1996

algorithms

binary-search

normal

when input is [2 2 2 2 2 2 2 2 2 2] and search key x > 2


i=1 j=10 k= ((1+10)/ 2)) = 5
i=5 j=10 k= ((5+10)/ 2)) = 7
i=7 j=10 k= ((7+10)/ 2)) = 8
i=8 j=10 k= ((8+10)/ 2)) = 9
i=9 j=10 k= ((9+10)/ 2)) = 9
and goes into infinite loop

for correct output


if a[k] < x then i:= k+1

else j:= k-1;


1 votes

1.27 Binary Search: TIFR2010-B-29 top


Suppose you are given an array A with 2n numbers.
The numbers in odd positions are sorted in ascending order, that is, A[1] A[3] A[2n 1].
The numbers in even positions are sorted in descending order, that is, A[2] A[4] A[2n].
What is the method you would recommend for determining if a given number is in the array?
A. Sort the array using quick-sort and then use binary search.
B. Merge the sorted lists and perform binary search.
C. Perform a single binary search on the entire array.
D. Perform separate binary searches on the odd positions and the even positions.
E. Search sequentially from the end of the array.

tifr2010

binary-search

Copyright GATE Overflow. All rights reserved.

-- skrahul ( 275 points)

gateoverflow.in/18752

GATE Overflow

April 2016

27 of 1876

Selected Answer

Option D is the correct answer.


We can simply use clever indexing to binary search the element in the odd positions, and in the even positions separately.
This will take O(logn) time and O(1) space in the worst case.

A: Sorting using Quicksort will take O(n2 ) time.
B: Merging will take O(n) time and O(n) space.
C: Binary search only works on a sorted array.
E: Sequential search will take O(n) time.
-- Pragy Agarwal ( 13675 points)

3 votes

1.28 Binary Tree: GATE2014-3_12 top

gateoverflow.in/2046

Consider the following rooted tree with the vertex labeled P as the root:

The order in which the nodes are visited during an in-order traversal of the tree is
(A) SQPTRWUV
(B) SQPTUWRV
(C) SQPTWUVR
(D) SQPTRUWV


gate2014-3

algorithms

binary-tree

easy

Selected Answer

A.
the inorder traversal order of a ternary tree is left-->root-->middle-->right.
9 votes

1.29 Binary Tree: GATE2012_47 top

-- Gate Keeda ( 16619 points)

gateoverflow.in/2163

The height of a tree is defined as the number of edges on the longest path in the tree. The function shown in the pseudocode below is invoked as height(root) to compute the height of a binary tree rooted at the tree pointer root.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

28 of 1876

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

gate2012

algorithms

binary-tree

normal

Selected Answer

answer = option A
From the diagram below we are able to see how this works :

6 votes

-- Amar Vashishth ( 17735 points)

answer A
4 votes

1.30 Binary Tree: GATE2007_13 top


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

Copyright GATE Overflow. All rights reserved.

-- ankitrokdeonsns ( 7941 points)

gateoverflow.in/1211

GATE Overflow

April 2016

29 of 1876


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

gate2007

algorithms

binary-tree

normal

Selected Answer

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

-- Gate Keeda ( 16619 points)

4 votes

1.31 Binary Tree: GATE2004_85 top

gateoverflow.in/1079

A program takes as input a balanced binary search tree with n leaf nodes and computes the value of a function g(x) for each
node x. If the cost of computing g(x) is:
min

number of leaf-nodes
in left-subtree of x

number of leaf-nodes
in right-subtree of x

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


A. (n)
B. (nlogn)
C. (n2 )
D. (n2 logn)


gate2004

algorithms

binary-tree

normal

time-complexity

Selected Answer

B. At the root node (first level) the cost would be 2 and similarly at each level (toal cost per level and not the cost per
n

node in a level) the cost would be 2 and so for logn levels it would be (nlogn).
10 votes

-- Shaun Patel ( 5445 points)

Do a post order traversal and store and return min (g(x left), g(x right)) for all non leaf nodes and store 0 for all leaf nodes
and return 1. BST being balanced, with n leaf nodes we can have total 2n nodes and complexity of tree traversal is linear
in number of nodes- (n).

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

30 of 1876

But this is just computing the time complexity of g(x) for each node- not exactly what is asked in question.
Actually the procedure I gave is computing the COST of computing the value of g(x) which would have been correct had
the question been defined as
g(x) = min

number of leaf-nodes
in left-subtree of x

number of leaf-nodes
in right-subtree of x

The correct answer for this would be (nlogn) as at each level, the cost is (n) and we have logn levels since the tree is
balanced.
-- Arjun Suresh ( 124085 points)

4 votes

1.32 Binary Tree: GATE2000_2.16 top

gateoverflow.in/663

Let LASTPOST, LASTIN and LASTPRE denote the last vertex visited `in a postorder, inorder and preorder traversal respectively, of a complete
binary tree. Which of the following is always true?

a. LASTIN = LASTPOST
b. LASTIN = LASTPRE
c. LASTPRE = LASTPOST
d. None of the above

gate2000

algorithms

binary-tree

normal

Selected Answer

The answer is D.
Take any random sequence and check for the inorder, postorder and preorder Last Node.
8 votes

-- Gate Keeda ( 16619 points)

Inorder : Left -> Root -> Right


Preorder : Root -> Left -> Right
Postorder: Left -> Right -> Root
If the binary tree is full (last level is fully filled), the last visited node in Inorder and Preorder must be the rightmost one in
the last level. But for a complete binary tree this need not be the case (in a complete binary tree last level need not be
fully filled) and LASTPRE will be from the second last level in case the complete binary tree is not full. So, choice (D).
4 votes

1.33 Binary Tree: GATE2008_46 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/458

You are given the postorder traversal, P, of a binary search tree on the n elements 1, 2, , n. You have to determine the
unique binary search tree that has P as its postorder traversal. What is the time complexity of the most efficient algorithm
for doing this?

A. (logn)
B. (n)
C. (nlogn)
D. None of the above, as the tree cannot be uniquely determined

Copyright GATE Overflow. All rights reserved.

GATE Overflow
gate2008

April 2016

algorithms

binary-tree

31 of 1876

normal

Selected Answer

Last element in post order is the root of tree- find this element in inorder- logn time.
Now as in quick sort consider this as pivot and split the post order array into 2- possible because all elements smaller
than pivot goes to left and all elements larger than pivot goes to right and suppose we have x elements smaller than pivot,
these elements will be same in both inorder as well as postorder (order may change). We already got the root, now left
child is the left split and right child is the right split.
So, doing this recursively gives time complexity of this approach as
T(n) = T(k) + T(n k 1) + logn
Solving would give T(n) = O(nlogn) in worst case, by putting k = 0 and shown at bottom.
But searching for an element in the inorder traversal of given BST can be done in O(1) because we have n elements from
1..n so there is no need to search for an element- if last element in post order is say 5 we take it as root and since 4
elements (1..4) are smaller we split the post order array in to two- (first 4 elements), (6th element onward) and solve
recursively. Time complexity for this would be
T(n) = T(k) + T(n k 1) + O(1)
which gives T(n) = O(n).
Since we know that all elements must be traversed at least once, T(n) = (n) also and so
T(n) = (n).
The following code is doing this.
//Install graphviz (sudo apt-get install graphviz on Ubuntu) to view output tree
#include<stdio.h>
#include<stdlib.h>
struct tree
{
struct tree* left;
struct tree* right;
int x;
};
struct tree* makenode(int x)
{
struct tree * root = malloc(sizeof(struct tree));
root -> x = x;
root -> left = root -> right = NULL;
return root;
}
struct tree* makeBST(int *post, int start, int n, int inorder){
if(n <= 0)
return NULL;
int pivot = post[start + n -1];
struct tree * root = makenode(pivot);
root -> left = makeBST(post, start, pivot-1 - inorder, inorder );
root -> right = makeBST(post, pivot - inorder - 1, n - (pivot - inorder), pivot);
return root;
}
void preorder(struct tree* node)
{
if(node == NULL)
return;
printf("%d ", node->x);
preorder(node->left);
preorder(node->right);
}
void printdot(struct tree* node, FILE * f)
{
if(node == NULL)
return;
if(node-> left != NULL)
{
fprintf(f, "%d -- %d;\n", node->x, node->left->x);
}
if(node-> right != NULL)
{
fprintf(f, "%d -- %d;\n", node->x, node->right->x);
}
printdot(node->left, f);
printdot(node->right, f);
}
int main(){
int i, n, *a;
printf("Enter n: ");
scanf("%d", &n);
a = malloc(n * sizeof(int));
printf ("Enter post order traversal: ");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
struct tree * tree = makeBST(a, 0, n, 0);

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

32 of 1876

printf("Pre order traversal is : ");


preorder(tree);
printf("\n");
FILE * f = fopen("tree.dot", "w");
fprintf(f, "graph tree { \n");
printdot(tree, f);
fprintf(f, "}\n");
fclose(f);
#if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__) || (defined (__gnu_linux__)) )
system("dot -Tpng tree.dot -o output.png; eog output.png");
#endif
}

T(n) = T(k) + T(n k 1) + logn


Solving would give T(n) = O(nlogn), by putting k = 0,
[Math Processing Error]
-- Arjun Suresh ( 124085 points)

11 votes

Answer is c as inorder is sorted u can do a binary search


-- Shreyans Dhankhar ( 2265 points)

1 votes

1.34 Binary Tree: GATE2014-3_39 top

gateoverflow.in/2073

Suppose we have a balanced binary search tree T holding n numbers. We are given two numbers L and H and wish to sum
up all the numbers in T that lie between L and H. Suppose there are m such numbers in T. If the tightest upper bound on the
time to compute the sum is O(na logb n + m clogd n), the value of a + 10b + 100c + 1000d is ______.

gate2014-3

algorithms

binary-tree

time-complexity

numerical-answers

normal

Selected Answer

In worst case for finding L and H it will take O(logn) time as the given tree is balanced binary search tree.
Now there are m elements between L and H. So to traverse m element it will take O(m) time (traversal algorithm given below). So, total

O(m + logn)  a = 0, b = 1, c = 1, d = 0
0 + (10 1) + (100 1) + (1000 0) = 110.
To find all the numbers from L to H we can do an inorder traversal from root and discard all elements before L and after H
. But this has O(n) time complexity. So, we can do a modification to inorder traversal and combine with binary search as
follows:
1. Find L using binary search and keep all nodes encountered in the search in a stack.
2. After finding L add it to stack as well and initialize sum = 0.
3. Now, for all nodes in stack, do an inorder traversal starting from their right node and adding the node value to sum.
If H is found, stop the algorithm.
9 votes

int getSum(node *root, int L, int H)


{
// Base Case
if (root == NULL)
return 0;
if (root->key < L)
return getSum(root->right, L, H);
if (root->key > H)
return getSum(root->left, L, H)

Copyright GATE Overflow. All rights reserved.

-- Kalpish Singhal ( 1575 points)

GATE Overflow

April 2016

33 of 1876

if (root->key >= L && root->key <=H)


return getSum(root->left, L, H) + root->key +
getSum(root->right, L, H);
}
it will be O(logn +m)
it can go max of logn depth to find nodes in range and function calls for nodes in range ie m
Note that the code first traverses across height to find the node which lies in range. Once such a node is found, it recurs
for left and right children. Two recursive calls are made only if the node is in range. So for every node that is in range, we
make at most one extra call (here extra call means calling for a node that is not in range).
source:http://geeksquiz.com/gate-gate-cs-2014-set-3-question-49/
-- Anurag Semwal ( 4775 points)

2 votes

Do tree traversal from root as follows: Do a recursive search to find L, saving all the nodes visited in a stack. Since tree is
balanced BST, it'll take O(log n) time. After finding L instead of search do inorder traversal up to m nodes from this node
and continuing (if needed) using the saved nodes during searching. Complexity O(m).
Total time = O(m) + O(log n)
a=0, b=1, c=1, d=0
a+10b+100c+1000d = 0+ 10 + 100 + 0
= 110
-- Digvijay Pandey ( 26235 points)

1 votes

within those m numbers, we have to search m times to see if the numbers are existing in the Balanced BST & add them.
so, m log n time.
c = 1, d = 1 => answer = 0 + 0 + 100 + 1000 = 1100
-- innovwelt ( 27 points)

1 votes

1.35 Binary Tree: GATE1997_4.5 top

gateoverflow.in/2246

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

gate1997

algorithms

binary-tree

Selected Answer

Answer: D
The tree is:

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

34 of 1876

-- Rajarshi Sarkar ( 27781 points)

5 votes

answer D
-- ankitrokdeonsns ( 7941 points)

4 votes

1.36 Binary Tree: GATE2007_46 top

gateoverflow.in/1244

Consider the following C program segment where CellNode represents a node in a binary tree:
struct CellNode {
struct CellNode *leftChild;
int element;
struct CellNode *rightChild;
};
int Getvalue (struct CellNode *ptr) {
int value = 0;
if (ptr != NULL) {
if ((ptr->leftChild == NULL) &&
(ptr->rightChild == NULL))
value = 1;
else
value = value + GetValue(ptr->leftChild)
+ GetValue(ptr->rightChild);
}
return(value);
}

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

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

gate2007

algorithms

binary-tree

normal

Selected Answer

Answer: C
As the function returns 1 if and only if any node has both left & right children as NULL (that node is a leaf node). Hence,
value gets incremented at each leaf node.
3 votes

1.37 Binary Tree: GATE2007_39 top


The inorder and preorder traversal of a binary tree are
d b e a f c g and a b d e c f g, respectively

Copyright GATE Overflow. All rights reserved.

-- Rajarshi Sarkar ( 27781 points)

gateoverflow.in/1237

GATE Overflow

April 2016

35 of 1876

The postorder traversal of the binary tree is:



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

gate2007

algorithms

binary-tree

normal

Selected Answer

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

-- Gate Keeda ( 16619 points)

3 votes

1.38 Binary Tree: GATE2013_43 top

gateoverflow.in/1554

The preorder traversal sequence of a binary search tree is 30, 20, 10, 15, 25, 23, 39, 35, 42. Which one of the following is
the postorder traversal sequence of the same tree?
(A) 10, 20, 15, 23, 25, 35, 42, 39, 30
(B) 15, 10, 25, 23, 20, 42, 35, 39, 30
(C) 15, 20, 10, 23, 25, 42, 35, 39, 30
(D) 15, 10, 23, 25, 20, 35, 42, 39, 30
gate2013

algorithms

binary-tree

normal

Selected Answer

Since it is a binary search tree, its inorder traversal produces a sorted sequence i.e. 10, 15, 20, 23, 25, 30, 35, 39, 42.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

36 of 1876

Now given inorder and preorder traversals, we get following tree :

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

8 votes

1.39 Connected Components: GATE1992_03,iii top

gateoverflow.in/580

How many edges can there be in a forest with p components having n vertices in all?
gate1992

algorithms

connected-components

easy

Selected Answer

Answer: n-p
Corollary: If G is a forest with n vertices and p components, then G has n-p edges.
As, 0 edges for p-1 vertices (p-1 components) and n-p edges for n-p+1 vertices (1 component). So, total of n-p edges for
p components.
-- Rajarshi Sarkar ( 27781 points)

3 votes

1.40 Connected Components: GATE2005-IT_14 top

gateoverflow.in/3759

In a depth-first traversal of a graph G with n vertices, k edges are marked as tree edges. The number of connected
components in G is

1)
2)
3)
4)
gate2005-it

k
k + 1
n - k - 1
n - k

algorithms

graph-algorithms

connected-components

normal

Selected Answer

Answer D => n-k


Why ?
If Graph is connected , while doing DFS we will visit some spanning Tree of Graph. So no of edges will be n-1 &
No of components => n - (n-1) => 1

If Graph is not connected in that case when we do the DFS on those disconnected graph,
For every disconnected component with say x vertices, we will get x-1 Tree edge. When we sum up all vertices we will get
total no of vertices. When we sum up all edges in spanning tree of each component, we will get => Total no of vertices Total No of connected component ( Due to for each connected component we are getting tree of no of vertices in that
connnected component - 1)
So Total connected component => D) n-k

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

37 of 1876

-- Akash ( 26265 points)

5 votes

and by taking a random example take A B C D(fully connected) E, F(both disconnected) how many vertices? 6. Edges in
any minumum spanning tree of ABCD=3? yes. and we have 3 components. so akash's answer is right!
-- Aspi R Osa ( 1305 points)

1 votes

1.41 Connected Components: GATE2006-IT_47 top

gateoverflow.in/3590

Consider the depth-first-search of an undirected graph with 3 vertices P, Q, and R. Let discovery time d(u) represent the
time instant when the vertex u is first visited, and finish time f(u) represent the time instant when the vertex u is last
visited. Given that
d(P) = 5 units f(P) = 12 units
d(Q) = 6 units f(Q) = 10 units
d(R) = 14 unit f(R) = 18 units
which one of the following statements is TRUE about the graph

A)
B)
C)
D)

There is only one connected component


There are two connected components, and P and R are connected
There are two connected components, and Q and R are connected
There are two connected components, and P and Q are connected

gate2006-it

algorithms

graph-algorithms

connected-components

normal

since d(q)=d(p)+1 and f(q)< f(p) which means p and q are connected
and r is seperate so d is the answer
-- Shreyans Dhankhar ( 2265 points)

4 votes

1.42 Connected Components: GATE2014-1_3 top

gateoverflow.in/1754

Let G = (V, E) be a directed graph where V is the set of vertices and E the set of edges. Then which one of the following graphs has the same strongly connected
components as G ?

(A) G1 = (V, E 1 ) where E 1 = {(u, v) (u, v) E}


(B) G2 = (V, E 2 ) where E 2 = {(u, v) (v, u) E}
(C) G3 = (V, E 3 ) where E 3 = {(u, v) there is a path of length 2 from u to v in E}
(D) G4 = (V 4 , E) where V 4 is the set of vertices in G which are not isolated

gate2014-1

algorithms

graph-algorithms

connected-components

normal

Selected Answer

A is false. Consider just two vertices connected to each other. So, we have one SCC. The new graph won't have any edges
and so 2 SCC.
B is true. In a directed graph a SCC will have a path from each vertex to every other vertex. So, changing the direction of
all the edges, won't change the SCC.
D is false. Consider any graph with isolated vertices- we loose those components.
C is a bit tricky. Any edge is a path of length 1. So, the new graph will have all the edges from old one. Also, we are
adding new edges (u, v). So, does this modify any SCC? No, because we add an edge (u, v), only if there is already a path of
length <= 2 from u to v- so we do not create a new path. So, both B and C must be answers though GATE key says only
B.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

38 of 1876
-- Arjun Suresh ( 124085 points)

6 votes

1.43 Connected Components: GATE1997_6.2 top

gateoverflow.in/2258

Let G be the graph with 100 vertices numbered 1 to 100. Two vertices i and j are adjacent if |i j | = 8 or |i j | = 12.
The number of connected components in G is
a. 8
b. 4
c. 12
d. 25

gate1997

algorithms

graph-algorithms

connected-components

normal

Selected Answer

From the description it is clear that vertices are connected as follows:


1-9-17-...-97
2-10-18-...-98
3-11-19-...-99
4-12-20-...-100
5-13-21-...-93
6-14-22-...-94
7-15-23-...-95
8-16-24-...96
We have covered all vertices using 8 vertex sets considering only i j = 8. Using i j = 12 we can see the vertex 1 is
connected to 13, 2-14, 3-15 and 4-16, so the top 4 vertex sets are in fact connected to the bottom 4 sets, thus reducing
the connected components to 4.
-- Arjun Suresh ( 124085 points)

5 votes

there will be 4 connected component.(1 5 9 13 17......)(2 6 10 14 18....) (3 7 11 15 19 .....)(4 8 12 16......)


-- Supromit Roy ( 483 points)

1 votes

1.44 Connected Components: GATE2006-IT_46 top

gateoverflow.in/3589

Which of the following is the correct decomposition of the directed graph given below into its strongly connected
components?


A)
B)

{P, Q, R, S}, {T}, {U}, {V}


{P,Q, R, S, T, V}, {U}

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

C)
D)

39 of 1876

{P, Q, S, T, V}, {R}, {U}


{P, Q, R, S, T, U, V}

gate2006-it

algorithms

graph-algorithms

connected-components

normal

ans (B)..
-- Vicky Bajoria ( 3147 points)

2 votes

1.45 Decidability: GATE2005_45 top

gateoverflow.in/1375

Consider three decision problems P 1, P 2 and P 3. It is known that P 1 is decidable and P 2 is undecidable. Which one of the
following is TRUE?
A. P3 is decidable if P 1 is reducible to P 3
B. P3 is undecidable if P 3 is reducible to P 2
C. P3 is undecidable if P 2 is reducible to P 3
D. P3 is decidable if P 3 is reducible to P 2's complement

gate2005

algorithms

decidability

normal

Selected Answer

(A) If P1 is reducible to P 3, then P 3 is at least as hard as P 1. So, no guarantee if P 3 is decidable.


(B) If P 3 is reducible to P 2, then P 3 cannot be harder than P 2. But P 2 being undecidable, this can't say P 3 is undecidable.
(C) If P 2 is reducible to P 3, then P 3 is at least as hard as P 2. Since, P 2 is undecidable, this means P 3 is also undecidable hence the answer.
(D) Complement of an undecidable problem is undecidable. Now, reducing to an undecidable problem can't prove P 3 is
decidable.
http://gatecse.in/wiki/Some_Reduction_Inferences
-- Arjun Suresh ( 124085 points)

9 votes

1.46 Dfs: TIFR2014-B-3 top

gateoverflow.in/27137

Consider the following directed graph.

Suppose a depth-first traversal of this graph is performed, assuming that whenever there is a choice, the vertex earlier in
the alphabetical order is to be chosen. Suppose the number of tree edges is T, the number of back edges is B and the
number of cross edges is C. Then
a. B
b. B
c. B
d. B
e. B

tifr2014

=
=
=
=
=

1, C
0, C
2, C
1, C
2, C

dfs

=
=
=
=
=

1, and T
2, and T
1, and T
2, and T
2, and T

data-structure

=
=
=
=
=

4.
4.
3.
3.
1.

graph-algorithms

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

40 of 1876

Selected Answer

Since they said that whenever their is a choice we will have to select the node which is alphabetically earlier , therefore we
choose the starting node as A .
The tree then becomes A-B-E-C . Therefore no of tree edges is 3 that is (T=3) .
Now there is one cycle B-E-C so we will get a back edge from C to B while performing DFS. Hence B=1 .
Now D becomes disconnected node and it can only contribute in forming cross edge . There are 2 cross edges D-A , D-B .
Therefore C=2 .
Answer is Option D .
Correct me if am going wrong.
-- Riya Roy ( 4769 points)

4 votes

1.47 Distance Vector Routing: GATE2011-49 top

gateoverflow.in/43324

Consider the following recursive C function that takes two arguments.


unsigned int foo(unsigned int n, unsigned int r) {
if (n>0) return ((n%r) + foo(n/r, r));
else return 0;
}
What is the return value of the function foo when it is called as foo(513, 2)?

A. 9
B. 8
C. 5
D. 2

gate2011

algorithms

recursion

identify-function

distance-vector-routing

normal

Selected Answer

The function returns the sum of digits in a binary representation of the given number
so 1+0+0+0+0+0+0+0+0+1 = 2
1 votes

Final return value is 2 So option d

Copyright GATE Overflow. All rights reserved.

-- Sandeep_Uniyal ( 5063 points)

GATE Overflow

April 2016

41 of 1876

-- Manojk ( 3327 points)

1 votes

1.48 Dynamic Programming: GATE 2016-2-14 top

gateoverflow.in/39570

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.


gate2016-2

algorithms

graph-algorithms

shortest-path

dynamic-programming

easy

Selected Answer

In floyd warshalls we calcuate all possibilities and select best one so its neither dac nor greedy but based on
Dynamic Programming Paradigm.

9 votes

1.49 Dynamic Programming: GATE2009-53 top

-- Anurag Semwal ( 4775 points)

gateoverflow.in/1338

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 I(i, j) to compute the length of the LCS of X[m] and Y[n] is given below:

Copyright GATE Overflow. All rights reserved.

GATE Overflow
l(i,j)

April 2016

42 of 1876

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

Which one of the following options is correct?


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

gate2009

algorithms

normal

dynamic-programming

recursion

Selected Answer

Answer is C. When the currently compared elements doesn't match, we have two possibilities for the LCS, one including
X[i] but not Y[j] and other including Y[j] but not X[i].
-- Akash ( 26265 points)

6 votes

Answer is C. When the currently compared elements doesn't match, we have two possibilities for the LCS, one including
X[i] but not Y[j] and other including Y[j] but not X[i].
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
if (m == 0 || n == 0)
return 0;
if (X[m-1] == Y[n-1])
return 1 + lcs(X, Y, m-1, n-1);
else
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}

-- Sona Praneeth Akula ( 3473 points)

6 votes

1.50 Dynamic Programming: GATE2009-54 top

gateoverflow.in/43476

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 I(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]
The value of l(i, j) could be obtained by dynamic programming based on the correct recursive definition of l(i, j) of the form
given above, using an array L[M, N], where M = m + 1 and N = n + 1, such that L[i, j] = l(i, j).
Which one of the following statements would be TRUE regarding the dynamic programming solution for the recursive
definition of l(i, j)?
A. All elements of L should be initialized to 0 for the values of l(i, j) to be properly computed.
B. The values of l(i, j) may be computed in a row major order or column major order of L[M, N].
C. The values of l(i, j) cannot be computed in either row major order or column major order of L[M, N].
D. L[p, q] needs to be computed before L[r, s] if either p < r or q < s.

gate2009

normal

algorithms

dynamic-programming

recursion

expr2 = max (l(i 1, j), l(i, j 1))


When the currently compared elements doesn't match, we have two possibilities for the LCS, one including X[i] but not

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

43 of 1876

Y[j] and other including Y[j] but not X[i].


/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
if (m == 0 || n == 0)
return 0;
if (X[m-1] == Y[n-1])
return 1 + lcs(X, Y, m-1, n-1);
else
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}

54. Answer is B. Dynamic programming is used to save the previously found LCS. So, for any index [p,q] all smaller ones
should have been computed earlier. Option D is not correct as the condition given requires even L[3,2] to be computed
before L[2,4] which is not a necessity if we follow row-major order.
int lcs( char *X, char *Y, int m, int n )
{
int L[m+1][n+1];
int i, j;
/* Following steps build L[m+1][n+1] in bottom up fashion. Note
that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
for (i=0; i<=m; i++)
{
for (j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;

else
L[i][j] = max(L[i-1][j], L[i][j-1]);

/* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */


return L[m][n];


-- Arjun Suresh ( 124085 points)

0 votes

1.51 Expectation: GATE2003-62 top

gateoverflow.in/43576

In a permutation a1 . . . an , of n distinct integers, an inversion is a pair (ai, aj) such that i < j and ai > aj.
What would be the worst case time complexity of the Insertion Sort algorithm, if the inputs are restricted to permutations of
1.. . n with at most n inversions?
A. (n2 )
B. (nlogn)
C. (n1.5)
D. (n)

gate2003

algorithms

sorting

expectation

normal

Selected Answer

ANSWER: D. (n)
REASON:
Count of number of times the inner loop of insertion sort executes is actually equal to number of inversions in input
permutation a1 , a2 , an . Since for each value of i = 1..n, j take the value 1..i 1, which means for every j < i it checks if
a[j] > a[i].
In any given permutation, maximum number of inversions possible is n(n 1)/2 which is O(n2 ). It is the case where the
array is sorted in reverse order. Therefore, to resolve all inversions i.e., worst case time complexity of insertion sort is
(n2 ).
However, as per the question the number of inversion in input array is restricted to n. The worst case time complexity of
insertion sort reduces to (n).

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

44 of 1876

INSERTION SORT ALGORITHM (for reference)


-- Prateek Dwivedi ( 825 points)

3 votes

1.52 Expectation: GATE2003-61 top

gateoverflow.in/949

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?
n (n 1 )
2

A.

n (n 1 )
4

B.

n (n +1 )
4
C.
D. 2n[log2 n]

gate2003

algorithms

sorting

expectation

normal

They are asking the average number of inversion. basically what i learned about averages from dbms indexing is.
average apart from the standard definition can be calculated as ( best case + worst case )/2
and inversion is like 9,5.
so best case will be sorted array - 1,2,3,4,5 no inversion . = zero
worst case = 9,5,4,3,2,1 . here total number of inversion will be n(n-1)/2 as . 9 can be paired with any 5 elements
(5,4,3,2,1 ) will form a inversion pair. similarly 5 with 4.elements .
so we can say if we have n elements then. it will be (n-1)+(n-2)+(n-3)...+2+1 which is the sum of first n-1 natural
numbers. so it is n(n-1)/2
so expected average number of inversion = (n(n-1)/2 + zero (best case)) /2= n(n-1)/4
so option b.
second question.
we all know that insertion sort has complexity due to swapping and movements, if we have n n inversion pair then the
movements and comparision will be restricted to n only . like if inversion is 1 , then array must be sorted and only the
inversion should exist at the end, like 1,2,3,5,4. otherwise more than one inversion pair will form. so to sort this. for two
it will be 1,2,3,7,5,4. so to sort this type of array using insertion sort atmost N swaps wiill be required, so d
4 votes

-- Ravi Singh ( 7303 points)

If u dont have any proper method to solve , try by taking small example and eliminate options.
Take n=3,
Permutation ----> no of inversions
1 2 3 0
1 3 2 1
2 3 1 2
2 1 3 1
3 1 2 2
3 2 1 3
Total inversions =9, no of cases =6, expected no of inversions=9/6 = 1.5, put in all options , only B satisfied.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

45 of 1876

62) We have seen maximum n inversions can occur. So no use of restriction , and 3 2 1 in this case Insertion sort will
take o(n2).
-- Aryan ( 223 points)

1 votes

Select 2 out of n and half of them will be inversions B.


-- anshu ( 2155 points)

1 votes

1.53 Grammar: GATE1998_6 top

gateoverflow.in/1697

a. Solve the following recurrence relation


xn = 2xn 1 1, n > 1
x1 = 2
b. Consider the grammar
S Aa b
A Ac Sd
Construct an equivalent grammar with no left recursion and with minimum number of production rules.

gate1998

algorithms

recurrence

compiler-design

grammar

descriptive

(b) As it is the case of indirect recursion so let first make it as direct recursion then apply rules of removal of left
recursion.
to make it as direct recursion first production remain unchanged while in second production substitute the right hand side
of first production wherever it comes.In the question S comes in middle of A so substitute the right hand side of
production S.Now after substituting it looks like..
A->Ac|Aad|bd|
Now remove direct recursion from it
For removal of direct recursion rule--

Replace these with two sets of productions, one set for

and another set for the fresh nonterminal

After applying these rule we'll get..

A->bdA'|A'
A'->cA'|adA'|

Now complete production without left recursion is...
S->Aa|b
A->bdA'|A'
A'->cA'|adA'|

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

46 of 1876



-- shashi shekhar ( 327 points)

0 votes

1.54 Graph Algorithms: GATE2007-IT_24 top

gateoverflow.in/3457

A depth-first search is performed on a directed acyclic graph. Let d[u] denote the time at which vertex u is visited for the
first time and f[u] the time at which the dfs call to the vertex u terminates. Which of the following statements is always true
for all edges (u, v) in the graph ?

A)
B)
C)
D)
gate2007-it

d[u] < d[v]


d[u] < f[v]
f[u] < f[v]
f[u] > f[v]

algorithms

graph-algorithms

normal

Selected Answer

since DFS is performed on directed acyclic graph so we dnt have any back edges
since we are only having tree edges forward edges and cross edges
so u vil get the answer as D
-- Shreyans Dhankhar ( 2265 points)

6 votes

I'm gonna disprove all wrong options here.


A) d[u] < d[v] , Counter Example => Well if we directly start DFS on V first. Then I call DFS on X which visits U.
B) d[u] < f[v] Counter example => Same as A)
C) f[u] < f[v] Counter example => Same as A) again
So answer is D)
-- Akash ( 26265 points)

2 votes

1.55 Graph Algorithms: GATE2007-IT_3 top

gateoverflow.in/3434

Consider a weighted undirected graph with positive edge weights and let uv be an edge in the graph. It is known that the
shortest path from the source vertex s to u has weight 53 and the shortest path from s to v has weight 65. Which one of the
following statements is always true?

A)
B)

weight (u, v) < 12


weight (u, v) 12

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

C)
D)

47 of 1876

weight (u, v) > 12


weight (u, v) 12

gate2007-it

algorithms

graph-algorithms

normal

Selected Answer

D. weight(u,v) 12
If weight (u, v) < 12, then the min. weight of (s, v) = weight of (s, u) + weight of (u, v) = 53 + (<12) will be less than
65.
-- Arjun Suresh ( 124085 points)

10 votes

1.56 Graph Algorithms: GATE2016-2-41 top

gateoverflow.in/39620

In an adjacency list representation of an undirected simple graph G = (V, E), each edge (u, v) has two adjacency list entries:
[v] in the adjacency list of u, and [u] in the adjacency list of v. These are called twins of each other. A twin pointer is a
pointer from an adjacency list entry to its twin. If | E | = m and | V | = n, and the memory size is not a constraint, what is the
time complexity of the most efficient algorithm to set the twin pointer in each entry in each adjacency list?

( )

A. n2

B. (n + m)

( )
D. (n )
C. m 2
4


gate2016-2

algorithms

graph-algorithms

normal

Can we use this approach not sure about this?


We will consider a directed graph with every undirected edge is replaced by two directed edges one forward and one
backward. Then we do DFS-like traversal on this graph and set the twin pointer of as it's parent pointer. So the time
complexity will be (m + n)
-- Sumit1311 ( 641 points)

1 votes

1.57 Graph Algorithms: GATE2004_81 top

gateoverflow.in/1075

L e t G 1 = (V, E1 ) and G 2 = (V, E2 ) be connected graphs on the same vertex set V with more than two vertices. If
G 1 G 2 = (V, E1 E2 ) is not a connected graph, then the graph G 1 G 2 = (V, E1 E2 )
(a). cannot have a cut vertex.
(b). must have a cycle
(c). must have a cut-edge (bridge).
(d). Has chromatic number strictly greater than those of G 1 and G 2
gate2004

algorithms

graph-algorithms

Selected Answer

Take a tree for example

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

48 of 1876

(A) False. Every vertex of tree(other than leaves) is a cut vertex


(B)True
(C)False. Without E in G1 and G2, G1 U G2 has no bridge.
(D)False. G1 U G2, G1, G2 three graphs have same chromatic number of 2.
-- srestha ( 11537 points)

1 votes

1.58 Graph Algorithms: GATE2009_13 top


Which of the following statement(s) is/are correct regarding Bellman-Ford shortest path algorithm?
A. Always finds a negative weighted cycle, if one exists.
B. Finds whether any negative weighted cycle is reachable from the source.

A. P only
B. Q only
C. Both P and Q
D. Neither P nor Q

gate2009

algorithms

graph-algorithms

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/1305

GATE Overflow

April 2016

49 of 1876

as we can see that last step is the verification step. In that step values remained unchanged. If there was a negative edge weight cycle
reachable from source then at verification step also those values will be different from the values above.
In case the cycle is not reachable from source then we can see that they will be at distance(or cost) from the source from the beginning till
the last step. As take anything away from the it will still be infinite.
But it can also be the case that there are some points which are not forming a cycle and are still unreachable from source those also will be at
distance from the source from the beginning till end.
Hence, we won't be able to make a distinction among the cycle and such vertices. Thus, we say that this algorithm can detect negative edge
weight cycles only if they are reachable from the source.
answer = option B
-- Amar Vashishth ( 17735 points)

3 votes

The answer is B.
-- Gate Keeda ( 16619 points)

4 votes

1.59 Graph Algorithms: GATE2007_41 top

gateoverflow.in/1239

In an unweighted, undirected connected graph, the shortest path from a node S to every other node is computed most
efficiently, in terms of time complexity, by

A. Dijkstras algorithm starting from S.
B. Warshalls algorithm.
C. Performing a DFS starting from S.
D. Performing a BFS starting from S.

gate2007

algorithms

graph-algorithms

easy

Selected Answer

In BFS traversal .1st we note those vertices which can be reached directly from starting vertex..next we note the vertices
which can be reached in 2 steps from starting vertex ..then as follows so it is the best choice i can make
3 votes

Copyright GATE Overflow. All rights reserved.

-- Bhagirathi Nayak ( 10239 points)

GATE Overflow

April 2016

50 of 1876

1.60 Graph Algorithms: GATE2005_82 top

gateoverflow.in/1404

Statement for linked Answer Questions 82a & 82b:


Let s and t be two vertices in a undirected graph G = (V, E) having distinct positive edge weights. Let [X, Y] be a partition of V
such that s X and t Y. Consider the edge e having the minimum weight amongst all those edges that have one vertex in X
and one vertex in Y.
(A) The edge e must definitely belong to:
A. the minimum weighted spanning tree of G
B. the weighted shortest path from s to t
C. each path from s to t
D. the weighted longest path from s to t

(B) Let the weight of an edge e denote the congestion on that edge. The congestion on a path is defined to be the maximum
of the congestions on the edges of the path. We wish to find the path from s to t having minimum congestion. Which of the
following paths is always such a path of minimum congestion?

A. a path from s to t in the minimum weighted spanning tree
B. a weighted shortest path from s to t
C. an Euler walk from s to t
D. a Hamiltonian path from s to t

gate2005

algorithms

graph-algorithms

normal

Answer for 82 b) is option a) A path from s to t in MST.


T is the spanning tree and E T is the edge set of the tree.
Let L denote the set of all paths P e in T where e is any edge in E G. For g E T , we define the congestion of g as the
number of paths in L in which g is an element:
c(g, T) = |{P e L : g P e}|.
We then define the congestion of G embedded onto T as the maximum c(g, T) over all edges g in E T :
c(G : T) = max{c(g, T) : g E T }.
The tree congestion of G, denoted t(G), is the minimum value of c(G : T) over all trees T in T G. Similarly, the spanning
tree congestion of G, denoted s(G), is the minimum value of c(G : T) over all spanning trees S in SG:
t(G) = min{c(G : T) : T T G},
s(G) = min{c(G : S) : S S G}
Please refer to the link
http://www.math.csusb.edu/reu/dt07.pdf
2 votes

-- Shounak Kundu ( 3757 points)

For 82b answer is clearly option B and this concept is used in Link State Routing Algorithm.
1 votes

Copyright GATE Overflow. All rights reserved.

-- chandan1223 ( 37 points)

GATE Overflow

April 2016

51 of 1876

For 82a The answer should be Option A because edge 'e' is the lightest safe edge connecting X and Y so the minimum
spanning tree of G must contain 'e' (Greedy and optimal choice).
While B might seem correct but it is not always true. One such case is when G is not connected therefore there might not
be any path between 's' and 't'.
Since the question is about definitely true B is incorrect and A is the only correct optio

Lets say AC =1 CD = 2 BD = 3 and AB=4


Then if s= A and t= B then AC is the lightest edge crossing X and Y where X = { A } and Y = { C, B, D}
But clearly AC is not on the shortest path from A to B. The shortest path is AB = 4.
-- chandan1223 ( 37 points)

1 votes

1.61 Graph Algorithms: GATE2005_38 top

gateoverflow.in/1374

L e t G(V, E) be an undirected graph with positive edge weights. Dijkstras single source shortest path algorithm can be
implemented using the binary heap data structure with time complexity:

( )

A. O | V | 2

B. O( | E | + | V | log | V | )
C. O( | V | log | V | )
D. O(( | E | + | V | )log | V | )

gate2005

algorithms

graph-algorithms

normal

Selected Answer

D.- Binary heap. |E| decrease key operations and each taking O(log |V|) time plus |V| extract-min operations each taking
O(log |V|).
B- Fibonacci heap. |E| decrease key operations and each taking O(1) time plus |V| extract-min operations each taking
O(log |V|).
A- Array. Finding min-vertex in each iteration takes O(V) and this needs to be done |V| times.
Binomial Heap- same as Binary heap here as the critical operations are decrease key and extract-min.
7 votes

1.62 Graph Algorithms: GATE1994_24 top

-- Gate Keeda ( 16619 points)

gateoverflow.in/2520

An independent set in a graph is a subset of vertices such that no two vertices in the subset are connected by an edge. An
incomplete scheme for a greedy algorithm to find a maximum independent set in a tree is given below:
V: Set of all vertices in the tree;
I :=

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

52 of 1876

while V do
begin
select a vertex u V such that
_______;
V := V - {u};
if u is such that
________then I := I {u}
end;
Output(I);

a. Complete the algorithm by specifying the property of vertex u in each case.


b. What is the time complexity of the algorithm

gate1994

algorithms

graph-algorithms

normal

(a) While adding vertex u to I it should not have an edge with any node in I.
(b) The algorithm runs till V is empty (in O(n) time) and is checking u with each vertex v in set I (in O(n) time). So,
overall complexity O(n2).
-- Rajarshi Sarkar ( 27781 points)

2 votes

1.63 Graph Algorithms: GATE2013_19 top

gateoverflow.in/1441

What is the time complexity of Bellman-Ford single-source shortest path algorithm on a complete graph of n vertices?
(A) (n2 ) (B) (n2 logn) (C) (n3 ) (D) (n3 logn)
gate2013

algorithms

graph-algorithms

normal

Selected Answer

Time complexity of Bellman-Ford algorithm is (VE) where V is number of vertices and E is number of edges.If the graph
is complete, the value of E becomes (V2).So overall time complexity becomes (V3). And given here is n vertices...so
answers ends up to (n3).
11 votes

-- Gate Keeda ( 16619 points)

1.64 Graph Algorithms: GATE2004_44 top

gateoverflow.in/1041

Suppose we run Dijkstras single source shortest-path algorithm on the following edge-weighted directed graph with vertex P
as the source.


In what order do the nodes get included into the set of vertices for which the shortest path distances are finalized?

A. P,Q,R,S,T,U
B. P,Q,R,U,S,T
C. P,Q,R,U,T,S
D. P,Q,T,R,U,S

Copyright GATE Overflow. All rights reserved.

GATE Overflow

gate2004

April 2016

algorithms

graph-algorithms

53 of 1876

normal

Selected Answer

Ans is (B). In Dijkstra's algorithm at each point we choose the smallest weight edge which starts from any one of the
vertices in the shortest path found so far and add it to the shortest path.
-- gate_asp ( 483 points)

4 votes

1.65 Graph Algorithms: GATE2008-IT_47 top

gateoverflow.in/3357

Consider the following sequence of nodes for the undirected graph given below.
1. a b e f d g c
2. a b e f c g d
3. a d g e b c f
4. a d b c g e f
A Depth First Search (DFS) is started at node a. The nodes are listed in the order they are first visited. Which all of the
above is (are) possible output(s)?


A)
B)
C)
D)
gate2008-it

1 and 3 only
2 and 3 only
2, 3 and 4 only
1, 2 and 3 only

algorithms

graph-algorithms

normal

Selected Answer

Answer: B
1. After f is visited, c or g should be visited next. So, the traversal is incorrect.
4. After c is visited, e or f should be visited next. So, the traversal is incorrect.
2 and 3 are correct.
2 votes

-- Rajarshi Sarkar ( 27781 points)

option B)
2 votes

1.66 Graph Algorithms: GATE2006_12 top

Copyright GATE Overflow. All rights reserved.

-- Laxmi ( 683 points)

gateoverflow.in/891

GATE Overflow

April 2016

54 of 1876

To implement Dijkstras 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
gate2006

algorithms

graph-algorithms

easy

Answer is A) Queue
we can find single source shortest path in unweighted graph by using Breadth first search (BFS) algorithm which using
"Queue" data structure , which time O(m+n) (i.e. linear with respect to the number of vertices and edges. )
-- Mithlesh Upadhyay ( 2633 points)

8 votes

1.67 Graph Algorithms: GATE2014-3_13 top

gateoverflow.in/2047

Suppose depth rst search is executed on the graph below starting at some unknown vertex. Assume that a recursive call to visit a vertex is made only after rst
checking that the vertex has not been visited earlier. Then the maximum possible recursion depth (including the initial call) is _________.

gate2014-3

algorithms

graph-algorithms

numerical-answers

normal

Selected Answer

19. apply DFS.


-- Gate Keeda ( 16619 points)

7 votes

1.68 Graph Algorithms: GATE1998_1.21 top

gateoverflow.in/1658

Which one of the following algorithm design techniques is used in finding all pairs of shortest distances in a graph?
A. Dynamic programming
B. Backtracking
C. Greedy
D. Divide and Conquer

gate1998

algorithms

graph-algorithms

easy

Selected Answer

Answer is A because floyd warshall algorithm used to find all shortest path which is a dynamic programming approach.
2 votes

Copyright GATE Overflow. All rights reserved.

-- shashi shekhar ( 327 points)

GATE Overflow

April 2016

1.69 Graph Algorithms: GATE2004-IT_56 top

55 of 1876

gateoverflow.in/3699

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)
B)
C)
D)

(E, G), (C, F), (F, G), (A, D), (A, B), (A, C)
(A, D), (A, B), (A, C), (C, F), (G, E), (F, G)
(A, B), (A, D), (D, F), (F, G), (G, E), (F, C)
(A, D), (A, B), (D, F), (F, C), (F, G), (G, E)

gate2004-it

algorithms

graph-algorithms

normal

Selected Answer

Answer is (D)
(A) and (B) produce disconnected components with the GIVEN order in options which is NEVER allowed by
prims's algorithm.
(C) produces connected component every instant a new edge is added BUT when first vertex is chosen(first
vertex is chosen randomly) first edge must be the minimum weight edge that is chosen . Therefore (A,D)
MUST be chosen BEFORE (A,B). Therefore (C) is FALSE

-- Sandeep_Uniyal ( 5063 points)

4 votes

1.70 Graph Algorithms: GATE2001_2.14 top

gateoverflow.in/732

Consider an undirected unweighted graph G. Let a breadth-first traversal of G be done starting from a node r. Let d(r,u) and
d(r,v) be the lengths of the shortest paths from r to u and v respectively in G. if u visited before v during the breadth-first
traversal, which of the following statements is correct?
A. d(r, u) < d(r, v)
B. d(r, u) > d(r, v)
C. d(r, u) d(r, v)
D. None of the above

gate2001

algorithms

graph-algorithms

Selected Answer

Ans :->
C.

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

56 of 1876

BFS is used to count shortest path from source (If all path costs are 1 !)
now if u is visited before v it means 2 things.
1. Either u is closer to v.
2. if u & v are same distance from r, then our BFS algo chose to visit u before v.
-- Akash ( 26265 points)

2 votes

1.71 Graph Algorithms: GATE2005-IT_84a top

gateoverflow.in/3856

A sink in a directed graph is a vertex i such that there is an edge from every vertex j i to i and there is no edge from i to
any other vertex. A directed graph G with n vertices is represented by its adjacency matrix A, where A[i] [j] = 1 if there is
an edge directed from vertex i to j and 0 otherwise. The following algorithm determines whether there is a sink in the graph
G.

i = 0;
do {
j = i + 1;
while ((j < n) && E1) j++;
if (j < n) E2;
} while (j < n);
flag = 1;
for (j = 0; j < n; j++)
if ((j! = i) && E3) flag = 0;
if (flag) printf("Sink exists");
else printf ("Sink does not exist");

Choose the correct expressions for E 1 and E 2



A)

E1 : A[i][j] and E 2 : i = j;

B)

E1 : !A[i][j] and E 2 : i = j + 1;

C)

E1: !A[i][j] and E 2 : i = j;

D)

E1 : A[i][j] and E 2 : i = j + 1;

gate2005-it

algorithms

graph-algorithms

normal

Selected Answer

If there is a sink in the graph, the adjacency matrix will contain all 1's (except diagonal) in one column and all 0's (except
diagonal) in the corresponding row of that vertex. The given algorithm is a smart way of doing this as it finds the sink in
O(n) time complexity.
The first part of the code, is finding if there is any vertex which doesn't have any outgoing edge to any vertex coming
after it in adjacency matrix. The smart part of the code is E2, which makes rows skip when there is no edge from i to it,
making it impossible them to form a sink. This is done through
E1: !A[i][j]
and
E2: i = j;
E1 makes sure that there is no edge from i to j and i is a potential sink till A[i][j] becomes 1. If A[i][j] becomes 1, i can no
longer be a sink, similarly all previous j can also not be a sink (as there was no edge from i to them and a sink requires an
edge from all other vertices). Now, the next potential candidate for sink is j. So, in E2, we must make i = j.
So, answer is (C)
For E3,
http://gateoverflow.in/3857/gate2005-it_84b
3 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

57 of 1876

1.72 Graph Algorithms: GATE2005-IT_84b top

gateoverflow.in/3857

A sink in a directed graph is a vertex i such that there is an edge from every vertex j i to i and there is no edge from i to
any other vertex. A directed graph G with n vertices is represented by its adjacency matrix A, where A[i] [j] = 1 if there is
an edge directed from vertex i to j and 0 otherwise. The following algorithm determines whether there is a sink in the graph
G.

i = 0;
do {
j = i + 1;
while ((j < n) && E1) j++;
if (j < n) E2;
} while (j < n);
flag = 1;
for (j = 0; j < n; j++)
if ((j! = i) && E3) flag = 0;
if (flag) printf("Sink exists") ;
else printf ("Sink does not exist");

Choose the correct expression for E3



A) (A[i][j] && !A[j][i])
B) (!A[i][j] && A[j][i])
C) (!A[i][j] | | A[j][i])
D) (A[i][j] | | !A[j][i])
gate2005-it

algorithms

graph-algorithms

normal

Selected Answer

If there is a sink in the graph, the adjacency matrix will contain all 1s (except diagonal) in one column and all 0s (except
diagonal) in the corresponding row of that vertex. The given algorithm is a smart way of doing this as it finds the sink in
O(n) time complexity.
The first part of the code, is finding if there is any vertex which does not have any outgoing edge to any vertex coming
after it in adjacency matrix. The smart part of the code is E2, which makes rows skip when there is no edge from i to it,
making it impossible them to form a sink. This is done through
E1: !A[i][j]
and
E2: i = j;
E1 makes sure that there is no edge from i to j and i is a potential sink till A[i][j] becomes 1. If A[i][j] becomes 1, i can no
longer be a sink, similarly all previous j can also not be a sink (as there was no edge from i to them and a sink requires an
edge from all other vertices). Now, the next potential candidate for sink is j. So, in E2, we must make i = j.
Now, the loop breaks when we found a potential sink- that is a vertex which does not have any outgoing edge to any
coming after it in adjacency matrix. So, if the column in which this vertex comes is all 1s and the row is all 0s (except
diagonal), this is the sink. Otherwise there is no sink in the graph. So, E3 is checking this condition.
But in the code flag is used for storing the state that sink is present or not. And as per the usage of flag in code, by default
sink is considered present. So, the condition in E3 must make flag = 0, if the found i is not a sink. So, the condition
should be:
A[i][j] || !A[j][i]
So, (D) is the answer.
4 votes

-- Arjun Suresh ( 124085 points)

Everything is well explained no need to add something new but at final answer for E3 is wrong somehow.
Lemme correct it with the concept of
"Logics"
A vertex would be sink iff there is an edge from every vertex to this vertex and there are not a single edge from this
vertex to some other.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

58 of 1876

Now at E3 we have to tell condition for a non-sink vertex..


!(p and q) equals !p or !q
A vertex i would not be sink iff either there is an edge from it to some other vertex or there is atleast one vertex that dont
have any edge to i.
So i mean answer is D.
-- Rupie_c ( 263 points)

1 votes

1.73 Graph Algorithms: GATE2014-1_11 top

gateoverflow.in/1771

Let G be a graph with n vertices and m edges.What is the tightest upper bound on the running time of Depth First Search on G, when G is represented as an
adjacency matrix?


(A) (n)
(B) (n + m)
(C) (n2 )
(D) (m2 )

gate2014-1

algorithms

graph-algorithms

normal

Selected Answer

Ans (C)
http://web.eecs.utk.edu/~huangj/CS302S04/notes/graph-searching.html
-- Keith Kr ( 5467 points)

4 votes

1.74 Graph Algorithms: Gate2000_2.19 top

gateoverflow.in/4208

Let G be an undirected graph. Consider a depth-first traversal of G, and let T be the resulting depth-first search tree. Let u
be a vertex in G and let v be the first new (unvisited) vertex visited after visiting u in the traversal. Which of the following
statement is always true?
A. {u, v} must be an edge in G, and u is a descendant of v in T
B. {u, v} must be an edge in G, and v is a descendant of u in T
C. If {u, v} is not an edge in G then u is a leaf in T
D. If {u, v} is not an edge in G then u and v must have the same parent in T

gate2000

algorithms

graph-algorithms

normal

Selected Answer

C is the correct answer..because it may happen that we read vertex u(leaf node) and hit a dead end and backtracking to
vertex y(say) then searching for possibilites we read v ..so it is nt the case that u,v must have any descendant relationship
.. You can try with random graphs and arrive at the same conclusion
8 votes

Copyright GATE Overflow. All rights reserved.

-- Bhagirathi Nayak ( 10239 points)

GATE Overflow

April 2016

59 of 1876

let this be the dfs order of tree then


u= D and v = F
so what we conclude
1. its not necessary their is edge b/w them .
2. if thier is no edge then u must be leaf i.e. D is leaf here.
3. it not always possible u and v have same parent . but they have same ancestor .

-- Anirudh Pratap Singh ( 4093 points)

4 votes

1.75 Graph Algorithms: GATE2002_12 top

gateoverflow.in/865

Fill in the blanks in the following template of an algorithm to compute all pairs shortest path lengths in a directed graph G
with n*n adjacency matrix A. A[i,j] equals 1 if there is an edge in G from i to j, and 0 otherwise. Your aim in filling in the
blanks is to ensure that the algorithm is correct.
INITIALIZATION: For i = 1 ... n
{For j = 1 ... n
{ if a[i,j] = 0 then P[i,j] =_______ else P[i,j] =_______;}
}
ALGORITHM: For i = 1 ... n
{For j = 1 ... n
{For k = 1 ... n
{P[__,__] = min{_______,______}; }
}
}

a. Copy the complete line containing the blanks in the Initialization step and fill in the blanks.
b. Copy the complete line containing the blanks in the Algorithm step and fill in the blanks.
c. Fill in the blank: The running time of the Algorithm is O(___).

gate2002

algorithms

graph-algorithms

time-complexity

normal

INITIALIZATION: For i = 1 ... n


{For j = 1 ... n
{ if a[i,j] = 0 then P[i,j] =____infinite___ else P[i,j] =____a[i,j]___;}
}
ALGORITHM: For i = 1 ... n
{For j = 1 ... n
{For k = 1 ... n
{P[__i,_j_] = min(_p[i,j]______,_p[i,k]+p[k,j]_____)};
}
}
time coplexity 0(n^3)
this algorithm is 4 weighted graph but it will work 4 unweighted graph 2 because if p[i,j]=1, p[i,k]=1 and p[k,j]=1 then
according to the algo p[i,j] = min(p[i,j],p[i,k]+p[k,j]) =min(1,2) =1
nd all the other case is also satisfied.(ike as if p[i,j] was 0 in last iteration nd there exist a path via k)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

60 of 1876

-- Saurav Kumar Gupta ( 1445 points)

2 votes

1.76 Graph Algorithms: GATE2003_67 top

gateoverflow.in/954

Let G = (V,E) be an undirected graph with a subgraph G 1 = (V1 , E1 ). Weights are assigned to edges of G as follows.

w(e) =

0 if e E1
1 otherwise

A single-source shortest path algorithm is executed on the weighted graph ( V,E,w) with an arbitrary vertex v1 of V1 as the
source. Which of the following can always be inferred from the path costs computed?

A. The number of edges in the shortest paths from v1 to all vertices of G
B. G 1 is connected
C. V1 forms a clique in G
D. G 1 is a tree

gate2003

algorithms

graph-algorithms

normal

Selected Answer

After applying the shortest path algorithm, check cost of vertex from source to every vertex in G 1 . If G 1 is connected all
these costs must be 0 as edge weights of subgraph G 1 is 0 and that should be the shortest path. If cost is not 0, to at least
one vertex in G 1 (not necessarily G), then G 1 is disconnected.
Ans is b
-- Anurag Semwal ( 4775 points)

6 votes

Ans is (B)
When we compute shortest path from one of the vertex v1 in V1.Then we can infer as
G1 is connected if the cost from v1 to any other vertex in V1 is 1.
G1 is disconnected otherwise
-- Khushboo Tak ( 1961 points)

4 votes

1.77 Graph Algorithms: GATE2003_70 top

gateoverflow.in/957

Let G = (V, E) be a directed graph with n vertices. A path from vi to vj in $G$ is a sequence of vertices (vi, vi +1 , , vj) such that
(vk, vk + 1) E for all k in i through j 1. A simple path is a path in which no vertex appears more than once.
Let A be an n n array initialized as follows.
A[j, k] =
Consider the following algorithm.
for i=1 to n
for j=1 to n
for k=1 to n
A[j,k] = max(A[j,k], A[j,i] + A[i,k]);

Copyright GATE Overflow. All rights reserved.

1 if (j, k) E
0 otherwise

GATE Overflow

April 2016

61 of 1876

Which of the following statements is necessarily true for all j and k after termination of the above algorithm?
A. A[j, k] n
B. If A[j, j] n 1 then G has a Hamiltonian cycle
C. If there exists a path from j to k, A[j,k] contains the longest path length from j to k
D. If there exists a path from j to k, every simple path from j to k contains at most A[j,k] edges


gate2003

algorithms

graph-algorithms

normal

D is correct.
Consider a graph with 2 nodes and one edge from to V1 and V2 ,
Running the above algorithm will result in A being
A

1
2

1
1

2
2

Clearly options B and C are wrong. Since


1. A[1][1] and A[2][2] > n-1 and there exists no Hamiltonian cycle. Hence invalid
2. The longest path between V1 and V2 is 1, but A[1][2] is 2, which is invalid. And no path between V2 and V1 yet A[2]
[1] = 1
Hence A or D could be valid.
Now consider a graph with 2 nodes and two edges, one from V1 and V2 and other form V2 and V1 . Running the above
algorithm will result in A being
A
1

1
2

2
3

Hence option A is invalid, as A[i][j] can be >n


D is correct
3 votes

-- ryan sequeira ( 1011 points)

Solution:D
Tracing this algorithm on a simple graph with two nodes(with only one edge form node 1 to node 2) revels that the only
statement that can be true about this algorith is D.
1 votes

1.78 Graph Algorithms: GATE2014-2_14 top

-- Gowthaman Arumugam ( 1079 points)

gateoverflow.in/1969

Consider the tree arcs of a BFS traversal from a source node W in an unweighted, connected, undirected graph. The tree T formed by the tree arcs is a data
structure for computing
(A) the shortest path between every pair of vertices.
(B) the shortest path from W to every vertex in the graph.
(C) the shortest paths from W to only those nodes that are leaves of T.
(D) the longest path in the graph.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

gate2014-2

algorithms

graph-algorithms

62 of 1876

normal

Selected Answer

BFS always having starting node. It does not calculate shortest path between every pair but it computes shorted path
between W and any other vertex ..
-- Digvijay Pandey ( 26235 points)

2 votes

1.79 Graph Algorithms: GATE2006_48 top

gateoverflow.in/1824

Let T be a depth first search tree in an undirected graph G. Vertices u and are leaves of this tree T. The degrees of both u
and in G are at least 2. which one of the following statements is true?
(A) There must exist a vertex w adjacent to both u and in G
(B) There must exist a vertex w whose removal disconnects u and in G
(C) There must exist a cycle in G containing u and
(D) There must exist a cycle in G containing u and all its neighbours in G.
gate2006

algorithms

graph-algorithms

normal

I think Ans Is D..??


Is it Correct or not please leave comment..
1 votes

-- Nikunj Vinchhi ( 21 points)

I took many examples and didnt understand the question for half an hour.
But now i realise, on reading clearly. its very easy and direct.
A LEAF. in a DFS TREE. has degree two.
Another LEAF. in a DFS TREE. has degree two.
Both can be non adjacent leaves also.
It implies that if a LEAF has degree two then it will form a cycle.
Since it is non adjacent leaves that have cycle. so Option C may be wrong.
Hence option D.
1 votes

1.80 Graph Algorithms: GATE2003_21 top


Consider the following graph

Among the following sequences


I. abeghf
II. abfehg
III. abfhge
IV. afghbe

Copyright GATE Overflow. All rights reserved.

-- Aspi R Osa ( 1305 points)

gateoverflow.in/911

GATE Overflow

April 2016

63 of 1876

which are depth first traversals of the above graph?


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

gate2003

algorithms

graph-algorithms

normal

In dfs think of a stack as if every adjacent node is being put on top of it lifo and chosen randomly while in bfs think of a
queue i.e.fifo here option d.
-- anshu ( 2155 points)

1 votes

1.81 Graph Algorithms: TIFR2013-B-15 top

gateoverflow.in/25798

Let G be an undirected graph with n vertices. For any subset S of vertices, the set of neighbours of S consists of the union of
S and the set of vertices S that are connected to some vertex in S by an edge of G. The graph G has the nice property that
every subset of vertices S of size at most n/2 has at least 1.5 | S | -many neighbours. What is the length of a longest path in G?
a. O(1)
b. O(loglogn) but not O(1)
c. O(logn) but not O(loglogn)

(n ) but not O(logn)


e. O(n) but not O ( n )
d. O

tifr2013

graph-algorithms

Here we have to find the longest path in Graph.


Let's start with 1 node(chose any one) & find the number of hops in which whole Graph is reachable i.e. all
the n vertices are reachable.
From First node (say A) -
(1) within 1 hop(1 edge traversal) we can reach atleast = 3/2 nodes
{as neighbourhood of A has atleast 3/2 nodes}
3

()
()
()

(2) within 2 hops we can reach atleast

(3) within 3 hops we can reach atleast

3
3
2

nodes

nodes

and so on.. like this when our nodes reach

()

within 1 more hop we can reach upto

3n

nodes..

3n

uptill here we will take O(log n) hops {to reach 4 nodes}.


But this property is valid upto a subset of size atmost n/2 .. so, here I stuck to proceed..
Hope it helps.. Also any suggestions to proceed further are welcome..
0 votes

Copyright GATE Overflow. All rights reserved.

-- Himanshu Agarwal ( 8861 points)

GATE Overflow

April 2016

64 of 1876

1.82 Graph Algorithms: GATE2008_7 top

gateoverflow.in/405

The most efficient algorithm for finding the number of connected components in an undirected graph on n vertices and m
edges has time complexity
(A) (n)
(B) (m)
(C) (m + n)
(D) (mn)
gate2008

algorithms

graph-algorithms

time-complexity

normal

Selected Answer

Run DFS to find connected components. Its time complexity is (m + n), hence (C) is the answer.
-- Happy Mittal ( 9253 points)

9 votes

1.83 Graph Search: GATE2015-1_45 top

gateoverflow.in/8321

Let G = (V, E) be a simple undirected graph, and s be a particular vertex in it called the source. For x V, let d(x) denote the
shortest distance in G from s to x. A breadth first search (BFS) is performed starting at s. Let T be the resultant BFS tree. If
(u, v) is an edge of G that is not in T, then which one of the following CANNOT be the value of d(u) d(v)?
A. 1
B. 0
C. 1
D. 2

gate2015-1

algorithms

graph-search

bfs

normal

Selected Answer

2 is the answer.
d(u) d(v) = 0 is possible when both u and v have an edge from t and t is in the shortest path from s to u or v.
d(u) d(v) = 1 is possible when v and t are in the shortest path from s to u and both t and v are siblings- same distance from s
to both t and v causing t u edge to be in BFS tree and not v u.
d(u) d(v) = 1 is possible as explained above by interchanging u and v.
d(u) d(v) = 2 is not possible. This is because on BFS traversal we either visit u first or v. Let's take u first. Now, we put all
neighbors of u on queue. Since v is a neighbour and v is not visited before as assumed, d(v) will become d(u) + 1. Similarly,
for v being visited first.
10 votes

(B)Take distance from S


d(U) =1 from S
d(V)=1 from S
So, d(U) - d(V) =0 , d(X) is one shortest distance of the graph
and BFS traversal will not take edge UV

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

65 of 1876

(C) Now for assuming d(U) and d(V) has a distance 1, we similarly calculate the distance from S(in next figure)

(A)In previous figure change the position of U and V, so get


d(U)-d(V) = -1
(D) but 2 not possible as there is a direct edge from U to V always, So, no graph possible with min distance 2. The max
distance could be 1
So, ans is (D)
-- srestha ( 11537 points)

3 votes

option d... thanku arjun sir


-- Anoop Sonkar ( 4167 points)

2 votes

answer is d
-- naresh1845 ( 1135 points)

2 votes

1.84 Greedy Algorithm: GATE2005_84 top

gateoverflow.in/1406

Statement for the Linked Answer Questions 84a & 84b:


We are given 9 tasks T1 , T2 , , T9 . The execution of each task requires one unit of time. We can execute one task at a time.
Each task Ti has a profit Pi and a deadline di. Profit Pi is earned if the task is completed before the end of the dth
i unit of time.
Task

T1

T2

T3

T4

T5

T6

T7

T8

T9

Profit

15

20

30

18

18

10

23

16

25

Deadline


(A) Are all tasks completed in the schedule that gives maximum profit?

A. All tasks are completed
B. T1 and T6 are left out
C. T1 and T8 are left out
D. T4 and T6 are left out

(B) What is the maximum profit earned?

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

66 of 1876


A. 147
B. 165
C. 167
D. 175

gate2005

algorithms

greedy-algorithm

process-schedule

normal

Selected Answer

The most important statement in question is

each task requires one unit of time


This shows that we can greedily choose the better task and that should give us the optimal solution. The best task would
be the one with maximum profit. Thus we can sort the tasks based on deadline and then profit as follows:
Task

T7

T2

T9 T4

T5

T3

T6

T8

T1

Deadline

a) 0 ----T7 ----- 1----T2-----2-----T9-----3-----T5-----4-----T3-----5-----T8-----6-----T1------7


T4 and T6 left out
b) profit=147
-- Pooja ( 22745 points)

4 votes

1.85 Hashing: GATE2015-2_33 top

gateoverflow.in/8152

Which one of the following hash functions on integers will distribute keys most uniformly over 10 buckets numbered 0 to 9
for i ranging from 0 to 2020?

A. h(i) =
B. h(i) =
C. h(i) =
D. h(i) =

gate2015-2

i2 mod 10
i3 mod 10
(11 i2 )mod 10
(12 i2 )mod 10
algorithms

hashing

normal

Selected Answer

Since mod 10 is used, the last digit matters.


If you do cube all numbers from 0 to 9, you get following

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

67 of 1876

Number Cube Last Digit in Cube


0 0 0
1 1 1
2 8 8
3 27 7
4 64 4
5 125 5
6 216 6
7 343 3
8 512 2
9 729 9

Therefore all numbers from 0 to 2020 are equally divided in 10 buckets. If we make a table for square, we dont get equal
distribution. In the following table. 1, 4, 6 and 9 are repeated, so these buckets would have more entries and buckets 2,
3, 7 and 8 would be empty.

Number Square Last Digit in Cube


0 0 0
1 1 1
2 4 4
3 9 9
4 16 6
5 25 5
6 36 6
7 49 9
8 64 4
9 81 1

http://geeksquiz.com/gate-gate-cs-2015-set-2-question-43/
-- Anu ( 6733 points)

7 votes

Ans B, all numbers are generated in this, if you have any doubt check this
-- Vikrant Singh ( 10051 points)

4 votes

1.86 Hashing: GATE2007_40 top

gateoverflow.in/1238

Consider a hash table of size seven, with starting index zero, and a hash function (3x + 4) mod 7. Assuming the hash table is
initially empty, which of the following is the contents of the table when the sequence 1, 3, 8, 10 is inserted into the table
using closed hashing? Note that denotes an empty location in the table.

A. 8, , , , , , 10
B. 1, 8, 10, , , , 3
C. 1, , , , , , 3
D. 1, 10, 8, , , , 3

gate2007

algorithms

hashing

easy

Selected Answer

The answer is B.
1 will occupy location 0, 3 will occupy location 6, 8 hashed to location 0 which is already occupied so, it will be hashed

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

68 of 1876

to one location next to it. i.e. to location 1.


Since 10 also clashes, so it will be hashed to location 2.
-- Gate Keeda ( 16619 points)

3 votes

1.87 Heap: GATE2013_30 top

gateoverflow.in/1541

The number of elements that can be sorted in (logn) time using heap sort is
log n

(A) (1) (B) ( logn) (C) ( log log n ) (D) (logn)

gate2013

algorithms

sorting

heap

normal

Selected Answer

log n

To sort k elements in a heap, complexity is (klogk). Lets assume there are log log n elements in the heap.

log n

log n

Complexity = log log n log log log n

log n

= log log n (loglogn logloglogn)


log nlog log log n

log log n

= logn

))

= (logn) (as shown below)


So, (c) is the answer.

loglogn > logloglogn


log log log n

log log n

<1

log nlog log log n


log log n

 logn

< logn

log nlog log log n


log log n

26 votes

answer = option C

Copyright GATE Overflow. All rights reserved.

= (logn)

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

69 of 1876

-- Amar Vashishth ( 17735 points)

4 votes

1.88 Heap: GATE2007_47 top

gateoverflow.in/1245

Consider the process of inserting an element into a Max Heap, where the Max Heap is represented by an array. Suppose we
perform a binary search on the path from the new leaf to the root to find the position for the newly inserted element, the
number of comparisons performed is:

A. (log2 n)
B. (log2 log2 n)
C. (n)
D. (nlog2 n)

gate2007

algorithms

time-complexity

heap

normal

Selected Answer

number of elements in the path from new leaf to root = log n, and all elements are sorted from leaf to root so we can do a
binary search which will result in O(log log n) number of comparisons.
Since in heap is a complete binary tree, in an array implementation, from every node index, we can know its depth and
this will be the n for binary search.
-- Vikrant Singh ( 10051 points)

6 votes

1.89 Heap: GATE2003_23 top

gateoverflow.in/1110

In a min-heap of size n the 7 th smallest element can be found in

gate2003

algorithms

data-structure

heap

time-complexity

Selected Answer

Time to find the smallest element on a min-heap- one retrieve operation - (1)
Time to find the second smallest element on a min-heap- requires 22 1 = 3 check operations to find the second smallest
element out of 3 elements - (1)
Time to find the 7 th smallest element - requires O(27 1) = O(127) check operations to find the seventh smallest element out
of 127 possible ones - (1)
In short if the number of required operations is independent of the input size n, then it is always (1).
(Here, we are doing a level order traversal of the heap and checking the elements)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

70 of 1876

If we are not allowed to traverse the heap and allowed only default heap-operations, we will be restricted with doing
Extract-min 7 times which would be O(logn).
-- gatecse ( 9515 points)

17 votes

The 7th most element is always within the 7 levels from the root so we have constant number of nodes in worst condition
.we need to check only constant number of nodes to find the 7th smallest number so constant time
-- Bhagirathi Nayak ( 10239 points)

5 votes

1.90 Heap: TIFR2011-B-21 top


Let S =

gateoverflow.in/20324

{x1, . . . . , xn } be a set of n numbers. Consider the problem of storing the elements of S in an array A[1...n] such that the

following min-heap property is maintained for all 2 i n:A[i/2] A[i]. (Note that x is the largest integer that is at
most x). Which of the following statements is TRUE?
a. This problem can be solved in O(logn) time.
b. This problem can be solved in O(n) time but not in O(logn) time.
c. This problem can be solved in O(nlogn) time but not in O(n) time.

( )

d. This problem can be solved in O n2 time but not in O(nlogn) time.


e. None of the above.
tifr2011

algorithms

sorting

heap

Selected Answer

store the elements in an array and then call build_heap(A). the build_heap takes O(n) time.
so, option 'b' is correct.
but, if we try building heap by inserting each element one by one, the total complexity will be then O(n log n). cause
insertion takes O(log n) and inserting 'n' elements will take O(n log n).
-- Sujit Kumar Muduli ( 169 points)

5 votes

1.91 Huffman Code: GATE2007-77 top


1 1 1

gateoverflow.in/43513

2 4 8 16 32 32

Suppose the letters a, b, c, d, e, f have probabilities , , ,

What is the average length of the correct answer to Q.76?


A. 3
B. 2.1875
C. 2.25
D. 1.9375
gate2007

algorithms

huffman-code

Selected Answer

Ans should be D)

Copyright GATE Overflow. All rights reserved.

normal

, respectively.

GATE Overflow

April 2016

71 of 1876

-- sonam vyas ( 6439 points)

2 votes

1.92 Huffman Code: GATE2006-IT_48 top

gateoverflow.in/3591

The characters a to h have the set of frequencies based on the first 8 Fibonacci numbers as follows
a : 1, b : 1, c : 2, d : 3, e : 5, f : 8, g : 13, h : 21
A Huffman code is used to represent the characters. What is the sequence of characters corresponding to the following code?
110111100111010

A)
fdheg
B)
ecgdf
C)
dchfg
D)
fehdg
gate2006-it

algorithms

huffman-code

normal

Selected Answer

Answer is A. Huffman's tree is as follows. The two least frequent characters are taken as the children of a newly made
node and the frequency of the newly made node is made equal to the sum of those two child nodes. Then the same
procedure is repeated till all nodes are finished.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

72 of 1876

110111100111010 = 110 11110 0 1110 10 = fdheg


-- Arjun Suresh ( 124085 points)

2 votes

1.93 Huffman Code: GATE2007-76 top


1 1 1

gateoverflow.in/1271

Suppose the letters a, b, c, d, e, f have probabilities 2 , 4 , 8 , 16 , 32 , 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
gate2007

algorithms

huffman-code

normal

Selected Answer

Based on the probabilities, we can say the probable frequency of the letters will be

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

73 of 1876

16, 8, 4, 2, 1, 1
Now, the Huffman tree can be constructed as follows:


So, A is the answer for 76.
https://www.siggraph.org/education/materials/HyperGraph/video/mpeg/mpegfaq/huffman_tutorial.html
4 votes

1.94 Identify Function: GATE2005_31 top


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("%d\n", sum);
}

What does the above program print?


Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/1367

GATE Overflow

April 2016

74 of 1876

A. 8, 4, 0, 2, 14
B. 8, 4, 0, 2, 0
C. 2, 0, 4, 8, 14
D. 2, 0, 4, 8, 0

gate2005

algorithms

identify-function

recursion

normal

Selected Answer

Option d.
foo is printing the lowest digit. But the printf inside it is after the recursive call. This forces the output to be in reverse
order
2, 0, 4, 8
The final value "sum" printed will be 0 as C uses pass by value and hence the modified value inside foo won't be visible
inside main.
-- anshu ( 2155 points)

6 votes

1.95 Identify Function: GATE2014-2_10 top

gateoverflow.in/1964

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 ________

gate2014-2

algorithms

identify-function

numerical-answers

easy

Selected Answer

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

8 >> 1 = 4 // In binary: (00001000) >> 1 = (00000100)



3 votes

1.96 Identify Function: GATE2013_31 top


Consider the following function:

Copyright GATE Overflow. All rights reserved.

-- Prasanna Ranganathan ( 2051 points)

gateoverflow.in/1542

GATE Overflow

April 2016

75 of 1876

int unknown(int n){


int i, j, k=0;
for (i=n/2; i<=n; i++)
for (j=2; j<=n; j=j*2)
k = k + n/2;
return (k);
}

The return value of the function is


(A) (n2 ) (B) (n2 logn) (C) (n3 ) (D) (n3 logn)

gate2013

algorithms

identify-function

normal

Selected Answer

The outer loop is running for n/2 times and inner loop is running for log 2 n times (each iteration doubles j and j stops at n
means log2 n times j loop will iterate).
Now in each iteration k is incremented by n/2. So, overall k will be added n/2 * log n * n/2 with an initial value of 0. So,
final value of k will be (n 2 log n)
-- Arjun Suresh ( 124085 points)

9 votes

1.97 Identify Function: GATE1993_7.4 top

gateoverflow.in/2292

What does the following code do?


var a, b: integer;
begin
a:=a+b;
b:=a-b;
a:a-b;
end;


A. exchanges a and b
B. doubles a and stores in b
C. doubles b and stores in a
D. leaves a and b unchanged
E. none of the above


gate1993

algorithms

identify-function

easy

Selected Answer

Answer is simply A i.e. it swaps the values of the two.. Take any two values for A and B. and perform the given operations
over them.
7 votes

-- Gate Keeda ( 16619 points)

(a)
initially a = 10 b = 5
a = 15
b = 10
a = 5
1 votes

Copyright GATE Overflow. All rights reserved.

-- Manu Thakur ( 5261 points)

GATE Overflow

April 2016

1.98 Identify Function: GATE1998_2.12 top

76 of 1876

gateoverflow.in/1684

What value would the following function return for the input x = 95?
Function fun (x:integer):integer;
Begin
If x > 100 then fun := x 10
Else fun := fun(fun (x+11))
End;

A. 89
B. 90
C. 91
D. 92


gate1998

algorithms

recursion

identify-function

normal

Selected Answer

value
return
by
fun(95) = fun(fun(106)) = fun(96) = fun(fun(107)) = fun(97) = fun(fun(108)) = fun(98) = fun(fun(109)) = fun(99) = fun(fun(110)) = fun(100) = fun(fun(111)) = fun(101
-- Digvijay Pandey ( 26235 points)

7 votes

1.99 Identify Function: GATE2011-48 top

gateoverflow.in/2154

Consider the following recursive C function that takes two arguments.


unsigned int foo(unsigned int n, unsigned int r) {
if (n>0) return ((n%r) + foo(n/r, r));
else return 0;
}

What is the return value of the function foo when it is called as foo(345, 10)?
A. 345
B. 12
C. 5
D. 3

gate2011

algorithms

recursion

identify-function

normal

Selected Answer

A) The function returns the sum of digits of the given number.


so 5+4+3 = 12
5 votes

1.100 Identify Function: GATE2010_35 top


What is the value printed by the following C program?
#include<stdio.h>
int f(int *a, int n)
{
if (n <= 0) return 0;
else if (*a % 2 == 0) return *a+f(a+1, n-1);
else return *a - f(a+1, n-1);
}
int main()

Copyright GATE Overflow. All rights reserved.

-- Danish ( 1967 points)

gateoverflow.in/2336

GATE Overflow
{

April 2016

77 of 1876

int a[] = (12, 7, 13, 4, 11, 6);


printf("%d", f(a, 6));
return 0;


(A) -9
(B) 5
(C) 15
(D) 19

gate2010

algorithms

recursion

identify-function

normal

Selected Answer

It will print
12 + ( 7 - (13 - (4 + (11 - ( 6 + 0)))))
= 12 + (7 - (13 - ( 4 + ( 11 -6)))))
= 12 + 7 - 13 + 9
= 15
-- gatecse ( 9515 points)

8 votes

it is C. 15.
-- Gate Keeda ( 16619 points)

3 votes

1.101 Identify Function: GATE2014-3_10 top

gateoverflow.in/2044

Let A be the square matrix of size n n. Consider the following pseudocode. What is the expected output?
C=100;
for i=1 to n do
for j=1 to n do
{
Temp = A[i][j]+C;
A[i][j] = A[j][i];
A[j][i] = Temp -C;
}
for i=1 to n do
for j=1 to n do
output (A[i][j]);

(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 A
(D) None of the above

gate2014-3

algorithms

identify-function

easy

Selected Answer

A.
In the computation of given pseudo code for each row and column of Matrix A, each upper
triangular element will be interchanged by its mirror image in the lower triangular and after
that the same lower triangular element will be again re-interchanged by its mirror image in
the upper triangular, resulting the final computed Matrix A same as input Matrix A.
8 votes

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

GATE Overflow

April 2016

78 of 1876

take a small matrix


[a b]
[c d]
it will give
[a c
b+100 d]
for first row iterated
[a b + 100 -100
c d]
for second row iterated.
hence answer A.
-- Aspi R Osa ( 1305 points)

1 votes

1.102 Identify Function: GATE1999_2.24 top

gateoverflow.in/1501

Consider the following C function definition


int Trial (int a, int b, int c)
{
if ((a>=b) && (c<b) return b;
else if (a>=b) return Trial(a, c, b);
else return Trial(b, a, c);
}

The functional Trial:



A. Finds the maximum of a, b, and c
B. Finds the minimum of a, b, and c
C. Finds the middle number of a, b, c
D. None of the above

gate1999

algorithms

identify-function

normal

Selected Answer

a b c Return
111

The final return statement is c < b, so this never


returns. Answer D.


9 votes

1.103 Identify Function: GATE2006_53 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/1831

Consider the following C-function in which a[n] and b[m] are two sorted integer arrays and c[n+m] be another integer
array,
void xyz(int a[], int b [], int c []){
int i,j,k;
i=j=k=0;
while ((i<n) && (j<m))
if (a[i] < b[j]) c[k++] = a[i++];
else c[k++] = b[j++];
}

Which of the following condition(s) hold(s) after the termination of the while loop?

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

79 of 1876

i. j < m, k = n + j 1 and a[n 1] < b[j] if i = n


ii. i < n, k = m + i 1 and b[m 1] a[i] if j = m
(A) only (i)
(B) only (ii)
(C) either (i) or (ii) but not both
(D) neither (i) nor (ii)

gate2006

algorithms

identify-function

normal

Selected Answer

The while loop add elements from a and b (whichever is smaller) to c and terminates when either of them exhausts. So,
when loop terminates either i = n or j = m.
Suppose i = n. This would mean all elements from array a are added to c => k must be incremented by n. c would also
contain j elements from array b. So, number of elements in c would be n+j and hence k = n + j.
Similarly, when j = m, k = m + i.
Hence, option (D) is correct. (Had k started from -1 and not 0 and we used ++k inside loop, answer would have been
option (C))

-- Arjun Suresh ( 124085 points)

10 votes

Option A and B are incorrect because j<m or i<n for loop termination.
From remaining C and D , k is no of elements added in c. it would either be n+j or m+i after loop terminates
not n+j-1...
So D should be the correct answer
-- Madhur Rawat ( 2379 points)

3 votes

1.104 Identify Function: GATE2004_42 top


What does the following algorithm approximate? (Assume m > 1, > 0).
x = m;
y = 1;
While (x-y > )
{
x = (x+y)/2;
y = m/x;
}
print(x);


A. log m
B. m 2
1

C. m

2
1

D. m


gate2004

algorithms

identify-function

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/1039

GATE Overflow

April 2016

80 of 1876

by putting y = m/x into x = ( x + y )/2


x= ( x + m/x ) /2
=> 2x 2 = x2 + m
=> x = m^1/2
or we can check by putting 2-3 different values also.
-- gate_asp ( 483 points)

7 votes

1.105 Identify Function: GATE2003_88 top

gateoverflow.in/971

In the following C program fragment, j, k, n and TwoLog_n are integer variables, and A is an array of integers. The variable
n is initialized to an integer 3, and TwoLog_n is initialized to the value of 2 log2 (n)
for (k = 3; k <= n; k++)
A[k] = 0;
for (k = 2; k <= TwoLog_n; k++)
for (j = k+1; j <= n; j++)
A[j] = A[j] || (j%k);
for (j = 3; j <= n; j++)
if (!A[j]) printf("%d", j);

The set of numbers printed by this program fragment is


A. {m m n, (i)[m = i!]}

B. m m n, (i) m = i2

]}

C. {m m n, m is prime}
D. { }


gate2003

algorithms

identify-function

normal

Selected Answer

The nested loop is taking all integers from 2 to 2 * log 2 n take all their non-multiples before n, and make the
corresponding entry in A as 1. For example, for 2, and n = 10, A[3], A[5], A[7], and A[9] are made 1. Similarly for 3, 4,
... till 2 * log n. So, if any entry A[p] is 1 means it must be a multiple of 2, 3, .... 2log 2 n, which is (2 log n)! and is
greater than n. So, for no index p, A[p] will be 0. So, answer is D.
Suppose the line
A[j] = A[j] || (j%k);
is replaced with
A[j] = A[j] || !(j%k);
Now, the nested loop is taking all integers from 2 to log 2 n, take all their multiples before n, and make the corresponding
entry in A as 1. For example, for 2, and n = 10, A[4], A[6], A[8] and A[10] are made 1. Similarly for 3, 4, ... till 2 * log n.
So, for all non-prime indices of A, we will have a 1, and for prime indices we have a 0. And we print i if A[j] is 0 meaning j
is prime.
3 votes

Answer: D

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

81 of 1876

The code sets 1 at all array index after A[2].


Ref: http://ideone.com/2bsRHY
-- Rajarshi Sarkar ( 27781 points)

2 votes

1.106 Identify Function: GATE2008-IT_83 top

gateoverflow.in/3407

Consider the code fragment written in C below :



void f (int n)
{
if (n <= 1) {
printf ("%d", n);
}
else {
f (n/2);
printf ("%d", n%2);
}
}

Which of the following implementations will produce the same output for f(173) as the above code?
P1

P2

void f (int n)
{
if (n/2) {
f(n/2);
}
printf ("%d", n%2);
}

void f (int n)
{
if (n <=1) {
printf ("%d", n);
}
else {
printf ("%d", n%2);
f (n/2);
}
}



A)
B)
C)
D)
gate2008-it

Both P1 and P2
P2 only
P1 only
Neither P1 nor P2

algorithms

recursion

identify-function

normal

Selected Answer

Answer: C
The code fragment written in C and P1 prints the binary equivalent of the number n.
P2 prints the binary equivalent of the number n in reverse.
5 votes

Copyright GATE Overflow. All rights reserved.

-- Rajarshi Sarkar ( 27781 points)

GATE Overflow

April 2016

82 of 1876

here P1 and P2 will print opposite in direction as shown in diagram


and given code fragment will print like P1 and not like P2
Hence ans will be (C)
-- srestha ( 11537 points)

1 votes

ans is 3). As P1 prints 10101101 same as given code in question but P2 prints the output in reverse order.
-- Laxmi ( 683 points)

1 votes

1.107 Identify Function: GATE2008-IT_82 top


Consider the code fragment written in C below :
void f (int n)
{
if (n <=1) {
printf ("%d", n);
}
else {
f (n/2);
printf ("%d", n%2);
}
}

What does f(173) print?



1)
2)
3)
4)
gate2008-it

010110101
010101101
10110101
10101101

algorithms

recursion

Selected Answer

Copyright GATE Overflow. All rights reserved.

identify-function

normal

gateoverflow.in/3406

GATE Overflow

April 2016

83 of 1876

Answer: D
The function prints the binary equivalent of the number n.
Binary equivalent of 173 is 10101101.
6 votes

-- Rajarshi Sarkar ( 27781 points)

OUTPUT IS
10101101
i.e Option D
since recusive funtion calls will be
1st function call 173/2=86(int part only)
2nd function call 86/2 =43
3rd function call 43/2=21(int part only)
4th function call 21/2=10(int part only)
5th function call 10/2=5
6th function call 5/2=2(integer part only)
7th function call 2/2=1
now in 7th function call condition if(n<=1) will become true
so n will be printed( i.e 1 will be printed )
now while returning every function will execute its remaining part of code ie


printf ("%d", n%2);
So 6th function will print 2 mod 2 = 0
5th function will print 5 mod 2= 1
4th function will print 10 mod 2 = 0
3rd function will print 21 mod 2 = 1
2nd function will print 43 mod 2 = 1
1st function will print 86 mod 2 = 0
the main f function call will print 173 mod 2 = 1
1 votes

1.108 Identify Function: GATE2003_1 top


Consider the following C function.
For large values of y, the return value of the function f best approximates

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

A. xy
B. ex
C. ln(1 + x)

Copyright GATE Overflow. All rights reserved.

-- Kalpish Singhal ( 1575 points)

gateoverflow.in/892

GATE Overflow

April 2016

84 of 1876

D. xx


gate2003

algorithms

identify-function

normal

Selected Answer

i=1

i=2

then

then

p=1

p=

& s=1+x

x2

x2

& s=1+x+ 2

As y tends to infinity, s tends to ex.


Hence, the correct answer is option B.
-- Pooja ( 22745 points)

8 votes

1.109 Identify Function: GATE2005-IT_57 top

gateoverflow.in/3818

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)
B)
C)
D)
gate2005-it

5
8
9
20

algorithms

identify-function

normal

Selected Answer

The sequence has to be followed.


6.) f(20,1) = 9.
5.) f(10,2) - 1 = 9
4.) f(5,4) - 2 = 10
3.) f(2,8) + 4 = 12
2.) f(1,16) - 8 = 8
1.) f(0,32) + 16 = 16
4 votes

1.110 Identify Function: GATE2015-3_49 top

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

gateoverflow.in/8558

GATE Overflow

April 2016

85 of 1876

Suppose c = c[0], , c[k 1] is an array of length k, where all the entries are from the set {0, 1}. For any positive integers
a and n, consider the following pseudocode.
DOSOMETHING (c, a, n)
z1
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 _______.




gate2015-3

algorithms

identify-function

normal

numerical-answers

Selected Answer

Initially k = 4, c = [1, 0, 1, 1], a = 2, n = 8


now let's iterate through the function step by step :
z = 1 (at the start of do-something)
i = 0 (start of external for loop)
in the do loop
z = 1*1 % 8 = 1 (non zero value so considered as true and continue)
c[0] = 1 so in the if clause z = 1*2 % 8 = 2
in the do loop
z = 2*2 % 8 = 4 (since now z = 2) (non zero value so considered as true and continue)
c[0] = 1 so in the if clause z = 4*2 % 8 = 0
now no need to check further :
reason all the operations that update Z are multiplicative operations and hence the value of Z will never
change from 0.
11 votes

-- Tamojit Chatterjee ( 1925 points)

Answer is 0. By manually iterating through the steps by pencil and paper we can get this answer
4 votes

-- ppm ( 549 points)

we can do it mentally , at one stage value of z will be zero , beyond that , for any value of K it will be 0 only.
Ans :0
1 votes

1.111 Identify Function: TIFR2014-B-2 top


Consider the following code.

Copyright GATE Overflow. All rights reserved.

-- Rohan Mundhey ( 241 points)

gateoverflow.in/27136

GATE Overflow

April 2016

86 of 1876

def brian(n):
count = 0
while ( n ! = 0 )
n = n & ( n-1 )
count = count + 1
return count

Here n is meant to be an unsigned integer. The operator & considers its arguments in binary and computes their bit wise AND
. For example, 22 & 15 gives 6, because the binary (say 8-bit) representation of 22 is 00010110 and the binary representation
of 15 is 00001111, and the bit-wise AND of these binary strings is 00000110, which is the binary representation of 6. What does
the function brian return?
a. The highest power of 2 dividing n, but zero if n is zero.
b. The number obtained by complementing the binary representation of n.
c. The number of ones in the binary representation of n.
d. The code might go into an infinite loop for some n.
e. The result depends on the number of bits used to store unsigned integers.
tifr2014

algorithms

identify-function

Selected Answer


option c. It return no of 1's in binary representation of n.
here n&(n-1) reset rightmost bit of n in each iteration.
e.g
Suppose n=15=00001111(binary)
n-1=14(00001110)
00001111
^ 00001110
-------------------- 00001110

-- Avdhesh Singh Rana ( 1509 points)

4 votes

1.112 Identify Function: GATE2015-2_11 top


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-k);
return x;
}

The return value of fun(5) is ______.


gate2015-2

algorithms

identify-function

recurrence

normal

Selected Answer

fun(1) = 1;
fun(2) = 1 + fun(1) * fun(1) = 1 + 1 = 2;
fun(3) = 1 + fun(1) * fun(2) + fun(2) * fun(1) = 5;
fun(4) = 1 + fun(1) * fun(3) + fun(2) * fun(2) + fun(3) * fun(1) = 1 + 5 + 4 + 5 = 15;

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/8060

GATE Overflow

April 2016

87 of 1876

fun(5) = 1 + fun(1) * fun(4) + fun(2) * fun(3) + fun(3) * fun(2) + fun(4) * fun(1) = 1 + 15 + 10 + 10 + 15 = 51;

More formal way:

The recurrence relation is

f(n) =

1, n = 1
1
1 + ni =1
f(i) f(n i), n > 1

f(1) = 1

f(2) = 1 + f(1). f(1) = 1 + 1.1 = 2

f(3) = 1 + f(1). f(2) + f(2). f(1) = 1 + 1.2 + 2.1 = 5

f(4) = 1 + f(1). f(3) + f(2). f(2) + f(3). f(2) = 1 + 1.5 + 2.2 + 5.1 = 15

f(5) = 1 + f(1). f(4) + f(2). f(3) + f(3). f(2) + f(4). f(1) = 1 + 1.15 + 2.5 + 5.2 + 15.1 = 51
-- Arjun Suresh ( 124085 points)

13 votes

Answer: 51.
Find the running code here: http://ideone.com/wrLiLm
-- Rajarshi Sarkar ( 27781 points)

1 votes

1.113 Identify Function: GATE2014-1_41 top


Consider the following C function in which size is the number of elements in the array E:
int MyX(int *E, unsigned int size)
{
int Y = 0;
int Z;
int i, j, k;
for(i = 0; i< size; i++)
Y = Y + E[i];

for(i=0; i < size;


for(j = i; j <
{
Z = 0;
for(k = i;
Z = Z +
if(Z > Y)
Y = Z;
}
return Y;

i++)
size; j++)
k <= j; k++)
E[k];

The value returned by the function MyX is the


(A) maximum possible sum of elements in any sub-array of array E.
(B) maximum element in any sub-array of array E.
(C) sum of the maximum elements in all possible sub-arrays of array E.
(D) the sum of all the elements in the array E.

gate2014-1

algorithms

identify-function

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/1919

GATE Overflow

April 2016

88 of 1876

Selected Answer

answer is (A) maximum possible sum of elements in any sub-array of array E.


int MyX ( int * E, unsinged int size )
{
int Y= 0;
int z;
int i, j,k;
// calculate sum of the elements of the array E and stores it in Y
for i 0;i<size;i++)
Y = Y+E[i];
//calculate the sum of all possible subaarays (starting from postion 0..n-1)
for (i=0;i<size;i++)
for(j=i;j<size ;j++)
{
z = 0;
for(k=i; k<=j;k++)
z=z+E[k];
// checks whether sum of elements of each subarray is greater than the current max, if so, then assign it to currentmax
if(z>Y)
Y = z;
}
// ultimately returns the maximum possible sum of elements in any sub array of given array E
return Y;
}


-- Kalpna Bhargav ( 2931 points)

7 votes

1.114 Identify Function: GATE2006-IT_52 top

gateoverflow.in/3595

The following function computes the value of ( n ) correctly for all legal values m and n (m 1, n 0 and m > n)
int func(int m, int n)
{
if (E) return 1;
else return(func(m -1, n) + func(m - 1, n - 1));
}

In the above function, which of the following is the correct expression for E?

A)
B)
C)
D)
gate2006-it

(n = = 0) || (m = = 1)
(n = = 0) && (m = = 1)
(n = = 0) || (m = = n)
(n = = 0) && (m = = n)

algorithms

identify-function

normal

Selected Answer

Answer: C
m

Because ( 0 ) = 1 and ( n ) = 1.
5 votes

-- Rajarshi Sarkar ( 27781 points)

ans..(C).
1 votes

1.115 Identify Function: GATE1995_2.3 top

Copyright GATE Overflow. All rights reserved.

-- Vicky Bajoria ( 3147 points)

gateoverflow.in/2615

GATE Overflow

April 2016

89 of 1876

Assume that X and Y are non-zero positive integers. What does the following Pascal program segment do?
while X <> Y do
if X > Y then
X := X - Y
else
Y := Y - X;
write(X);

A. Computes the LCM of two numbers


B. Divides the larger number by the smaller number
C. Computes the GCD of two numbers
D. None of the above

gate1995

algorithms

identify-function

normal

Selected Answer

Answer: C
Let X = 3 and Y = 7.
1st pass: X=3, Y=4
2nd pass: X=3, Y=1
3rd pass: X=2, Y=1
4th pass: X=1, Y=1
write (X), which writes 1.
Ref: http://www.naturalnumbers.org/EuclidSubtract.html
-- Rajarshi Sarkar ( 27781 points)

7 votes

1.116 Identify Function: GATE1995_4 top

gateoverflow.in/2640

a. Consider the following Pascal function where A and B are non-zero positive integers. What is the value of GET(3, 2)?
function GET(A,B:integer): integer;
begin
if B=0 then
GET:= 1
else if A < B then
GET:= 0
else
GET:= GET(A-1, B) + GET(A-1, B-1)
end;


b. The Pascal procedure given for computing the transpose of an N N, (N > 1) matrix A of integers has an error. Find the
error and correct it. Assume that the following declaration are made in the main program
const
MAXSIZE=20;
type
INTARR=array [1..MAXSIZE,1..MAXSIZE] of integer;
Procedure TRANSPOSE (var A: INTARR; N : integer);
var
I, J, TMP: integer;
begin
for I:=1 to N 1 do
for J:=1 to N do
begin
TMP:= A[I, J];
A[I, J]:= A[J, I];
A[J, I]:= TMP
end
end;


gate1995

algorithms

identify-function

ans for A is 3.

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

90 of 1876

ans for B is:


outer for loop should run for 1 to n/2, if it run for n-1 times then it will again put the transposed elements at its original
place.
-- jayendra ( 5797 points)

2 votes

1.117 Identify Function: GATE1994_6 top

gateoverflow.in/2502

What function of x, n is computed by this program?


Function what(x, n:integer): integer:
Var
value : integer
begin
value := 1
if n > 0 then
begin
if n mod 2 =1 then
value := value * x;
value := value * what(x*x, n div 2);
end;
what := value;
end;


gate1994

algorithms

identify-function

normal

Selected Answer

answer - x n
-- ankitrokdeonsns ( 7941 points)

5 votes

1.118 Identify Function: GATE2009_18 top


Consider the program below:
#include <stdio.h>
int fun(int n, int *f_p) {
int t, f;
if (n <= 1) {
*f_p = 1;
return 1;
}
t = fun(n-1, f_p);
f = t + *f_p;
*f_p = t;
return f;
}
int main() {
int x = 15;
printf("%d/n", fun(5, &x));
return 0;
}

The value printed is



A. 6
B. 8
C. 14
D. 15

gate2009

algorithms

recursion

Selected Answer

Copyright GATE Overflow. All rights reserved.

identify-function

normal

gateoverflow.in/1310

GATE Overflow

April 2016

91 of 1876

The answer is B.
Let the address of x be 1000.
1.f(5,1000) = 8
2.f(4,1000) = 5
3.f(3,1000) = 3
4.f(2,1000) = 2
5.f(1,1000) = 1.
The evaluation is done from 5 to 1. Since recursion is used.
5 votes

-- Gate Keeda ( 16619 points)

Answer 8 . Option B

2 votes

-- Akhil Nadh PC ( 1967 points)

1.119 Identify Function: GATE1995_1.4 top


In the following Pascal program segment, what is the value of X after the execution of the program segment?

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/2591

GATE Overflow

April 2016

92 of 1876

X := -10; Y := 20;
If X > Y then if X < 0 then X := abs(X) else X := 2*X;

A. 10
B. -20
C. -10
D. None

gate1995

algorithms

identify-function

easy

Selected Answer

Ans of X remains unchanged. As the if condition becomes false.


X := -10

ans is C . This is classic example of if-else issue. Always else matches for nesting to closest if in C Programming & Pascal .
https://en.wikipedia.org/wiki/Dangling_else

if (x>y)
{
if (x<0)
x=abs(x)
else
x=2*x
}


-- Akash ( 26265 points)

5 votes

1.120 Insertion Sort: TIFR2010-B-27 top


Consider the Insertion Sort procedure given below, which sorts an array L of size n( 2) in ascending order:
begin
for xindex:= 2 to n do
x := L [xindex];
j:= xindex - 1;
while j > 0 and L[j] > x do
L[j + 1]:= L[j];
j:= j - 1;
end {while}
L [j + 1]:=X;
end{for}
end

It is known that insertion sort makes at most n (n - 1) / 2 comparisons. Which of the following is true?
a. There is no input on which insertion Sort makes n (n - 1) / 2 comparisons.
b. Insertion Sort makes n (n - 1) / 2 comparisons when the input is already sorted in ascending order.
c. Insertion Sort makes n (n - 1) / 2 comparisons only when the input is sorted in descending order.
d. There are more than one input orderings where insertion sort makes n (n - 1) / 2 comparisons.
e. Insertion Sort makes n (n - 1) / 2 comparisons whenever all the elements of L are not distinct.
tifr2010

algorithms

sorting

insertion-sort

Selected Answer

In worst case Insertion sort will have N(N-1)/2 comparisons i.e. when input is sorted in descending order.
50 40 30 20 10
pass 1 50 40 30 20 10..............n 0 compare
pass 2 40 50 30 20 10..............n 1 compare

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/19036

GATE Overflow

April 2016

93 of 1876

.
.
.
pass n n ...............10 20 30 40 50 n-1 compare
1+2+3....................+n-1 = N(N-1)/2 comparisons
-- Umang Raman ( 10379 points)

2 votes

1.121 Lines Curves: GATE2007-IT_81 top

gateoverflow.in/3533

Let P1 , P2 , , Pn be n points in the xy-plane such that no three of them are collinear. For every pair of points Pi and Pj, let Lij be
the line passing through them. Let Lab be the line with the steepest gradient among all n(n 1)/2 lines.
The time complexity of the best algorithm for finding Pa and Pb is
A) (n)
B) (nlogn)

( )
D) (n )
C) nlog2 n
2

gate2007-it

algorithms

lines-curves

time-complexity

normal

1.122 Linked Lists: GATE1994_1.17 top

gateoverflow.in/2460

Linked lists are not suitable data structures for which one of the following problems?
A. Insertion sort
B. Binary search
C. Radix sort
D. Polynomial manipulation

gate1994

algorithms

linked-lists

normal

Selected Answer

B. Because in binary search we need to have access to the mid of the list in constant time. and finding the mid itself in a
linked list takes O(n) time which makes no sense to Binary search which otherwise takes O(logn).
-- Gate Keeda ( 16619 points)

8 votes

1.123 Linked Lists: GATE2004-IT_13 top

gateoverflow.in/3654

Let P be a singly linked list. Let Q be the pointer to an intermediate node x in the list. What is the worst-case time complexity
of the best-known algorithm to delete the node x from the list ?

A)
B)
C)
D)

Copyright GATE Overflow. All rights reserved.

O(n)
O(log2 n)
O(log n)
O(1)

GATE Overflow

April 2016

gate2004-it

algorithms

linked-lists

time-complexity

94 of 1876

normal

Selected Answer

In the worst case x could be last or second last node, In that case full traversal of the list is required. Therefore answer is
(A).
-- suraj ( 3299 points)

4 votes

Since Q is pointing to node X, it can de done in O(1) time..


Algo:
Q -> data = Q ->next -> data; // Copy the value of next node into Q.
del = Q -> next; // take another pointer variable pointing to next node of Q.
Q -> next = Q -> next ->next;
free (del);
-- gate_asp ( 483 points)

4 votes

1.124 Linked Lists: GATE1997_18 top

gateoverflow.in/2278

Consider the following piece of C code fragment that removes duplicates from an ordered list of integers.
Node
*remove-duplicates (Node* head, int *j)
{
Node *t1, *t2;
*j=0;
t1 = head;
if (t1! = NULL) t2 = t1 ->next;
else return head;
*j = 1;
if(t2 == NULL)
return head;
while t2 != NULL)
{
if (t1.val != t2.val) ----------------> S1)
{
(*j)++; t1 -> next = t2; t1 = t2: -----> (S2)
}
t2 = t2 ->next;
}
t1 -> next = NULL;
return head;
}

Assume the list contains n elements (n 2) in the following questions.


a. How many times is the comparison in statement S1 made?
b. What is the minimum and the maximum number of times statements marked S2 get executed?
c. What is the significance of the value in the integer pointed to by j when the function completes?

gate1997

algorithms

data-structure

linked-lists

normal

1.125 Linked Lists: GATE2010_36 top

gateoverflow.in/2337

The following C function takes a singly-linked list as input argument. It modies the list by moving the last element to the front of the list and returns the modied
list. Some part of the code is left blank.
typedef struct node
{
int value;
struct node *next;
} node;
Node *move_to-front(Node *head)
{
Node *p, *q;
if ((head == NULL) || (head -> next == NULL))
return head;
q = NULL;

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

95 of 1876

p = head;
while (p->next != NULL)
{
q=p;
p=p->next;
}
_______________
return head;
}

Choose the correct alternative to replace the blank line.


(A) q=NULL; p->next = head; head = p;
(B) q->next = NULL; head = p; p->next = head;
(C) head = p; p->next =q; q->next = NULL;
(D) q->next = NULL; p->next = head; head = p;

gate2010

algorithms

linked-lists

normal

Selected Answer

as per given code p points to last node which should be head in modified.
q is the previous node of tail which should be tail for modified
answer D
-- Sankaranarayanan P.N ( 7645 points)

9 votes

after the last iteration of the while loop, here's how the condition look like :

on selecting option D ; we serve the purpose of moving the last node to the front of the linked list. this is how it works:
its first statement makes q the last node
second statement makes the last node p points to the first node
last statement declares p as the head of the linked list.

-- Amar Vashishth ( 17735 points)

1 votes

1.126 Linked Lists: GATE1993_13 top

gateoverflow.in/2310

Consider a singly linked list having n nodes. The data items d1 , d2 , dn are stored in these n nodes. Let X be a pointer to the jth
node (1 j n) in which dj is stored. A new data item d stored in node with address Y is to be inserted. Give an algorithm to
insert d into the list to obtain a list having items d1 , d2 , , dj, d, , dn in order without using the header.
gate1993

algorithms

linked-lists

normal

Selected Answer

these steps are mandatory for the algorithm :

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

96 of 1876

temp = X next
X next = Y
Y next = temp
-- Amar Vashishth ( 17735 points)

3 votes

1.127 Loop Invariants: TIFR2010-B-30 top

gateoverflow.in/19042

Consider the following program for summing the entries of the array b: array [0. . N 1] of integers, where N is a positive
integer. (The symbol '<>' denotes 'not equal to').
var

i, s: integer;
Program
i:= 0;
s:= 0;
[*] while i <> N do
s := s + b[i];
i := i + 1;
od

Which of the following gives the invariant that holds at the beginning of each loop, that is, each time the program arrives at
point [*] ?
N

A. s = j =0 b[j] & 0 i N
i =1

B. s = j =0 b[j] & 0 i < N


i

C. s = j =0 b[j] & 0 < i N


N

D. s = j =1 b[j] & 0 i < N


i 1

E. s = j =0 b[j] & 0 i N

tifr2010

algorithms

loop-invariants

Selected Answer

Whenever we encounter the [*], the variable s holds the sum of all elements b[0] to b[i 1].
When we first enter the loop, i = 0, and s doesn't have any elements summed up.
When we last enter the loop, i = (N 1) and s contains the sum of elements b[0] through b[N 2].
We leave the loop when i = N, and s gets the sum of elements b[0] to b[N 1]
The only option that matches this behavior is option E
i 1

s = j =0 b[j] & 0 i N
3 votes

1.128 Loop Invariants: GATE 2016-2-35 top


The following function computes XY for positive integers X and Y.
int exp (int X, int Y) {
int res =1, a = X, b = Y;

Copyright GATE Overflow. All rights reserved.

-- Pragy Agarwal ( 13675 points)

gateoverflow.in/39578

GATE Overflow

April 2016

while (b != 0) {
if (b % 2 == 0) {a = a * a; b = b/2; }
else
{res = res * a; b = b - 1; }
}
return res;
}

Which one of the following conditions is TRUE before every iteration of the loop?
A. XY = ab
B. (res a)Y = (res X)b
C. XY = res ab
D. XY = (res a)b


gate2016-2

algorithms

loop-invariants

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

97 of 1876

GATE Overflow

April 2016

98 of 1876

Answer ==> C
6 votes

Copyright GATE Overflow. All rights reserved.

-- Akash ( 26265 points)

GATE Overflow

April 2016

99 of 1876

OPTION C.
-- ajit ( 1369 points)

3 votes

1.129 Matrix Chain Ordering: GATE2011_38 top

gateoverflow.in/2140

Four Matrices M1 , M2 , M3 , and M4 of dimensions p q, q r, r s and s t respectively can be multiplied in several ways with
different number of total scalar multiplications. For example when multiplied as ((M1 M2 ) (M3 M4 )), the total number of
scalar multiplications is pqr + rst + prt. When multiplied as (((M1 M2 ) M3 ) 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 minimum number of scalar multiplications needed is
(A) 248000
(B) 44000
(C) 19000
(D) 25000
gate2011

algorithms

dynamic-programming

matrix-chain-ordering

normal

Selected Answer

Answer is C.



Brute Force approach - anyone can do.
1

No. of possible ordering for 4 matrices is C3 where C3 is the 3rd Catalan number and given by n = 3 in n +1 2n Cn = 5.
So, here we have
1. (M1 M2 ) (M3 M4 )
2. (M1 (M2 M3 )) M4
3. ((M1 M2 ) M3 ) M4
4. M1 (M2 (M3 M4 ))
5. M1 ((M2 M3 ) M4 ))
Each of these would give no. of multiplications required as
1. pqr + rst + prt
2. qrs + pqs + pst
3. pqr + prs + pst
4. rst + qrt + pqt
5. qrs + qst + pst
The last 2 are having qt terms which are the highest terms by far and hence we can avoid them from consideration
qt = 8000 multiplied by one other term would be larger than any value in choice. So, just find the value of first 3 terms.
1. pqr + rst + prt = 20000 + 8000 + 16000 = 44000
2. qrs + pqs + pst = 10000 + 5000 + 4000 = 19000 - smallest value in choice, we can stop here.
3. pqr + prs + pst

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

100 of 1876


Dynamic Programming Solution (should know Matrix Chain Ordering algorithm)
Here we have a chain of length 4.
Dynamic programming solution of Matrix chain ordering has the solution

m[i, j] =

0
mini k<jm[i]k] + m[k + 1][j] + pi 1 pjpk

if i = j
if i < j

So, we can fill the following table starting with the diagonals and moving upward diagonally. Here k < j but i.

j=1 j=2

j=3

j=4

i=1 0

p0 p1 p2 = 20000 min (10000 + p0 p1 p3 , 20000 + p0 + p2 p3 ) = 15000 min (18000 + p0 p1 p4 , 20000 + 8000 + p0 + p2 + p4 , 15000 + p0 p3 p4 ) = 19000

i=2

p1 p2 p3 = 10000

min (10000 + p2 p3 p4 ), p1 p3 p4 ) = 18000

i=3

p2 p3 p4 = 8000

i=4


Our required answer is given by m[1, 4] = 19000.
-- Sona Praneeth Akula ( 3473 points)

5 votes

1.130 Matrix Chain Ordering: GATE 2016-2-38 top

gateoverflow.in/39587

Let A1 , A2 , A3 and A4 be four matrices of dimensions 10 5, 5 20, 20 10, and 10 5, respectively. The minimum number of
scalar multiplications required to find the product A1 A2 A3 A4 using the basic matrix multiplication method is _________.
gate2016-2

dynamic-programming

matrix-chain-ordering

normal

numerical-answers

Selected Answer

Answer is 1500 !
Matrix Paranthesizing => A1 ((A2 A3) A4)
Check my solution below, using dynamic programming (There was little mistake while writing in parantheses in this
image, ignore it Check paranthesis above ) =>

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

101 of 1876

-- Akash ( 26265 points)

7 votes

Minimum number of scalar multiplications required is 1500.


A1((A2A3)A4) is the order, where scalar multiplications are minimum here and is 1500
-- Sreyas S ( 1273 points)

4 votes

1.131 Median: TIFR2013-B-12 top

gateoverflow.in/25774

It takes O(n) time to find the median in a list of n elements, which are not necessarily in sorted order while it takes only O(1)
time to find the median in a list of n sorted elements. How much time does it take to find the median of 2n elements which
are given as two lists of n sorted elements each?
a. O(1)
b. O(logn) but not O(1)
c. O( n) but not O(logn)
d. O(n) but not O( n)
e. O(nlogn) but not O(n)

tifr2013

algorithms

median

1) Calculate the medians m1 and m2 of the input arrays ar1[]


and ar2[] respectively.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

102 of 1876

2) If m1 and m2 both are equal.


return m1 (or m2)
3) If m1 is greater than m2, then median is present in one
of the below two subarrays.
a) From first element of ar1 to m1 (ar1[0 to n/2])
b) From m2 to last element of ar2 (ar2[n/2 to n-1])
4) If m2 is greater than m1, then median is present in one
of the below two subarrays.
a) From m1 to last element of ar1 (ar1[n/2 to n-1])
b) From first element of ar2 to m2 (ar2[0 to n/2])
5) Repeat the above process until size of both the subarrays
becomes 2.
6) If size of the two arrays is 2 then
the median.
Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2
Time complexity O(logn)
-- Umang Raman ( 10379 points)

1 votes

1.132 Merge Sort: GATE2015-3_27 top

gateoverflow.in/8480

Assume that a mergesort algorithm in the worst case takes 30 seconds for an input of size 64. Which of the following most
closely approximates the maximum input size of a problem that can be solved in 6 minutes?

A. 256
B. 512
C. 1024
D. 2018
gate2015-3

algorithms

sorting

merge-sort

Selected Answer

The worst case time complexity of Mergesort is k nlogn for an input of size n.
For an input of size 64, the algorithm takes 30s. Therefore,
k 64log2 64 = 30s
k 384 = 30s
 k = 0.078125s
Let the size of the problem that can be solved in 6 minutes be x. Then,
k xlog2 x = 360s
From this, we get:

xlog2 x =

360s
0.078125s

 x = 512
16 votes

1.133 Merge Sort: GATE2005-IT_59 top

-- Pragy Agarwal ( 13675 points)

gateoverflow.in/3820

Let a and b be two sorted arrays containing n integers each, in non-decreasing order. Let c be a sorted array containing 2n
integers obtained by merging the two arrays a and b. Assuming the arrays are indexed starting from 0, consider the
following four statements

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

103 of 1876

I. a[i] b [i] => c[2i] a [i]


II. a[i] b [i] => c[2i] b [i]
III. a[i] b [i] => c[2i] a [i]
IV. a[i] b [i] => c[2i] b [i]
Which of the following is TRUE?

A)
B)
C)
D)

only I and II
only I and IV
only II and III
only III and IV

gate2005-it

algorithms

sorting

merge-sort

normal

Selected Answer

a[i] b[i]
Since both a and b are sorted in the beginning, there are i elements smaller than or equal to a[i] (i starts from 0), and
similarly i elements smaller than or equal to b[i]. So, a[i] b[i] means there are 2i elements smaller than or equal to
a[i], and hence in the merged array a[i] will come after these 2i elements (its index will be > 2i). So, c[2i] a[i] (equality
takes care of the "equal to" case which comes when array contains repeated elements).
Similarly, a[i] b[i] says for b that, there are not more than 2i elements smaller than b[i] in the sorted array (i elements
from b, and maximum another i elements from a). So, b[i] c[2i]
So, II and III are correct -> option (C)
-- Arjun Suresh ( 124085 points)

6 votes

1.134 Merge Sort: GATE1995_1.16 top

gateoverflow.in/2603

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(logm + logn)

gate1995

algorithms

sorting

merge-sort

normal

Selected Answer

It is C.
The number of moves are however always m+n so that we can term it as theta(m+n). But the number of comparisons
vary as per the input. In the best case the comparisons are Min(m,n) and in worst case they are m+n-1.
10 votes

1.135 Minimum: GATE2008_42 top

-- Gate Keeda ( 16619 points)

gateoverflow.in/1872

G is a graph on n vertices and 2n 2 edges. The edges of G can be partitioned into two edge-disjoint spanning trees. Which of
the following is NOT true for G?
a. For every subset of k vertices, the induced subgraph has at most 2k 2 edges.
b. The minimum cut in G has at least 2 edges.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

104 of 1876

c. There are at least 2 edge-disjoint paths between every pair of vertices.


d. There are at least 2 vertex-disjoint paths between every pair of vertices.

gate2008

algorithms

graph-algorithms

minimum

spanning-tree

normal

Selected Answer

There are 2 spanning trees (a spanning tree connects all n vertices) for G which are edge disjoint. A spanning tree for n
nodes require n 1 edges and so 2 edge-disjoint spanning trees requires 2n 2 edges. As G has only 2n 2 edges, it is clear
that it doesn't have any edge outside that of the two spanning trees. Now lets see the cases:
Lets take any subgraph of G with k vertices. The remaining subgraph will have n k vertices. Between these two subgraphs
(provided both has at least one vertex) there should be at least 2 edges, as we have 2 spanning trees in G. So, (b) is
TRUE. Also, in the subgraph with k vertices, we cannot have more than 2k 2 edges as this would mean that in the other
subgraph with n k vertices, we would have less than 2n 2k edges, making 2 spanning trees impossible in it. So, (a) is
also TRUE.
A spanning tree covers all the vertices. So, 2 edge-disjoint spanning trees in G means, between every pair of vertices in G
we have two edge-disjoint paths (length of paths may vary). So, (c) is also TRUE.
So, that leaves option (d) as answer. It is not quite hard to give a counter example for (d).
-- Arjun Suresh ( 124085 points)

8 votes

1.136 Minimum Spanning Trees: GATE 2016-1-40 top

gateoverflow.in/39727

G = (V, E) is an undirected simple graph in which each edge has a distinct weight, and e is a particular edge of G. Which of the
following statements about the minimum spanning trees (MSTs) of G is/are TRUE?
I. If e is the lightest edge of some cycle in G, then every MST of G includes e.
II. If e is the heaviest edge of some cycle in G, then every MST of G excludes e.
A. I only.
B. II only.
C. Both I and II.
D. Neither I nor II.

gate2016-1

algorithms

graph-algorithms

minimum-spanning-trees

normal

Selected Answer

I think answer is option B


Statement 2 is correct absolutely. if e is the heaviest edge in cycle every mst excludes it.
Regarding statement 1, It is not fully right i think. When we think of a complete graph with 4 vertices and edge weights
1,2,5,6 in non diagonal and diagonal edges 3 and 4. 4,5,6 will create a cycle and we can exclude the lighest edge e (4)
from it, in a MST
So i think answer could be B
14 votes

-- Sreyas S ( 1273 points)

I think answer is D.
Statement I is wrong.
Statement II is also wrong, consider any graph where between any two nodes there are two paths, first path consists of
edges with weights 2 and 8, second path has weight 5 and 7. So, MST would include that heaviest weight in that cycle.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

105 of 1876
-- chaitoo ( 41 points)

3 votes

1.137 Minimum Spanning Trees: GATE 2016-1-14 top

gateoverflow.in/39673

Let G be a weighted connected undirected graph with distinct positive edge weights. If every edge weight is increased by the
same value, then which of the following statements is/are TRUE?
P: Minimum spanning tree of G does not change.
Q: Shortest path between any pair of vertices does not change.
A. P only
B. Q only
C. Neither P nor Q
D. Both P and Q

gate2016-1

algorithms

graph-algorithms

minimum-spanning-trees

shortest-path

normal

Selected Answer

Statement P is true.
For statement Q c onsider a simple graph with 3 nodes.

100

B
C

1
0
100 2

2
0

Shortest path from A to C is A-B-C = 1 + 2 = 3


Now if the value of each edge is increased by 100,

101 200

B
C

101
200

0
102
102 0

The shortest path from A to C is A-C = 200, (A-B-C = 101 + 102 = 203)
Hence option A is correct.
13 votes

-- ryan sequeira ( 1011 points)

According to me Only p is correct.


8 votes

-- akashrai110 ( 107 points)

Both are correct...option is D


5 votes

1.138 Minimum Spanning Trees: TIFR2015-B-2 top

-- Deepak Sharma ( 367 points)

gateoverflow.in/29844

Consider the following undirected connected graph G with weights on its edges as given in the figure below. A minimum
spanning tree is a spanning tree of least weight and a maximum spanning tree is one with largest weight. A second best
minimum spanning tree whose weight is the smallest among all spanning trees that are not minimum spanning trees in G.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

106 of 1876

Which of the following statements is TRUE in the above graph? (Note that all the edge weights are distinct in the above
graph)
a. There is more than one minimum spanning tree and similarly, there is more than one maximum spanning tree here.
b. There is a unique minimum spanning tree, however there is more than one maximum spanning tree here.
c. There is more than one minimum spanning tree, however there is a unique maximum spanning tree here.
d. There is more than one minimum spanning tree and similarly, there is more than one second-best minimum spanning
tree here.
e. There is unique minimum spanning tree, however there is more than one second-best minimum spanning tree here.
tifr2015

minimum-spanning-trees

Since, all the edge weights are distinct, we have a unique minimum weight spanning tree and maximum weight spanning
tree.
And we can have more than one second best minimum spanning tree because different combinations of edge may give
second largest value.
You can also try finding MinST and MaxST from the given graph.
Hence, option 'e' is only possible.
-- Monanshi Jain ( 5787 points)

2 votes

1.139 Minimum Spanning Trees: GATE 2016-1-39 top

gateoverflow.in/39725

Let G be a complete undirected graph on 4 vertices, having 6 edges with weights being 1, 2, 3, 4, 5, and 6. The maximum
possible weight that a minimum weight spanning tree of G can have is __________
gate2016-1

algorithms

graph-algorithms

minimum-spanning-trees

normal

numerical-answers

Selected Answer

Graph G can be like this:

12 votes

Copyright GATE Overflow. All rights reserved.

-- shaiklam09 ( 199 points)

GATE Overflow

April 2016

107 of 1876

ans is 7.
it is said maximum weight pssbl.
draw a triangle. 3 sides weight 1 2 3. and 4th point is in center. join it with tringle vertices.. got more 3 sides. new side
weight 4 5 6. now draw mst. take 1 take 2. cant take 3, so take 4. 1+2+4=7
-- Debasmita Bhoumik ( 213 points)

8 votes

The minimum spanning tree for a distinct edge weighted graph is unique .
And as the minimum spanning tree is unique the only possible weight is 6 ( selecting the lowest possible weights 1,2,3 )


-- Bharani Viswas ( 667 points)

5 votes

THE ANSWER FOR THIS QUESTION IS 6 !!


sorry for the disappointment!!
now the minimum spanning tree for a graph with distinct edge weights is UNIQUE if u want reference
( https://en.wikipedia.org/wiki/Minimum_spanning_tree)
now the given graph is having distinct edge weights so minimum spanning tree will be unique and its always 6
the question about maximum ???
there is no concept of max or min in minimum spanning tree !!!
-- Bharani Viswas ( 667 points)

4 votes

1.140 P Np Npc Nph: TIFR2011-B-37 top

gateoverflow.in/20922

Given an integer n 3, consider the problem of determining if there exist integers a, b 2 such that n = ab . Call this the
forward problem. The reverse problem is: given a and b, compute ab (mod b). Note that the input length for the forward
problem is logn + 1, while the input length for the reverse problem is loga + logb + 2. Which of the following
statements is TRUE?
a. Both the forward and reverse problems can be solved in time polynomial in the lengths of their respective inputs.
b. The forward problem can be solved in polynomial time, however the reverse problem is NP-hard.
c. The reverse problem can be solved in polynomial time, however the forward problem is NP-hard.
d. Both the forward and reverse problem are NP-hard.
e. None of the above.
tifr2011

algorithms

p-np-npc-nph

Selected Answer

The reverse problem can be solved in polynomial time as ab requires at most logb recursive calls using the approach given
below:
pow(int a, int b)
{
if(b%2)
return a* pow(a*a, b/2);
else
return pow(a*a, b/2);
}
1

Now, the forward problem is also solvable in polynomial time. We need to check for all the roots of n (from n till n

Copyright GATE Overflow. All rights reserved.

log n

GATE Overflow

April 2016

108 of 1876

whether it is an integer . But each of these check can be done in logn time using a binary search on the set of integers from
2..n and so, the overall complexity will be (logn)2 which is polynomial in logn (logn is the size of input). So, (a) must be the
answer.

-- gatecse ( 9515 points)

2 votes

1.141 P Np Npc Nph: GATE1995_11 top

gateoverflow.in/2647

Let L be a language over i.e., L . Suppose L satisfies the two conditions given below.
i. L is in NP and
ii. For every n, there is exactly one string of length n that belongs to L. Let Lc be the complement of L over . Show that
Lc is also in NP.

gate1995

algorithms

p-np-npc-nph

normal

Selected Answer

Since L is in NP it is decidable (recursive) and so is its complement Lc. Now, Lc may or may not be in NP. But we are given
that for any string length n, exactly one string belong to L, which means for any string length all but one string belong to
Lc.
Now, definition of NP says that all "yes" instances of the problem can be solved in polynomial time using a
nondeterministic TM. So, given an instance of Lc, x, we non-deterministically take all words of length n, where n is the
length of w, and see if it is in L. As soon as we get the word (such a word is sure to exist as exactly one word of length n
belong to L), we see if this word is same as x. If it is not same (and only if it is not same), x Lc and we get this answer in
polynomial time making Lc an NP problem.
-- Arjun Suresh ( 124085 points)

3 votes

1.142 P Np Npc Nph: TIFR2013-B-7 top

gateoverflow.in/25668

Which of the following is not implied by P = NP?


a. 3SAT can be solved in polynomial time.
b. Halting problem can be solved in polynomial time.
c. Factoring can be solved in polynomial time.
d. Graph isomorphism can be solved in polynomial time.
e. Travelling salesman problem can be solved in polynomial time.

tifr2013

algorithms

p-np-npc-nph

Selected Answer

I believe Umang is right, Option B is the correct answer.


Intractability : We are looking for EFFICIENT algorithms.
Intractable Problems are problems that are decidable, although the algorithm to decide that problem might be efficient (P)
or inefficient (NP), but at least an algorithm exists to solve these problems.
Here we talk about efficient vs inefficient computations.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

109 of 1876

Thus the language of problems in P and NP classes is the language of Decidable Problems i.e. Recursive
Language.
Undecidability: We are looking for algorithms.
Undecidable Problems are problems for which there is no algorithm to solve these problems.
Here we talk about what can or can not be computed.
The language of Undecidable Problems are "Recursively Enumerable but not recursive languages" & "Not
Recursively Enumerable Languages".
Clearly we can talk about the intractability of any problem if we know at least one algorithm o
t solve the
problem, if there is no algorithm to solve a problem how can we talk about efficiency?
Halting Problem is undecidable.
I guess, all other problems mentioned here are decidable.
I don't know the most efficient algorithms to solve these problems but at least I can say that Brute force approach will
work on all the other options except the Halting Problem.
What P = NP implies?
"Any problem that is solved by a non deterministic Turing machine in polynomial time also be solved by some
deterministic Turing machine in polynomial time, even if the degree of the polynomial is higher."
and
There is neither a Non Deterministic Turing Machine nor Deterministic Turing Machine that can solve the
Halting Problem.
So any inference about P & NP is not going to affect the solvability of Halting Problem, since it is undecidable.
-- Anurag Pandey ( 8183 points)

3 votes

1.143 P Np Npc Nph: TIFR2011-B-25 top

gateoverflow.in/20404

Let ATM be defined as follows:


ATM = {M, w The Turning machine M accepts the word w}
And let L be some NP complete language. Which of the following statements is FALSE?
a. L NP
b. Every problem in NP is polynomial time reducible to L.
c. Every problem in NP is polynomial time reducible to ATM.
d. Since L is NP complete, ATM is polynomial time reducible to L.
e. ATM NP.
tifr2011

theory-of-computation

algorithms

p-np-npc-nph

Selected Answer

ATM is the language of the Halting Problem. It is undecidable, but Recursively Enumerable.
L is NPC
a. True. Any language in NPC is also in NP by definition.
b. True. By definition, any problem in NP is polynomial time reducible to any NPC problem.
c. True. ATM is undecidable. Any language that is decidable is polynomial time reducible to ATM!

d. False. ATM is undecidable. No Turing Machine can guarantee an answer in a finite time, let alone a

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

110 of 1876

polynomial time.

e. True. ATM is undecidable. It is certainly not in NP.
Hence, the correct answer is option d.
-- Pragy Agarwal ( 13675 points)

5 votes

1.144 P Np Npc Nph: TIFR2012-B-20 top

gateoverflow.in/26480

This question concerns the classes P and N P . If you are familiar with them, you may skip the definitions and go directly to
the question.
Let L be a set. We say that L is in P if there is some algorithm which given input x decides if x is in L or not in time bounded
by a polynomial in the length of x. For example, the set of all connected graphs is in P , because there is an algorithm which,
given a graph graph, can decide if it is connected or not in time roughly proportional to the number of edges of the graph.
The class NP is a superset of class P . It contains those sets that have membership witnesses that can be verified in
polynomial time. For example, the set of composite numbers is in NP . To see this take the witness for a composite number
to be one of its divisors. Then the verification process consists of performing just one division using two reasonable size
numbers. Similarly, the set of those graphs that have a Hamilton cycle, i.e. a cycle containing all the vertices of the graph, is
in in NP. To verify that the graph has a Hamilton cycle we just check if the witnessing sequence of vertices indeed a cycle of
the graph that passes through all the vertices of the graph. This can be done in time that is polynomial in the size of the
graph.
More precisely, if L is a set in P consisting of elements of the form (x, w), then the set
M = {x: w, | w | | x | k and (x, w) L},
is in N P .
Let G = (V, E) be a graph. G is said to have perfect matching if there is a subset M of the edges of G so that
i. No two edges in M intersect (have a vertex in common); and
ii. Every vertex of G has an edge in M.

Let MATCH be the set of all graphs that have a perfect matching. Let MATCH be the set of graphs that do not have a perfect
matching. Let o(G) be the number of components of G that have an odd number of vertices.
Tuttes Theorem: G MATCH if and only if for all subsets S of V, the number of components in G S (the graph formed by
deleting the vertices in S) with an odd number of vertices is at most |S|. That is,
G MATCH S Vo(G S) | S | .
Which of the following is true?

A. MATCH NP and MATCH NP

B. MATCH NP and MATCH NP

C. MATCH NP and MATCH NP

D. MATCH P and MATCH P


E. none of the above
tifr2012

algorithms

p-np-npc-nph

1.145 P Np Npc Nph: TIFR2015-B-13 top

gateoverflow.in/30076

Two undirected graphs G 1 = (V1 , E1 ) and G 2 = (V2 , E2 ) are said to be isomorphic if there exist a bijection :V1 V2 such that for
all u, v V1 , (u, v) E1 if and only ((u), (v)) E2 . Consider the following language.
L={(G, H)| G and H are undirected graphs such that a subgraph of G is isomorphic to H}
Then which of the following are true?
(i) L NP.
(ii) L is NP- hard.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

111 of 1876

(iii) L is undecidable.
A. Only (i)
B. Only (ii)
C. Only (iii)
D. (i) and (ii)
E. (ii) and (iii)


tifr2015

p-np-npc-nph

non-gate

graph isomporphism is np complete and decidable so ans is d


-- Pooja ( 22745 points)

1 votes

1.146 P Np Npc Nph: TIFR2010-B-39 top

gateoverflow.in/18754

Suppose a language L is NP complete. Then which of the following is FALSE?


A. L NP
B. Every problem in P is polynomial time reducible to L.
C. Every problem in NP is polynomial time reducible to L.
D. The Hamilton cycle problem is polynomial time reducible to L.
E. P NP and L P.
tifr2010

algorithms

p-np-npc-nph

Selected Answer

Option E leads to a contradiction, hence is false.


We know that L is NPC, hence NP. If P NP, then L can't be in P
3 votes

-- Pragy Agarwal ( 13675 points)

A) A Problem is NP Complete Means, It is NP Hard & Belongs To NP. L Is NP Complete, it belongs to NP so correct.
B) NP Complete is as hard as every other problem in NP. As P is subset of NP (Every P Problem is NP) B Is correct.
C) This is correct, NP Complete = As hard as all other NP Problems. All can be reduces to it.
D) Hamilton cyle is NP Complete, so This is correct.
E) This created contradiction. If P != NP Then NP Complete problem can not belong to P.
3 votes

1.147 P Np Npc Nph: GATE2009_14 top


Let A be a problem that belongs to the class NP. Then which one of the following is TRUE?

A. There is no polynomial time algorithm for A.
B. If A can be solved deterministically in polynomial time, then P = NP.
C. If A is NP-hard, then it is NP-complete.

Copyright GATE Overflow. All rights reserved.

-- Akash ( 26265 points)

gateoverflow.in/1306

GATE Overflow

April 2016

112 of 1876

D. A may be undecidable.

gate2009

algorithms

p-np-npc-nph

easy

Selected Answer

A problem which is in P , is also in NP- so A is false. If problem can be solved deterministically in Polynomial time, then
also we can't comment anything about P=NP, we just put this problem in P. So, B also false. C is TRUE because that is the
definition of NP-complete.
D is false because all NP problems are not only decidable but decidable in polynomial time using a non-deterministic Turing
machine.
-- shreya ghosh ( 2801 points)

5 votes

1.148 P Np Npc Nph: GATE2004_30 top

gateoverflow.in/1027

The problem 3-SAT and 2-SAT are



A. both in P
B. both NP complete
C. NP-complete and in P respectively
D. undecidable and NP complete respectively


gate2004

algorithms

p-np-npc-nph

easy

Selected Answer

Option c.
http://cstheory.stackexchange.com/questions/6864/why-is-2sat-in-p
-- anshu ( 2155 points)

3 votes

1.149 P Np Npc Nph: GATE2006_31 top

gateoverflow.in/994

Let SHAM3 be the problem of finding a Hamiltonian cycle in a graph G=(V,E) with divisible by 3 and DHAM 3 be the
problem of determining if a Hamiltonian cycle exists in such graphs. Which one of the following is true?
(A) Both DHAM 3 and SHAM 3 are NP-hard
(B) SHAM3 is NP-hard, but DHAM 3 is not
(C) DHAM3 is NP-hard, but SHAM 3 is not
(D) Neither DHAM3 nor SHAM 3 is NP-hard


gate2006

algorithms

p-np-npc-nph

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

113 of 1876

Selected Answer

The only difference between SHAM and DHAM, in SHAM |V| is divisible by 3.. which can be check in constant amount of
time.. So the hardness of the two problem will the same... Next, finding hamiltonian cycle comes under NPC problem and
NPC problem is a subset of NPH, so both are NPH..
So, option (A)
-- Vicky Bajoria ( 3147 points)

3 votes

1.150 P Np Npc Nph: GATE1992_02,vi top

gateoverflow.in/561

02. Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
(vi) Which of the following problems is not NP-hard?
a. Hamiltonian circuit problem
b. The 0/1 Knapsack problem
c. Finding bi-connected components of a graph
d. The graph coloring problem

gate1992

p-np-npc-nph

algorithms

a. Is NPC and hence NP hard.


b.
Is
again
NP
hard
(optimization
version
is
NP
hard
and
decision
version
Ref: http://stackoverflow.com/questions/3907545/how-to-understand-the-knapsack-problem-is-np-complete

is

NPC).

c.Is in P. See the algorithm here based on DFS: http://en.wikipedia.org/wiki/Biconnected_component


d. NPC and hence NP hard.
-- Arjun Suresh ( 124085 points)

3 votes

1.151 P Np Npc Nph: GATE2003_12 top

gateoverflow.in/903

Ram and Shyam have been asked to show that a certain problem is NP-complete. Ram shows a polynomial time reduction
from the 3-SAT problem to , and Shyam shows a polynomial time reduction from to 3-SAT. Which of the following can be
inferred from these reductions?

A. is NP-hard but not NP-complete
B. is in NP, but is not NP-complete
C. is NP-complete
D. is neither NP-hard, nor in NP

gate2003

algorithms

p-np-npc-nph

normal

Selected Answer

C
Ram's reduction shows is NP hard.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

114 of 1876

Shyam's reduction shows is in NP.


So NPC.
-- Anurag Semwal ( 4775 points)

7 votes

1.152 P Np Npc Nph: GATE2013_18 top

gateoverflow.in/1440

Which of the following statements are TRUE?


1. The problem of determining whether there exists a cycle in an undirected graph is in P.
2. The problem of determining whether there exists a cycle in an undirected graph is in NP.
3. If a problem A is NP-Complete, there exists a non-deterministic polynomial time algorithm to solve A.
(A) 1, 2 and 3 (B) 1 and 2 only (C) 2 and 3 only (D) 1 and 3 only
gate2013

algorithms

p-np-npc-nph

normal

Selected Answer

Cycle detection is graph is in P as it can be done using a graph traversal (O(V+E))


Ref: http://www.geeksforgeeks.org/detect-cycle-undirected-graph/
If a problem is in P then it is also in NP as P is a subset of NP. So, both 1 and 2 are TRUE.
Statement 3 is also true as NP-Complete requires a problem to be in NP and for any problem in NP, we have a nondeterministic polynomial time algorithm.
So, answer is A- 1, 2 and 3 are TRUE.
-- Arjun Suresh ( 124085 points)

4 votes

1.153 P Np Npc Nph: GATE2008_44 top

gateoverflow.in/456

The subset-sum problem is dened as follows: Given a set S of n positive integers and a positive integer W, determine whether there is a subset of S whose
elements sum to W. An algorithm Q solves this problem in O(nW) time. Which of the following statements is false?

A. Q solves the subset-sum problem in polynomial time when the input is encoded in unary
B. Q solves the subset-sum problem in polynomial time when the input is encoded in binary
C. The subset sum problem belongs to the class NP
D. The subset sum problem is NP-hard
gate2008

algorithms

p-np-npc-nph

normal

Selected Answer

Subset problem is NP-Complete - there is reduction proof but I don't remember (Can see the below link). So, (C) and (D)
are true as an NPC problem is in NP as well as NPH.

https://en.wikipedia.org/wiki/Subset_sum_problem

Now, complexity of Q is O(nW), where W is an integer.
(a) Input is encoded in unary. So, length of input is equal to the value of the input. So, complexity = O(nW) where both n
and W are linear multiples of the length of the inputs. So, the complexity is polynomial in terms of the input length. So,
(a) is true.

(b) Input is encoded in binary. So, length of W will be lgW. (for W=1024, input length will be just 10). So, now W is
exponential in terms of the input length of W and O(nW) also becomes exponential in terms of the input lengths. So, Q is
not a polynomial time algorithm. So, (B) is false.
7 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

115 of 1876

1.154 P Np Npc Nph: GATE2005_58 top

gateoverflow.in/1381

Consider the following two problems on undirected graphs:


: Given G(V, E), does G have an independent set of size |V| - 4?
: Given G(V, E), does G have an independent set of size 5?
Which one of the following is TRUE?
A. is in P and is NP-complete
B. is NP-complete and is in P
C. Both and are NP-complete
D. Both and are in P

gate2005

algorithms

p-np-npc-nph

normal

Selected Answer

Independent Set- a set of vertices in a graph no two of which are adjacent.


Maximal Independent set problem - Given a graph G, find the size of the maximal independent set in it. This problem in
NP-hard.
Independent set decision problem - Given a graph G and a number k, does G have an independent set of size k. This
problem is NP-complete (NP-hard but in NP).
Now, in the given problem corresponds to the Independent set decision problem. But there is a difference there. We
h a v e 5 instead of k. And this drastically changes the problem statement. We can now give a polynomial time
deterministic algorithm for .
Find all vertex sets of size 5. We get | V| C5 such vertex sets
For each of them check if there is any adjacent vertices. This check can be done in constant time if we use an
Adjacency matrix representation

( )

Thus the whole time complexity reduces to | V| C5 which is O | V | 5 and hence polynomial. ( | V| Ck is not polynomial but | V| C5 is
).
Problem is asking for an independent set of size | V | 4. This is equivalent to asking if G has a vertex cover of size 4.
Following a similar approach as done for this problem also can be done in polynomial time.
So, both and are in P.
D choice.
Independent Set and Vertex cover Reduction: https://www.cs.cmu.edu/~ckingsf/bioinfo-lectures/npcomplete.pdf
-- Arjun Suresh ( 124085 points)

3 votes

1.155 P Np Npc Nph: GATE2006_16 top

gateoverflow.in/977

Let S be an NP-complete problem and Q and R be two other problems not known to be in NP. Q is polynomial time reducible
to S and S is polynomial-time reducible to R. Which one of the following statements is true?
(A) R is NP-complete
(B) R is NP-hard
(C) Q is NP-complete
(D) Q is NP-hard
gate2006

algorithms

p-np-npc-nph

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

116 of 1876

Selected Answer

Q cannot be NP hard as no np hard problems(unless they are np) can be polynomial time reducible to np complete.
Answer is B, as npc problem can be reducible to np hard problem. But there is confusion if Q is not NP hard then what
complexity class it is in!!
-- Shaun Patel ( 5445 points)

6 votes

1.156 Programming In C: GATE 2016-1-34 top

gateoverflow.in/39704


The following function computes the maximum value contained in an integer array P[] of size n (n >= 1).

int max (int *p,int n) {
int a = 0, b=n-1;
while (__________) {
if (p[a]<= p[b]) {a = a+1;}
else
{b = b-1;}
}
return p[a];
}

The missing loop condition is


A. a! = n
B. b! = 0
C. b > (a + 1)
D. b! = a

gate2016-1

algorithms

programming-in-c

normal

Selected Answer

d, solved through basic C fundamental approach


Option C fails for n = 2, p = [1, 2].
11 votes

-- sukanyac ( 171 points)

1.157 Programming In C: GATE2015-3_30 top

gateoverflow.in/8486

Consider the following two C code segments. Y and X are one and two dimensional arrays of size n and n n respectively,
where 2 n 10. Assume that in both code segments, elements of Y are initialized to 0 and each element X[i][j] of array X is
initialized to i + j. Further assume that when stored in main memory all elements of X are in same main memory page frame.
Code segment 1:
// initialize elements of Y to 0
// initialize elements of X[i][j] of X to i+j
for (i=0; i<n; i++)
Y[i] += X[0][i];

Code segment 2:
// initialize elements of Y to 0
// initialize elements of X[i][j] of X to i+j
for (i=0; i<n; i++)
Y[i] += X[i][0];

Which of the following statements is/are correct?


S1: Final contents of array Y will be same in both code segments
S2: Elements of array X accessed inside the for loop shown in code segment 1 are contiguous in main memory
S3: Elements of array X accessed inside the for loop shown in code segment 2 are contiguous in main memory

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

117 of 1876


A. Only S2 is correct
B. Only S3 is correct
C. Only S1 and S2 are correct
D. Only S1 and S3 are correct
gate2015-3

algorithms

programming-in-c

normal

Selected Answer

option C. Only S1 and S2 are correct because Y have same element in both code and in code1

Y[i] += X[0][i];
this row major order (In C, arrays are stored in row-major order) which gives address of each element in
sequential order(1,2,3,....,n) means we cross single element each time to move next shows contiguous in main memory
but in code2 for

Y[i] += X[i][0];
we are crossing n element (row crossing with n element )to move next


-- Anoop Sonkar ( 4167 points)

9 votes

answer will be c
as s1 is right(final contents are same ) and s2 as we are getting
consider size of 4
y[0]=0(same as x[0][0])
y[1]=2(as x[0][1]=0+1=1 and y[1]=0+1)
y[2]=1(x[0][2]=0+2=2 and y[2]=0+2)
thus following row major order as in c
-- sourav anand ( 1565 points)

1 votes

1.158 Quicksort: TIFR2012-B-14 top

gateoverflow.in/25209

Consider the quick sort algorithm on a set of n numbers, where in every recursive subroutine of the algorithm, the algorithm
chooses the median of that set as the pivot. Then which of the following statements is TRUE?
a. The running time of the algorithm is (n).
b. The running time of the algorithm is (nlogn).
c. The running time of the algorithm is (n1.5).
d. The running time of the algorithm is (n2 ).
e. None of the above.
tifr2012

algorithms

sorting

quicksort

Selected Answer

Algorithm is choosing median = n/2 smallest element as pivot.


Hence, the array is divided as:

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

118 of 1876

Median at

( )
2 1

( )
n 2

n
2 th

elements

location

elements

Therefore quick sort recurrence relation is given by:


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

( ) ( )

+ (n)

= (nlogn)

Hence, Option B is the correct answer.


-- Umang Raman ( 10379 points)

4 votes

1.159 Quicksort: GATE1992_03,iv top

gateoverflow.in/581

Assume that the last element of the set is used as partition element in Quicksort. If n distinct elements from the set [1n]
are to be sorted, give an input for which Quicksort takes maximum time.
gate1992

algorithms

sorting

quicksort

easy

Selected Answer

The algorithm will take maximum time when:


1) The array is already sorted in same order.
2) The array is already sorted in reverse order.
3) All elements are same in the array.
-- Rajarshi Sarkar ( 27781 points)

7 votes

1.160 Radix Sort: GATE2008-IT_43 top

gateoverflow.in/3353

If we use Radix Sort to sort n integers in the range nk/ 2 , nk , for some k > 0 which is independent of n, the time taken would
be?
A) (n)
B) (kn)
C) (nlogn)
D) (n2 )
gate2008-it

algorithms

sorting

radix-sort

normal

Answer: C
The complexity of Radix Sort is O(wn), for n keys which are integers of word size w.
Here, w = log2 (nk) = k log2 (n)
So, the complexity is O(wn) = O(k log2 (n) n), which leads to option C.
7 votes

1.161 Recurrence: TIFR2015-B-1 top

Copyright GATE Overflow. All rights reserved.

-- Rajarshi Sarkar ( 27781 points)

gateoverflow.in/29657

GATE Overflow

April 2016

119 of 1876

Consider the following recurrence relation:


T(n) =

2T( n) + logn

if n 2

if n = 1

Which of the following statements is TRUE?


a. T(n) is O(logn).
b. T(n) is O(logn. loglogn) but not O(logn).
c. T(n) is O(log3 / 2 n) but not O(logn. loglogn).
d. T(n) is O(log2 n) but not O(log3 / 2 n).
e. T(n) is O(log2 n. loglogn) but not O(log2 n).

tifr2015

algorithms

recurrence

time-complexity

Selected Answer

Let n = 2k

( )

( )

T 2k = 2T 2k/ 2 + k

( )

( )

Let T 2k = S(k)  T 2k/ 2 = S(k/2)


S(k) = 2S(k/2) + k
This gives S(k) = (klogk) (Master theorem case 2)
= (lognloglogn)
So ans is b
-- Pooja ( 22745 points)

0 votes

1.162 Recurrence: GATE2004_84 top

gateoverflow.in/1078

The recurrence equation


T(1) = 1

T(n) = 2T(n 1) + n, n 2

evaluates to
(a) 2n +1 n 2 (b) 2n n (c) 2n +1 2n 2 (d) 2n + n
gate2004

algorithms

recurrence

normal

Selected Answer

T(n) = 2T(n 1) + n, n >= 2, T(1) = 1


T(n) = n + 2(n 1) + 22 (n 2) + + 2 (n 1 ) (n (n 1))
= n(1 + 2 + + 2n 1 ) (1.2 + 2.22 + 3.23 + + (n 1).2n 1 )
= n(2n 1) (n.2n 2n +1 + 2)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

120 of 1876

= 2n +1 n 2
-- suraj ( 3299 points)

11 votes

T(1) = 1
T(2) = 4
T(3) = 11
T(4) = 26
T(5) = 57
T(6) = 120
T(7) = 247
So,
T(n) = 2n +1 n 2
-- Arjun Suresh ( 124085 points)

14 votes

1.163 Recurrence: GATE2004-IT_57 top

gateoverflow.in/3700

Consider a list of recursive algorithms and a list of recurrence relations as shown below. Each recurrence relation
corresponds to exactly one algorithm and is used to derive the time complexity of the algorithm.

Recurrence Relation

P. Binary search

Recursive Algorithm

I.

T(n) = T(n-k) + T(k) + cn

Q. Merge sort

II. T(n) = 2T(n-1) + 1

R. Quick sort
S. Tower of Hanoi

III. T(n) = 2T(n/2) + cn


IV. T(n) = T(n/2) + 1

Which of the following is the correct match between the algorithms and their recurrence relations?

A)
B)
C)
D)

P-II, Q-III, R-IV, S-I


P-IV, Q-III, R-I, S-II
P-III, Q-II, R-IV, S-I
P-IV, Q-II, R-I, S-III

gate2004-it

algorithms

recurrence

normal

Selected Answer

answer B
-- Sankaranarayanan P.N ( 7645 points)

4 votes

1.164 Recurrence: GATE1996_2.12 top


The recurrence relation
T(1) = 2
n

T(n) = 3T( 4 ) + n
has the solution T(n) equal to

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/2741

GATE Overflow

April 2016

121 of 1876

A. O(n)
B. O(logn)

()
3

C. O n

D. None of the above



gate1996

algorithms

recurrence

normal

Selected Answer

Answer: A
According to Master theorem,
n

T(n) = aT( b ) + f(n) can be expressed as:


T(n) = [nlogb a ][T(1) + u(n)]
f (n )
logb a

n
log4 3

where u(n) = (h(n)) where h(n) = n


= n
= n1 log4 3 as h(n) = nr where r > 0.
So, T(n) = [nlogb a ][T(1) + u(n)] = T(n) = [nlog4 3 ][T(1) + (n1 log4 3 )] = (n1 ).
-- Rajarshi Sarkar ( 27781 points)

1 votes

Master theorem:

< n so it is O(n).
-- Bhagirathi Nayak ( 10239 points)

3 votes

1.165 Recurrence: GATE2005-IT_51 top


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

B)

T(n) = ( n)

C)

T(n) = (n)

D)

T(n) = (nlogn)

gate2005-it

algorithms

recurrence

easy

Selected Answer

Option C it can be done by Master theorem.


nlogb a = nlog2 2 = n.
1

f(n) =

n = n .

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/3812

GATE Overflow

April 2016

122 of 1876

So, f(n) = O nlogb a is true for any real , 0 < < 2 . Hence Master theorem Case 1 satisfied,

T(n) = nlogb a = (n).

-- Bhagirathi Nayak ( 10239 points)

1 votes

1.166 Recurrence: GATE2002_2.11 top

gateoverflow.in/841

The running time of the following algorithm


Procedure A(n)
If n<=2 return (1) else return (A( n));
is best described by
A. O(n)
B. O( log n)
C. O(log log n)
D. O(1)


gate2002

algorithms

recurrence

normal

Selected Answer

The complexity will be the number of times the recursion happens which is equal to the number of times we can take
square root of n recursively, till n becomes 2.

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

( )

T 22 = T(2) + 1 = 2

( )
( )

T 22

T 22

= T(4) + 1 = 3
= T(16) + 1 = 4

So, T(n) = lglgn + 1 = O(loglogn)


6 votes

-- Arjun Suresh ( 124085 points)

log log n.
substitute root n = m then proceed.
1 votes

1.167 Recurrence: GATE2004_83 top


The time complexity of the following C function is (assume n > 0)
int recursive (int n) {
if(n == 1)
return (1);
else
return (recursive (n-1) + recursive (n-1));
}

Copyright GATE Overflow. All rights reserved.

-- Digvijay Pandey ( 26235 points)

gateoverflow.in/1077

GATE Overflow

April 2016

123 of 1876

(a) O(n) (b) O(nlogn) (c) O(n2 ) (d) O(2n )



gate2004

algorithms

recurrence

time-complexity

normal

Selected Answer

Its similar to tower of hanoi problem


T(n) = 2T(n 1) + 1
T(1)=1
T(2)=2.1 + 1 =3
T(3)=2.3 +1 =7
T(4)=2.7 +1 =15 .... .....
T(n)=2.T(n-1)+ 1
we can see that its a pattern getting formed which is t(n) = 2n 1 so it is d O(2n )
-- Bhagirathi Nayak ( 10239 points)

4 votes

1.168 Recurrence: GATE1993_15 top

gateoverflow.in/2312

Consider the recursive algorithm given below:


procedure bubblesort (n);
var i,j: index; temp : item;
begin
for i:=1 to n-1 do
if A[i] > A[i+1] then
begin
temp := A[i];
A[i] := A[i+1];
A[i+1] := temp;
end;
bubblesort (n-1)
end

Let an be the number of times the ifthen statement gets executed when the algorithm is run with value n. Set up the
recurrence relation by defining an in terms of an 1 . Solve for an .
gate1993

algorithms

recurrence

normal

Selected Answer

an = a n-1 + n-1 (n-1 comparisons for n numbers)


an = a n-2 + (n-2) + (n-1)
an = a n-3 + (n-3) + (n-2) + (n-1)
.
.
an = a n-n + (n-n) + (n-(n-1)) + .... + (n-3) + (n-2) + (n-1)
an = 0 + 1 + 2 + ....+ (n-3) + (n-2) + (n-1)
(n 1 ) (n )

which given a n =

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

124 of 1876

-- Rajarshi Sarkar ( 27781 points)

4 votes

1.169 Recurrence: TIFR2014-B-11 top


Consider the following recurrence relation:

{()
n

T(n) =

T k

3n

+T

( )
4

+n

if n 2
if n = 1

Which of the following statements is FALSE?


a. T(n) is O(n3 / 2 ) when k = 3.
b. T(n) is O(nlogn) when k = 3.
c. T(n) is O(nlogn) when k = 4.
d. T(n) is O(nlogn) when k = 5.
e. T(n) is O(n) when k = 5.

tifr2014

algorithms

recurrence

OPTION b is false
c) apply Akra-Bazzi method .
for ex k=4, then eq is T(n)=T(n/4)+T(3n/4)+n
let g(n)=n and a1=1,b1=1/4,a2=1,b2=3/4
then a i (bi)p=1 :: 1 (1/4)p + 1 (3/4) p =1 --> p=1
then T(n)=O(n p(1+ 1n (g(u) / u 1+p).du )
=n(1+ 1n u/u2 du
=n(1+logn)
=O(nlogn) ::option c is correct
d) apply back substitution
if k=5 T(n)=T(n/5) + T(3n/4)+n ---eq1
T(n/5)=T(n/52) + T((1/5)(3/4)n)+n/5
T(3n/4)=T((3/4)((1/5)n)+T((3/4)2n)+3n/4 substitute in eq1
we got T(n)= T(n/52) + 2 T((1/5)(3/4)n)+T((3/4) 2n)+n(1/5+3/4) +n
in the next we get T(n)=T(n/5 3)+--+n(1/5+3/4)2+n(1/5+3/4) +n
T(n)=T(n/53)+--+n(19/20)2+n(19/20) +n
T(n)=T(n/5k) + --+n(1+(19/20)+(19/20)2)+--(19/20)k-1)
T(n)=T(n/5 k)+--+n(-(19/20)k +1)/(1/20))
n/5 k=1 --> k=logn
::T(n)=1+ 20 n- 20 n(19/20) logn)
:: T(n)=O(n) which inturn O(n logn) both d,e are correct
a)by observing option a &b T(n)=(n n) T(n)=O(n logn) and logn=O( n)
so if option b is correct then option a is also correct ----> so option b is false (we can eliminate)

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/27308

GATE Overflow

April 2016

125 of 1876

//up vote if you are agree


-- venky.victory35 ( 363 points)

2 votes

1.170 Recurrence: GATE2009_35 top

gateoverflow.in/1321

The running time of an algorithm is represented by the following recurrence relation:

T(n) =

n3
n

T( 3 ) + cn

otherwise

Which one of the following represents the time complexity of the algorithm?

A. (n)
B. (nlogn)
C. (n2 )
D. (n2 logn)

gate2009

algorithms

recurrence

time-complexity

normal

Selected Answer

a = 1, b = 3, logb a = 0
So nlogb a = n0 = 1
f(n) = n
So, f(n) = (1)
To, check Master theorem case 3, we need c > 0,
f(n/3) cf(n)
c=1
So using case three of master theorem
T(n) = (f(n)) = (n)
answer is a
2 votes

-- Pooja ( 22745 points)

Answer is A.
Case III of Master's Theorem.
2 votes

1.171 Recurrence: GATE1994_1.7 top


The recurrence relation that arises in relation with the complexity of binary search is:

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

gateoverflow.in/2444

GATE Overflow

April 2016

126 of 1876

A. T(n) = T( 2 ) + k, k is a constant
n

B. T(n) = 2T( 2 ) + k, k is a constant


n

C. T(n) = T( 2 ) + logn
n

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

gate1994

algorithms

recurrence

easy

Selected Answer

It is A. searching for only one half of the list. leading to T(n/2) + constant time in comparing and finding mid element.
-- Gate Keeda ( 16619 points)

8 votes

answer is a in binary search once checked with middle value. we need to do the operation only with one half of the array.
-- Sankaranarayanan P.N ( 7645 points)

3 votes

1.172 Recurrence: GATE2003_35 top


Consider the following recurrence relation
T(1) = 1
T(n + 1) = T(n) +  n + 1 for all n 1
The value of T(m 2 ) for m 1 is
m

A. 6 (21m 39) + 4
m

B. 6 4m 2 3m + 5
m

C. 2 3m 2.5 11m + 20 5
m

D. 6 5m 3 34m 2 + 137m 104 + 6




gate2003

algorithms

time-complexity

recurrence

Selected Answer

T(m 2 ) = T(m 2 1) +

= T(m 2 2) +

(m 2 )

(m 2 1)

Copyright GATE Overflow. All rights reserved.


 
+

(m 2 )

gateoverflow.in/925

GATE Overflow

April 2016

= T(m 2 3) +

(m 2 2)

 
+

(m 2 1)

 
+

127 of 1876
(m 2 )

(2)  + (3)  + +

= T(1) +

(m 2 )

= 3 1 + 5 2 + + (2m 1) (m 1) + m (We are taking floor of square root of numbers, and between successive square roots
number of numbers are in the series 3, 5, 7 like 3 numbers from 1..4, 5 numbers from 5 9 and so on).
We can try out options here or solve as shown at end:
Put m = 5, T(25) = 3 1 + 5 2 + 7 3 + 9 4 + 5 = 75
Option A: 59
Option B: 75
Option C: non-integer
Option D: 297.5
So, answer must be B.

T(m 2 )

= 3 1 + 5 2 + + (2m 1) (m 1) + m = m + i =

1m1 (2i +

1). (i) = m + i =

1m1 2i2

+i=m+

(m1 ) .m. (2m1 )

(m1 )m

= 6 6 + 4m 2 2m

n . (n +1 )

[Sum of the first n natural numbers =

.
n . (n +1 ) . (2n +1 )

Sum of the squares of first n natural numbers =

-- Arjun Suresh ( 124085 points)

2 votes

1.173 Recurrence: GATE2008-IT_44 top


When n = 2 2k for some k 0, the recurrence relation
T(n) = (2) T(n/2) + n, T(1) = 1
evaluates to :

A)
B)
C)
D)

(n) (log n + 1)
(n) log n
(n) log (n)
n log n

gate2008-it

algorithms

recurrence

Selected Answer

T(n) =

(2)T

()

()

+ n

lg n

22

+ 2

n
2

+ n

.]

T(1) + lgn n

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/3354

GATE Overflow

April 2016

n + lgnn

n(lgn + 1)

128 of 1876

If we use Master theorem we get option B. But one must know that Matser theorem is used to find the asymptotic bound
and not an EXACT value. And in the question here it explicitly says "evaluates to".
-- Arjun Suresh ( 124085 points)

4 votes

Answer: A
T(1) = 1 is given. Put n = 1 in all options. Only option A gives T(1) = 1.
-- Rajarshi Sarkar ( 27781 points)

4 votes

Using Master's Theorem, Option B is coming


But solving the recurrence equation using back substitution, Option A is coming
As, they have not used Theta notation in the answer, so I am assuming they want the exact solution.
Therefore Answer is (A)
-- Dhananjay ( 657 points)

2 votes

1.174 Recurrence: GATE1997_4.6 top

gateoverflow.in/2247

Let T(n) be the function defined by T(1) = 1, T(n) = 2T( 2 ) + n for n 2.


Which of the following statements is true?
A. T(n) = O n
B. T(n) = O(n)
C. T(n) = O(logn)
D. None of the above
gate1997

algorithms

recurrence

normal

Selected Answer

answer B
using master method (case 1)
where a = 2, b = 2
O(n1/2) < O(n log ba)
O(n1/2) < O(n log 22)

4 votes

1.175 Recurrence: GATE1997_15 top

Copyright GATE Overflow. All rights reserved.

-- ankitrokdeonsns ( 7941 points)

gateoverflow.in/2275

GATE Overflow

April 2016

129 of 1876

Consider the following function.


Function F(n, m:integer):integer;
begin
If (n<=0 or (m<=0) then F:=1
else
F:F(n-1, m) + F(n, m-1);
end;

Use the recurrence relation

() ( ) ( )
n

n1
k

n1
k1

to answer the following questions. Assume that n, m are positive

integers. Write only the answers without any explanation.


a. What is the value of F(n, 2)?
b. What is the value of F(n, m)?
c. How many recursive calls are made to the function F, including the original call, when evaluating F(n, m).

gate1997

algorithms

recurrence

normal

1.176 Recurrence: GATE1992-07b top

gateoverflow.in/43600

Consider the function F(n) for which the pseudocode is given below :
Function F(n)
begin
F1 1
if(n=1) then F 3
else
For i = 1 to n do
begin
C 0
For j = 1 to n 1 do
begin C C + 1 end
F1 = F1 * C
end
F = F1
end

[n is a positive integer greater than zero]


Solve the recurrence relation for a closed form solution of F(n).
gate1992

algorithms

recurrence

descriptive

1.177 Recurrence: GATE1992-07a top

gateoverflow.in/586

Consider the function F(n) for which the pseudocode is given below :

Function F(n)
begin
F1 1
if(n=1) then F 3
else
For i = 1 to n do
begin
C 0
For j = 1 to n 1 do
begin C C + 1 end
F1 = F1 * C
end
F = F1
end

[n is a positive integer greater than zero]


(a) Derive a recurrence relation for F(n)
gate1992

algorithms

recurrence

descriptive

1.178 Recurrence: GATE2015-3_39 top

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/8498

GATE Overflow

April 2016

130 of 1876

Consider the following recursive C function.


void get(int n)
{
if (n<1) return;
get (n-1);
get (n-3);
printf("%d", n);
}

If get(6) function is being called in main() then how many times will the get() function be invoked before returning to the
main()?

A. 15
B. 25
C. 35
D. 45
gate2015-3

algorithms

recurrence

normal

Selected Answer

T(n) = T(n-1) + T(n-3) + 2, here T(n) denotes the number of times a recursive call is made for input n. 2 denotes the two
direct recursive calls.
T(n<=0) = 0
T(1) = 2
T(2) = 4
T(3) = 6
T(4) = 10
T(5) = 16
T(6) = 24
So, answer is 24 + 1 call from main = 25.
-- Arjun Suresh ( 124085 points)

8 votes

Answer: B.
-- Shyam Singh ( 1357 points)

1 votes

1.179 Recurrence: GATE2002_1.3 top


The solution to the recurrence equation T(2k) = 3T(2k1 ) + 1, T(1) = 1 is
A. 2k
(3 k+ 1 1 )
2
B.
log
C. 3 2 k
D. 2log3 k


gate2002

algorithms

recurrence

Selected Answer

Let x = 2k
x

()

T(x) = 3T 2

+1

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/807

GATE Overflow

April 2016

131 of 1876

We can apply Master's theorem case 1 with a = 3 and b = 2 as f(x) = 1 = O xlog2 3

So, T(x) = xlog2 3 = 2k

log 2 3

) (

= 2log2 3

( )

= 3k

So, only option possible is B.

We can also directly solve as follows:


x

()

T(x) = 3T 2

()

+ 1 = 9T 4

+ 1 + 3 = 3log2

2k

+ 1 + 3 + 9 + + 3log2

2 k 1

)(

recursion depth is log2 x and x = 2k = 3k +

OR

T

( ) = 3T ( ) + 1 = ( ) + 1 + 3 = ( ) + (1 + 3 + 9 + +
2k

2k1

32 T

2k2

3k T

2kk

3 log2 2 1

3k1

)(recursion depth is k) =

3 1

(Sum to n terms of GP with a

3 k 1

3k

+ 3 1 (Sum to n terms of GP with a = 1 and r =

-- Arjun Suresh ( 124085 points)

4 votes

1.180 Recurrence: GATE2006_51 top

gateoverflow.in/1829

Consider the following recurrence:


T(n) = 2T

( n ) + 1, T(1) = 1

Which one of the following is true?


(A) T(n) = (loglogn)
(B) T(n) = (logn)
(C) T(n) = ( n)
(D) T(n) = (n)

gate2006

algorithms

recurrence

normal

Selected Answer

( ) (( ) )

T(n) = 2T n

22

+1=2 T n

()

+1 +1=2T n

22

+3=4T n

+ 5 = 2 (lg lg n ) + 2 lglgn + 1 (Proved below) = O(lgn)

1
2k

()
1

23

k
= 2(Putting 2 so that we can take log.One more step of recurrence can't change the complexity.) 2 lgn = 1(Taking log both sides)lgn = 2kk = lglgn

5 votes

1.181 Recurrence: GATE2008-79 top


Let xn denote the number of binary strings of length n that contain no consecutive 0s.

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/43485

GATE Overflow

April 2016

132 of 1876

The value of x5 is
A. 5
B. 7
C. 8
D. 16
gate2008

algorithms

recurrence

normal

Here X1 =0,1(2)
X2=00,01,10,11(total 3)
X3=010,011,101,110,111(total 5)
Here X3=X2+x1
X4=3+5=8
X5=5+8=13
No option matching here.
-- Manojk ( 3327 points)

0 votes

1.182 Recurrence: GATE2015-1_49 top

gateoverflow.in/8355

Let a n represent the number of bit strings of length n containing two consecutive 1s. What is the recurrence relation for an ?
A. an 2 + an 1 + 2n 2
B. an 2 + 2an 1 + 2n 2
C. 2an 2 + an 1 + 2n 2
D. 2an 2 + 2an 1 + 2n 2
gate2015-1

algorithms

recurrence

normal

Selected Answer

Counting the number of bit strings NOT containing two consecutive 1's. (It is easy to derive a recurrence relation for the
NOT case as shown below.)
0 1
00 01 10 - 3 (append both 0 and 1 to any string ending in 0, and append 0 to any string ending in 1)
000 001 010 100 101 - 5 (all strings ending in 0 give two strings and those ending in 1 give 1 string)
0000 0001 0010 0100 0101 1000 1001 1010 - 8
....

an' = a n-1' + a n-2' (where a n denote the number of bit strings of length n containing two consecutive 1s)
2n - an = (2n-1 - a n-1) + (2n-2 - a n-2)
an = 2 n-2(4 - 2 - 1) + a n-1 + a n-2
an = a n-1 + a n-2 + 2 n-2
A choice.

10 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

133 of 1876

For strings with consecutive 1s,



a0=0
a1=0
a2 =11 (total 1) ,
a3= 011,111,110 (3),
a4= 0011,1011,0110,0111,1111,1110,1100,1101 (total 8)...by backtracking,option a and c satisfy a3 and only a satisfies
a4..so a is the answer.
-- Mitari Nagar ( 57 points)

3 votes

1.183 Recurrence: GATE2014-2_13 top

gateoverflow.in/1968

Which one of the following correctly determines the solution of the recurrence relation with T(1) = 1?
n

()

T(n) = 2T 2

+ logn

(A) (n)
(B) (nlogn)
(C) (n2 )
(D) (logn)

gate2014-2

algorithms

recurrence

normal

Selected Answer

f(n) = logn
a = 2, b = 2  nlogb a = n

( )

So, f(n) = logn = O n1 , we can take any from 0-1 for example 0.5 which gives logn = O( (n)), whose proof is given
here: http://math.stackexchange.com/questions/145739/prove-that-logn-o-sqrtn

So, Master theorem Case 1, and answer will be O nlog2 2 = O(n)


Alternate way:
T(1) = 1T(2) = 2T(1) + log2 = 3 = 3n 2T(4) = 2T(2) + log4 = 8 = 3n 4T(8) = 2T(4) + log8 = 19 = 3n 5T(16) = 2T(8) + log16 = 42 = 3n 6
The second term being subtracted is growing at a lower rate than the first term. So, we can say T(n) = O(n).

5 votes

1.184 Recurrence: GATE2008-78 top


Let xn denote the number of binary strings of length n that contain no consecutive 0s.
Which of the following recurrences does xn satisfy?

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/497

GATE Overflow

April 2016

134 of 1876

A. xn = 2xn 1
B. xn = x n / 2  + 1
C. xn = x n / 2  + n

D. xn = xn 1 + xn 2
gate2008

algorithms

recurrence

normal

Selected Answer

0 1 -2
01 10 11 -3
010 011 101 110 111 -5
0101 0110 0111 1010 1011 1101 1110 1111 -8
So, xn = xn-1 + xn-2 (For all the strings ending in 1, we get two new strings and for all strings ending in 0, we get a new
string. So, the new set of strings for n+1, will have exactly n strings ending in 1)
x5 = 8+5 = 13
6 votes

-- Arjun Suresh ( 124085 points)

n=1
0
1
n=2
00 = fails
01
10
11
n=3
so here we will make possible combinations with the above three valid strings of previous case(n=2) only; and to get new
strings of length 3, we can put either zero or 1 on the front of valid strings of the previous case, so we get:
0 01 = fails
0 10
0 11
1 01
1 10
1 11
here in this case we get 5 strings; pattern which option D says resembles here.
answer for Q.78 = option D

answer for Q.79 = x5 = x4 + x3 = 8 + 5 = 13 but no option matches so we select the closest which is option D
its wrong to do like this but.. we are out of choices here.

3 votes

1.185 Recurrence: GATE 2016-2-39 top

-- Amar Vashishth ( 17735 points)

gateoverflow.in/39581

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 ________.
Flow chart for Recursive Function A(n).

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

135 of 1876



gate2016-2

algorithms

time-complexity

recurrence

normal

numerical-answers

Selected Answer

If they are asking for worst case complexity hence,


By calling A(n) we get A(n/2) 5 times,
A(n) = 5A(n/2) + O(1)
Hence by applying masters theorem,
Case 1 : a > bk
nlog2 5
Thus value of alpha will be 2.32
-- Shashank Chavan ( 2439 points)

12 votes

1.186 Recursion: GATE1991_01,x top


Consider the following recursive definition of fib:
fib(n) :=

if n = 0 then 1
else if n = 1 then 1
else fib(n-1) + fib(n-2)

The number of times fib is called (including the first call) for evaluation of fib(7) is___________.

gate1991

algorithms

recursion

recurrence

normal

Selected Answer

The recurrence relation for the no. of calls is


T(n) = T(n 1) + T(n 2) + 2
T(0) = T(1) = 0 (for fib(0) and fib(1), there are no recursive calls).
T(2) = 2
T(3) = 4
T(4) = 8

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/507

GATE Overflow

April 2016

136 of 1876

T(5) = 14
T(6) = 24
T(7) = 40.
Counting the initial call we get 40 + 1 = 41.
-- Arjun Suresh ( 124085 points)

4 votes

Answer: 41
Make the recursion tree.
-- Rajarshi Sarkar ( 27781 points)

1 votes

1.187 Recursion: GATE2002_11 top

gateoverflow.in/864

The following recursive function in C is a solution to the Towers of Hanoi problem.


void move(int n, char A, char B, char C) {
if (......................) {
move (.............................);
printf("Move disk %d from pole %c to pole %c\n", n, A,C);
move (.....................);
}
}

Fill in the dotted parts of the solution.



gate2002

algorithms

recursion

normal

Selected Answer

void move(int n, char A, char B, char C) {


if (n > 0) {
move (n-1, A, C, B);
printf("Move disk %d from pole %c to pole %c\n", n, A, C);
move (n-1, B, A, C);
}
}


7 votes

-- sonam vyas ( 6439 points)

If(n==1) { Printf("\n %s %c %s %c","move disk1 from pole",A,"to pole",B); Return; } Towers(n-1,A,C,B); Printf....
Towers(n-1,C,B,A);
1 votes

1.188 Recursion: GATE2007-IT_27 top

-- Bhagirathi Nayak ( 10239 points)

gateoverflow.in/3460

The function f is defined as follows:



int f (int n) {
if (n <= 1) return 1;
else if (n % 2 == 0) return f(n/2);
else return f(3n - 1);
}

Assuming that arbitrarily large integers can be passed as a parameter to the function, consider the following statements.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

137 of 1876

i. The function f terminates for finitely many different values of n 1.


ii. The function f terminates for infinitely many different values of n 1.
iii. The function f does not terminate for finitely many different values of n 1.
iv. The function f does not terminate for infinitely many different values of n 1.
Which one of the following options is true of the above?

A)
B)
C)
D)

(i) and (iii)


(i) and (iv)
(ii) and (iii)
(ii) and (iv)

gate2007-it

algorithms

recursion

normal

Selected Answer

The function terminates for all powers of 2 (which is infinite), hence (i) is false and (ii) is TRUE.
Let n = 5.
Now, recursive calls will go like 5 - 14 - 7 - 20 - 10 - 5 And this goes into infinite recursion. And if we multiply 5 with any power of 2, also result will be infinite recursion. Since,
there are infinite powers of 2 possible, there are infinite recursions possible (even considering this case only). So, (iv) is
TRUE and (iii) is false.
So, correct answer is (D)

-- Arjun Suresh ( 124085 points)

8 votes

1.189 Recursion: GATE2007_44 top


In the following C function, let n m.
int gcd(n,m) {
if (n%m == 0) return m;
n = n%m;
return gcd(m,n);
}

How many recursive calls are made by this function?



A. (log2 n)
B. (n)
C. (log2 log2 n)
D. ( n)

gate2007

algorithms

recursion

time-complexity

normal

Selected Answer

Worst case will arise when both n and m are consecutive Fibonacci numbers.
gcd(Fn , Fn 1 ) = gcd(Fn 1 , Fn 2 ) = = gcd(F1 , F0 ) = 1
and nth Fibonacci number is 1.618n , where 1.618 is the Golden ratio.

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/1242

GATE Overflow

April 2016

138 of 1876

So, to find gcd(n, m), number of recursive calls will be (logn).



-- Vikrant Singh ( 10051 points)

9 votes

1.190 Recursion: GATE2007_42 top

gateoverflow.in/1240

Consider the following C function:


int f(int n)
{
static int r = 0;
if (n <= 0) return1;
if (n > 3)
{
r = n;
return f(n-2) + 2;
}
return f(n-1) + r;
}

What is the value of f(5)?



A. 5
B. 7
C. 9
D. 18

gate2007

algorithms

recursion

normal

Selected Answer

The answer is D.
f(5) = 18.
f(3) + 2 = 16 + 2 = 18
f(2) + 5 = 11 + 5 = 16
f(1) + 5 = 6 + 5 = 11
f(0) + 5 = 1+5 = 6
Consider from last to first. Since it is recursive function.
4 votes

1.191 Recursion: GATE2007_45 top


What is the time complexity of the following recursive function?
int

DoSomething (int n) {
if (n <= 2)
return 1;
else
return (DoSomething (floor(sqrt(n))) + n);


A. (n2 )
B. (nlog2 n)
C. (log2 n)
D. (log2 log2 n)

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

gateoverflow.in/1243

GATE Overflow

April 2016

139 of 1876


gate2007

algorithms

recursion

time-complexity

normal

Selected Answer

We are asked the time complexity which will be the number of recursive calls in the function as in each call we perform a
constant no. of operations and a recursive call. The recurrence relation for this is (considering constant time "c" as 1)

( )

( )

T(n) = T( n) + 1 = T n1 / 4 + 2 = T n1 / 8 + 3
Going like this we will eventually reach T(3) or T(2). For asymptotic case this doesn't matter and we can assume we reach
T(2) and in next step reach T(1). So, all we want to know is how many steps it takes to reach T(1) which will be 1+ no. of
steps to reach T(2).

()
1

From the recurrence relation we know that T(2) happens when n

2k

= 2.

Taking log and equating,


1
2k

logn = 12k = lognk = loglogn.

So, T(1) happens in loglogn + 1 calls, but for asymptotic complexity we can write as (loglogn)
Alternatively,
Substituting values
T(1) =
T(2) =
T(3) =

T(8) =
T(9) =

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

( (( ) ) ) (( ) )

( ( ( (( ) ) ) ) )

22

2 2

22

( )

=T

2 2
2 2

22

+ 1 = T(22 ) + 2 = T(2) + 3 = 1 + 3 = 4, loglogn = 3 as n = 256.

= 6, loglogn = 5 as n = 65536 65536 = 232

( )

10
T 2 (2 ) = T 2512 + 1 = T(2256 ) + 2 = T(2128 ) + 3 = T(264) + 4 = T(232) + 5 = T(216) + 6 = T(28 ) + 7 = T(24 ) + 8 = T(22 ) + 9 = T(2) + 10 = 11, loglogn = 10

So, answer is D
http://stackoverflow.com/questions/16472012/what-would-cause-an-algorithm-to-have-olog-log-n-complexity
6 votes

1.192 Recursion: GATE2014-2_40 top


Consider the following function
double f(double x){
if( abs(x*x - 3) < 0.01)
return x;
else

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/2000

GATE Overflow

April 2016

140 of 1876

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


}

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

gate2014-2

algorithms

recursion

numerical-answers

normal

Selected Answer

(We can directly go to the "if" part to get one answer, but we need to solve "else" part too to get all possible answers
which though is not asked in question)
Solving the else part:
x

2x

x2 +3

= 2x
x2 +3

So, the new value of x will be 2x and we need it equal to x.


x2 +3
2x

= x  x2 + 3 = 2x2  x2 = 3  x = 1.732


Now solving the if part.
abs(x*x - 3) < 0.01

So, x2 3 < 0.01 and x2 3 < 0.01  x2 < 3.01 and x2 > 2.99  x < 1.735 and x > 1.729
Corrected to 2 decimal places answer should be 1.73 or 1.74.

-- Arjun Suresh ( 124085 points)

4 votes

1.193 Reduction: GATE2015-3_53 top

gateoverflow.in/8562

Language L1 is polynomial time reducible to language L2 . Language L3 is polynomial time reducible to language L2 , which in
turn polynomial time reducible to language L4 . Which of the following is/are true?
I. if L4 P, then L2 P
II. if L1 P or L3 P, then L2 P
III. L1 P, if and only if L3 P
IV. if L4 P, then L3 P

A. II only
B. III only
C. I and IV only
D. I only
gate2015-3

algorithms

reduction

normal

Selected Answer

1. L1 is polynomial time reducible to L2. So, L2 is at least as hard as L1.


2. L3 is polynomial time reducible to L2. So, L2 is at least as hard as L3.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

141 of 1876

3. L2 is polynomial time reducible to L4. So, L4 is at least as hard as L2.



If L4 is in P, L3, L2 and L1 must also be in P. So, I and IV are true.
We can have L1 in P and L2 not in P, and none of the given conditions are violated. So, II is false.
Assume L3 not in P. Now, Since L2 must be at least as hard as L3, it must also be not in P. But L1 is less harder than L1
as per condition 1, and it can be in P without violating any given conditions. So, III is false.
Hence C choice.
More Info: http://gatecse.in/wiki/Some_Reduction_Inferences


-- Arjun Suresh ( 124085 points)

8 votes

from question we can conclude that ...


L1<L2
L3<L2<L4
now take first statement
I. if L4 belongs P, then L2 belongs P this is true because L2 is polynomial time reducible to language L4

II. if L1 belongs P or L3 belongs P, then L2 belongs P not possible because L1, L3 is is polynomial time reducible to
language L2, not L2 is polynomial time reducible to language L1,L2.

III. L1 belongs P, if and only if L3 belongs P this is not true because looking at L3 we can not define L1 or simply we can
say that L1 is not polynomial time reducible to language L3

IV. if L4 belongs P, then L1 belongs P and L3 belongs P this is true because we know that L1<L2 & L3<L2 and L2 is
polynomial time reducible to language L4 so we can say L1&L2 also be polynomial time reducible to language L4.
So option C is correct.
-- Anoop Sonkar ( 4167 points)

2 votes

Option C.
-- sameer2009 ( 1203 points)

2 votes

1.194 Runtime Environments: GATE1994_21 top

gateoverflow.in/2517

Consider the following recursive function:


function fib (n:integer);integer;
begin
if (n=0) or (n=1) then fib := 1
else fib := fib(n-1) + fib(n-2)
end;

The above function is run on a computer with a stack of 64 bytes. Assuming that only return address and parameter are
passed on the stack, and that an integer value and an address takes 2 bytes each, estimate the maximum value of n for
which the stack will not overflow. Give reasons for your answer.

gate1994

algorithms

runtime-environments

recursion

normal

Selected Answer

Size of an activation record = 2 + 2 = 4 bytes.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

142 of 1876

So, no. of possible activation records which can be live at a time = 64/4 = 16.
So, we can have 16 function calls live at a time (recursion depth = 16), meaning the maximum value for n without stack
overflow is 16 (calls from 1-16). For n = 17, stack will overflow.
This is different from the total no. of recursive calls which will be as follows:
n

No. of calls

3
4

5
9

15

25


-- Arjun Suresh ( 124085 points)

4 votes

1.195 Shortest Path: GATE 2016-1-38 top

gateoverflow.in/39731

Consider the weighted undirected graph with 4 vertices, where the weight of edge {i, j} is given by the entry Wij in the matrix
W.

W=

[ ]
0

x 0

The largest possible integer value of x, for which at least one shortest path between some pair of vertices will contain the
edge with weight x is ___________
gate2016-1

algorithms

graph-algorithms

shortest-path

normal

numerical-answers

Selected Answer

Answer is x=12. Here, when we read the last sentence of the question, i.e the largest possible integer value of x. when
x=11 , shortest path is edge with weight x only. But when x=12, there are 2 shortest paths, and we can say that the edge
with weight x is also a shortest path. Atleast 1 shortest path contain edge x. So answer will be 12.
14 votes

-- Sreyas S ( 1273 points)

x = 12
4 votes

1.196 Shortest Path: GATE2008_45 top

-- juxtapose ( 489 points)

gateoverflow.in/457

Dijkstra's single source shortest path algorithm when run from vertex a in the above graph, computes the correct shortest
path distance to

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

143 of 1876


A. only vertex a
B. only vertices a, e, f, g, h
C. only vertices a, b, c, d
D. all the vertices

gate2008

algorithms

graph-algorithms

shortest-path

normal

Selected Answer

(d) all the vertices. Just simulate the Dijkstra's algorithm on it. Dijkstra's algorithm is not meant for graphs with negative edges as it might not always work, but
here it does give the correct shortest path.

-- Arjun Suresh ( 124085 points)

5 votes

Dijkstra's single source shortest path algorithm here this works fine bcoz there is no -ve weight cycle in graph.
-- vinay kumar ( 467 points)

3 votes

1.197 Shortest Path: GATE1996_17 top

gateoverflow.in/2769

Let G be the directed, weighted graph shown in below figure

We are interested in the shortest paths from A.


a. Output the sequence of vertices identified by the Dijkstras algorithm for single source shortest path when the algorithm
is started at node A
b. Write down sequence of vertices in the shortest path from A to E
c. What is the cost of the shortest path from A to E?

gate1996

algorithms

graph-algorithms

shortest-path

normal

AEBDCF
shortest path between A and E is AE itself
length of 2
Someone plz verify this
1 votes

Copyright GATE Overflow. All rights reserved.

-- Gate Mm ( 423 points)

GATE Overflow

April 2016

144 of 1876

1.198 Shortest Path: GATE2012_40 top

gateoverflow.in/1765

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

algorithms

graph-algorithms

shortest-path

normal

Selected Answer


Relaxation at every vertex is as follows
Note the next vertex is taken out here is in RED colour
A

B
C
3(by

s)

S4
B

4(by

s)

7 (4+3 also=7)

(S->d

5(S->B>A)

8(S->A>C->E)

10(S->A->C>E)
10(same so no
change)
10

6(S
>B->C)

7(S->D)

E
T

12(S8
>B->D)
12

12

Now We see for S to T its (S->A->C->E->.T)


which is Option
D
-- Kalpish Singhal ( 1575 points)

9 votes

1.199 Sorting: GATE1991_01,vii top


The minimum number of comparisons required to sort 5 elements is ____
gate1991

normal

algorithms

sorting

Selected Answer

Answer: 7

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/505

GATE Overflow

April 2016

145 of 1876

Minimum number of comparisons = log(n!) = log(5!) = log(120) = 7.


Ref: http://en.wikipedia.org/wiki/Comparison_sort#Number_of_comparisons_required_to_sort_a_list
-- Rajarshi Sarkar ( 27781 points)

4 votes

1.200 Sorting: GATE 2016-1-13 top

gateoverflow.in/39660

The worst case running times of Insertion sort , Merge sort and Quick sort, respectively are:
A. (nlogn), (nlogn) and (n2 )
B. (n2 ), (n2 ) and (nlogn)
C. (n2 ), (nlogn) and (nlogn)
D. (n2 ), (nlogn) and (n2 )

gate2016-1

algorithms

sorting

easy

Selected Answer

Answer is D..
-- Abhilash Panicker ( 6507 points)

7 votes

1.201 Sorting: GATE1991_13 top

gateoverflow.in/540

Give an optimal algorithm in pseudo-code for sorting a sequence of n numbers which has only k distinct numbers (k is not
known a Priori). Give a brief analysis for the time-complexity of your algorithm.
gate1991

sorting

time-complexity

algorithms

difficult

use a hash map with chaining to sort all the numbers in O(n) time and constant space.
-- Amar Vashishth ( 17735 points)

2 votes

1.202 Sorting: GATE2000_17 top

gateoverflow.in/688

An array contains four occurrences of 0, five occurrences of 1, and three occurrences of 2 in any order. The array is to be sorted using swap
operations (elements that are swapped need to be adjacent).

a. What is the minimum number of swaps needed to sort such an array in the worst case?
b. Give an ordering of elements in the above array so that the minimum number of swaps needed to sort the array is maximum.

gate2000

algorithms

sorting

normal

Since swaps are needed to be of adjacent elements only, the algorithm is actually Bubble sort.
In bubble sort, all smaller elements to right of an element are required to be swapped. So if have ordering
[2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0], then we need total 47 swaps, and this will be the worst case.
so it answers actually both parts.
8 votes

Copyright GATE Overflow. All rights reserved.

-- Happy Mittal ( 9253 points)

GATE Overflow

April 2016

1.203 Sorting: GATE2001_1.14 top

146 of 1876

gateoverflow.in/707

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(nlogn)
(C) O(n2 )
(D) O(n!)
gate2001

algorithms

sorting

time-complexity

easy

Selected Answer

In worst case, we may pick pivot elements in the increasing order (input also given in sorted order) which will result in
running time of O(n2 )
Ans. C
-- Vikrant Singh ( 10051 points)

8 votes

1.204 Sorting: GATE1996_2.15 top

gateoverflow.in/2744

Quick-sort is run on two inputs shown below to sort in ascending order


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

gate1996

algorithms

sorting

normal

Selected Answer

C.
both are the worst cases of quick sort.
i) is sorted in ascending order.
ii) is sorted in descending order.
7 votes

1.205 Sorting: GATE2015-1_2 top

-- Gate Keeda ( 16619 points)

gateoverflow.in/8017

Which one of the following is the recurrence equation for the worst case time complexity of the quick sort algorithm for
sorting n ( 2) numbers? In the recurrence equations given in the options below, c is a constant.
A. T(n) = 2 T (n/2) + cn
B. T(n) = T ( n - 1) + T(1) + cn
C. T(n) = 2T ( n - 1) + cn

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

147 of 1876

D. T(n) = T (n/2) + cn
gate2015-1

algorithms

recurrence

sorting

easy

Selected Answer

B.
Worst case for quick sort happens when 1 element is on one list and n-1 elements on another list.
-- Arjun Suresh ( 124085 points)

7 votes

1.206 Sorting: GATE2003_22 top

gateoverflow.in/912

The unusual (n2 ) implementation of Insertion Sort to sort an array uses linear search to identify the position where and
element is to be inserted into the already sorted part of the array. If, instead, we use binary search to identify the position,
the worst case running time will
A. remain (n2 )
B. become (n(logn)2 )
C. become (nlogn)
D. become (n)

gate2003

algorithms

sorting

time-complexity

normal

Selected Answer

In insertion sort, with linear search, it takes


(worst case) n comparisons for searching the right position, and n swaps to make room to place the element.
Hence for n elements, a total of n (n + n); n for search and n for swaps.
= (2n2 ) = (n2 )

If we replace it with binary search, it takes
(worst case) logn comparisons for searching the right position, and n swaps to make room to place the element.
Hence for n elements, a total of n (logn + n); n for search and n for swaps.
= (n logn + n2 ) = (n2 )
Hence answer is A

3 votes

-- ryan sequeira ( 1011 points)

A. Complexity remains same. (n2 )


To place the element x in the correct position first we are finding its correct position in the sorted array using binary
search but we have to make the space for it by shifting all elements to the right, which in worst case may be equal to the
size of the sorted array.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

148 of 1876
-- Vikrant Singh ( 10051 points)

7 votes

1.207 Sorting: TIFR2010-B-23 top

gateoverflow.in/18623

Suppose you are given n numbers and you sort them in descending order as follows:
First find the maximum. Remove this element from the list and find the maximum of the remaining elements, remove this
element, and so on, until all elements are exhausted. How many comparisons does this method require in the worst case?
A. Linear in n.

( )

B. O n2 but not better.


C. O(nlogn)
D. Same as heap sort.

( )

E. O n1.5 but not better.

tifr2010

algorithms

time-complexity

sorting

well it is given that we have to follow the same procedure as stated . so i think it will be option b not better than O(n2).
for first n comparision in worst case then (n-1) thn (n-2) till it becomes 1.
so 1+2 .....+(n-2)+(n-1)+n=n(n+1)/2
O(n2).
-- Ravi Singh ( 7303 points)

0 votes

1.208 Sorting: GATE2006_14 top

gateoverflow.in/975

Which one of the following in place sorting algorithms needs the minimum number of swaps?
(A) Quick sort
(B) Insertion sort
(C) Selection sort
(D) Heap sort
gate2006

algorithms

sorting

easy

Selected Answer

(C) Selection sort


2 votes

-- Keith Kr ( 5467 points)

Selection sort
because in selection the maximum swaps which can take place are O(n)
because we pick up an element an find the minimum(in case of forward sorting) from the next index till the end of array
and than perform the swap
hence O(n) whereas in all other algos the swaps are greater
2 votes

-- ANKUR MAHIWAL ( 127 points)

1.209 Sorting: GATE1992_02,ix top


Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/559

GATE Overflow

April 2016

149 of 1876

Following algorithm(s) can be used to sort n in the range [1.....n3 ] in O(n) time
(a). Heap sort
(b). Quick sort
(c). Merge sort
(d). Radix sort
gate1992

easy

algorithms

sorting

Answer: D
Radix sort complexity is O(wn) for n keys which are integers of word size w.
-- Rajarshi Sarkar ( 27781 points)

2 votes

1.210 Sorting: TIFR2011-B-31 top

gateoverflow.in/20617

Given a set of n = 2k distinct numbers, we would like to determine the smallest and the second smallest using comparisons.
Which of the following statements is TRUE?
a. Both these elements can be determined using 2k comparisons.
b. Both these elements can be determined using n 2 comparisons.
c. Both these elements can be determined using n + k 2 comparisons.
d. 2n 3 comparisons are necessary to determine these two elements.
e. nk comparisons are necessary to determine these two elements.

tifr2011

algorithms

sorting

Selected Answer

Option c) n + k 2
Here is a nice explanation of the algorithm: http://www.codinghelmet.com/?path=exercises/two-smallest

it is solution to the problem known for ages, and it has to do with tennis tournaments. The question was, knowing the
outcome of the tennis tournament, how can we tell which player was the second best? The defeated finalist is a good
candidate, but there are other players that were defeated directly by the tournament winner and any of them could also be
a good candidate for the second best. So the solution to the problem is quite simple: Once the tournament finishes, pick up
the logN competitors that were beaten by the tournament winner and hold a mini-tournament to find which one is the best
among them. If we imagine that better players correspond with smaller numbers, the algorithm now goes like this. Hold the
tournament to find the smallest number (requires N-1 comparisons). During this step, for each number construct the list of
numbers it was smaller than. Finally, pick the list of numbers associated with the smallest number and find their minimum in
logN-1 steps. This algorithm requires N+logN-2 comparisons to complete, but unfortunately it requires additional space
proportional to N (each element except the winner will ultimately be added to someones list); it also requires more time per
step because of the relatively complex enlisting logic involved in each comparison. When this optimized algorithm is applied
to example array, we get the following figure.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

150 of 1876

Tournament held among numbers promotes value 1 as the smallest number. That operation, performed on an array with
nine numbers, requires exactly eight comparisons. While promoting the smallest number, this operation has also flagged
four numbers that were removed from competition by direct comparison with the future winner: 6, 2, 3 and 8 in that order.
Another sequence of three comparisons is required to promote number 2 as the second-smallest number in the array. This
totals 11 comparisons, while naive algorithm requires 17 comparisons to come up with the same result.
All in all, this algorithm that minimizes number of comparisons looks to be good only for real tournaments, while number
cracking algorithms should keep with the simple logic explained above. Implementation of simple algorithm may look like
this:
a array containing n elements
min1 = a[0] candidate for the smallest value
min2 = a[1] candidate for the second smallest value
if min2 < min1
min1 = a[1]
min2 = a[0]
for i = 2 to n 1
if a[i] < min1
min2 = min1
min1 = a[i]
else if a[i] < min2
min2 = a[i]

by Zoran Horvat @zoranh75


-- Pragy Agarwal ( 13675 points)

6 votes

1.211 Sorting: GATE1996_14 top

gateoverflow.in/2766

A two dimensional array A[1..n][1..n] of integers is partially sorted if i, j [1..n 1], A[i][j] < A[i][j + 1] and A[i][j] < A[i + 1][j]
Fill in the blanks:
a. The smallest item in the array is at A[i][j] where i=__ and j=__.
b. The smallest item is deleted. Complete the following O(n) procedure to insert item x (which is guaranteed to be smaller
than any item in the last row or column) still keeping A partially sorted.
procedure insert (x: integer);
var i,j: integer;
begin
i:=1; j:=1, A[i][j]:=x;
while (x > __ or x > __) do
if A[i+1][j] < A[i][j] then begin
A[i][j]:=A[i+1][j]; i:=i+1;
end
else begin
_____
end
A[i][j]:= ____
end


gate1996

algorithms

sorting

normal

Selected Answer

(a). i=1 and j=1 (smallest item in the array)


(b).here in while loop (x>A[i+1][j] or x>A[i][j+1])
A[i][j]:=A[i+1][j]; i:=i+1;
else begin
A[i][j]:=A[i][j+1]; j=j+1;
end
A[i][j]:=x;

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

151 of 1876
-- munna kumar ( 309 points)

5 votes

1.212 Sorting: GATE1999_1.14 top

gateoverflow.in/1467

If one uses straight two-way merge sort algorithm to sort the following elements in ascending order:
20, 47, 15, 8, 9, 4, 40, 30, 12, 17
then the order of these elements after second pass of the algorithm is:
A. 8, 9, 15, 20, 47, 4, 12, 17, 30, 40
B. 8, 15, 20, 47, 4, 9, 30, 40, 12, 17
C. 15, 20, 47, 4, 8, 9, 12, 30, 40, 17
D. 4, 8, 9, 15, 20, 47, 12, 17, 30, 40

gate1999

algorithms

sorting

normal

Selected Answer

20 47 15 8 9 4 40 30 12 17
\ / \ / \ / \ / \ /
20 47 8 15 4 9 30 40 12 17 after 1st pass
\ / \ / \ /
\ / \ / \ /
8,15,20,47 4,9, 30,40 12,17 after 2nd pass

Ans. B
-- Vikrant Singh ( 10051 points)

8 votes

1.213 Sorting: GATE1998_1.22 top


Give the correct matching for the following pairs:
(A) O(logn)
(B) O(n)
(C) O(nlogn)

(P) Selection
(Q) Insertion sort
(R) Binary search

(D) O(n2 )

(S) Merge sort


A. A-R B-P C-Q D-S
B. A-R B-P C-S D-Q
C. A-P B-R C-S D-Q
D. A-P B-S C-R D-Q

gate1998

algorithms

sorting

easy

Selected Answer

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/1659

GATE Overflow

April 2016

152 of 1876

selection sort O(n^2)


merge sort O(nlogn)
binary search (log n)
insertion sort O(n) note if you use O(n^2) here you will not be left with any choice to fill selection sort
-- Bhagirathi Nayak ( 10239 points)

5 votes

1.214 Sorting: GATE2013_6 top

gateoverflow.in/1415

Which one of the following is the tightest upper bound that represents the number of swaps required to sort n numbers
using selection sort?
(A) O(logn)
(B) O(n)
(C) O(nlogn)
(D) O(n2 )
gate2013

algorithms

sorting

easy

Selected Answer

In selection max you can do is n swaps..selecting the smallest element from all the elements and replacing it correct
position so O(n)
-- Bhagirathi Nayak ( 10239 points)

3 votes

1.215 Sorting: GATE2009_39 top

gateoverflow.in/1325

In quick-sort, for sorting n elements, the (n/4)th smallest element is selected as pivot using an O(n) time algorithm. What is
the worst case time complexity of the quick sort?

A. (n)
B. (nlogn)
C. (n2 )
D. (n2 logn)

gate2009

algorithms

sorting

normal

Selected Answer

B.
T(n)= O(n) pivot selection time + T(n/4 - 1) + T(3n/4)
which'll give (nlogn).
Pivot selection complexity is given in questions. Pivot being the (n/4)th smallest element, once it is found, we have two
sub arrays- one of size (n/4 - 1) and other of size (3n/4) and for both of these we solve recursively.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

153 of 1876
-- Gate Keeda ( 16619 points)

8 votes

1.216 Sorting: GATE2009_11 top

gateoverflow.in/1303

What is the number of swaps required to sort n elements using selection sort, in the worst case?

A. (n)
B. (nlogn)
C. (n2 )
D. (n2 logn)

gate2009

algorithms

sorting

easy

Selected Answer

The answer is A.
we have 1 swap in each loop and hence n swaps at max for 1 to n. Therefore the worst case number of swaps is
-- Gate Keeda ( 16619 points)

5 votes

1.217 Sorting: GATE1994_1.19 top

gateoverflow.in/2462

Which of the following algorithm design techniques is used in the quicksort algorithm?
A. Dynamic programming
B. Backtracking
C. Divide and conquer
D. Greedy method

gate1994

algorithms

sorting

easy

Selected Answer

C. it is one of the efficient algorithms in Divide and Conquer strategy.


8 votes

1.218 Sorting: GATE2012_39 top

-- Gate Keeda ( 16619 points)

gateoverflow.in/1762

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(nlogn)
(B) O(n2 logn)
(C) O(n2 + logn)
(D) O(n2 )

Copyright GATE Overflow. All rights reserved.

GATE Overflow
gate2012

April 2016

algorithms

sorting

154 of 1876

normal

Selected Answer

i thought like this:


you are given the first character of each n strings to sort it will take O(nlogn) time..in the worst case we may have to do
the above process 2 times,3 times,........,n times so n*O(nlogn)= O(n^2 logn) please correct me if my approach is
wrong...
-- Bhagirathi Nayak ( 10239 points)

5 votes

1.219 Sorting: GATE2014-1_14 top

gateoverflow.in/1780

Let P be quicksort program to sort numbers in ascending order using the first element as the 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

gate2014-1

algorithms

sorting

easy

Selected Answer

it would be t1>t2, because the first case is the worst case of quicksort i.e. minimum number is chosen as pivot. Hence in
the worst case the comparisons are high.
The splitting occurs as
[1] [2345]
[2] [345]
[3] [45]
[4] [5]
and
[123] [45]
[1] [23] [4][5]
[2] [3]
Number of recursive calls remain the same, but in second case the number of elements passed for the recursive call is less
and hence the number of comparisons also less.
-- Parul Agarwal ( 641 points)

3 votes

1.220 Sorting: GATE2014-2_38 top

gateoverflow.in/1997

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 ____.
gate2014-2

algorithms

sorting

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

155 of 1876

The optimal algorithm always chooses the smallest sequences for merging.
20 24 -44, 43 comparisons
30 35 -65, 64 comparisons
44 50 -94, 93 comparisons
65 94 -159, 158 comparisons

so, totally 43 + 64 + 93 + 158 = 358 comparisons.




-- Arjun Suresh ( 124085 points)

17 votes

1.221 Sorting: Gate 1991 Quicksort top

gateoverflow.in/1890

Let P be a Quicksort program to sort numbers in ascending order. Let t1 and t2 be the time taken by the program for the
inputs [1,2,3,4] and [5,4,3,2,1] respectively. Which of the following holds?
a)t1=t2
b)t1>t2
c)t1<t2
d)t1=t2+5log5
My approach:1) if 1st element is chosen as pivot
i)1,2,3,4:- n(n-1)/2 comparisons + nswaps==>6 comp+4swaps = 10units
ii)5,4,3,2,1:- n(n-1)/2comparisons+n(n-1)/2 swaps==>10+10=20 units
2)if last element is chosen as pivot
i)1,2,3,4:- n(n-1)/2 comp+n(n+1)/2 swaps==>6comp+10swaps = 16 units
ii)5,4,3,2,1:- n(n-1)/2comp+nswaps ==>10+5 = 15 units
so t1<=t2...more safely can't we say t1<t2?
sorting

The question seems to be wrong.There should be 5 inputs for the 1st case.otherwise t1<t2
-- Rohan Ghosh ( 1515 points)

0 votes

1.222 Sorting: GATE2006_52 top

gateoverflow.in/1830

The median of n elements can be found in O(n) time. Which one of the following is correct about the complexity of quick sort,
in which median is selected as pivot?
(A) (n)
(B) (nlogn)
(C) (n2 )
(D) (n3 )
gate2006

algorithms

sorting

easy

Selected Answer

as we choose the pivot a median element ...so every time we are going to have good splits guranteed so the best case
O(nlogn)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

156 of 1876

-- Bhagirathi Nayak ( 10239 points)

6 votes

1.223 Sorting: GATE2014-3_14 top

gateoverflow.in/2048

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(n2 )
(B) O(nlogn)
(C) (nlogn)
(D) O(n3 )

gate2014-3

algorithms

sorting

easy

Selected Answer

(A) O(n2 ) is the answer. When we choose the first element as the pivot, the worst case of quick sort comes if the input is
sorted- either in ascending or descending order. Now, when we choose the middle element as pivot, sorted input no longer
gives worst case behaviour. But, there will be some permutation of the input numbers which will be giving the same worst
case behaviour. For example,
1 2 3 4 5 6 7
This array gives worst case behaviour for quick sort when the first element is pivot.
6 4 2 1 3 5 7
This array gives the worst case behaviour of O(n2 ) if we take middle element as the pivot- each split will be 1 element on
one side and n-1 elements on other side. Similarly, for any input, we can have a permutation where the behaviour is like
this. So, whichever element we take as pivot it gives worst case complexity of O(n2 ) as long as pivot is from a fixed
position (not random position as in randomized quick sort).
-- Arjun Suresh ( 124085 points)

9 votes

1.224 Sorting: TIFR2012-B-13 top

gateoverflow.in/25207

An array A contains n integers. We wish to sort A in ascending order. We are told that initially no element of A is more than a
distance k away from its final position in the sorted list. Assume that n and k are large and k is much smaller than n. Which of
the following is true for the worst case complexity of sorting A?
a. A can be sorted with constant . kn comparison but not with fewer comparisons.
b. A cannot be sorted with less than constant . nlogn comparisons.
c. A can be sorted with constant . n comparisons.
d. A can be sorted with constant . nlogk comparisons but not with fewer comparisons.
e. A can be sorted with constant . k2 n comparisons but not fewer.

tifr2012

algorithms

sorting

Selected Answer

Let Array element be {4,3,2,1,7,5,6,9,10,8} and K be 3 here no element is more than 3 distance away from its final
position
So if we take
arr(1 to 6) and sort then surely first three element will be sorted in its final position {12345769108} O(6log6)
then sort arr(3 to 9) then 3 to 6 will be sorted {12345679108} O(6log6)
then at last arr(6 to 9) less than O(6log6) {12345678910}

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

157 of 1876

in general
Sort arr(0 to 2k)
Now we know that arr[0 to k) are in their final sorted positions
and arr(k to 2k) may be not sorted.
Sort arr(k to 3k)
Now we know that arr[k to 2k) are in their final sorted positions
and arr(2k to 3k) may be not sorted.
.
.
.
.
sort till arr(ik..N)
in final sorting there will be less than 2k element.
in each step it will take O(2klog2k)
n

and there will k steps so O(nlogk)


option D.

-- Umang Raman ( 10379 points)

5 votes

1.225 Sorting: TIFR2011-B-39 top

gateoverflow.in/20935

The first n cells of an array L contain positive integers sorted in decreasing order, and the remaining m n cells all contain 0.
Then, given an integer x, in how many comparisons can one find the position of x in L?
a. At least n comparisons are necessary in the worst case.
b. At least logm comparisons are necessary in the worst case.
c. O(log(m n)) comparisons suffice.
d. O(logn) comparisons suffice.
e. O(log(m/n)) comparisons suffice.

tifr2011

algorithms

sorting

Selected Answer

d) O(logn) comparisons suffice.


Since it is possible that m n, we need to restrict ourselves to the first O(n) elements to perform the binary search.
We start with the first element (index i = 1), and check if it is equal to 0. If not, we double the value of i, and check again.
We repeat this process until we hit a 0.
i = 1;
while(arr[i] != 0)
i *= 2;

Once we hit a 0, the largest possible value (worst case) of i can be 2n 2. This will happen if n = 2k + 1 for some k. Then, our
2nd last value of i will be 2k, and then we get 2k+1 , which is equal to 2n 2.
Now that we've hit a 0, and the array contains positive numbers in decreasing order, if x is present in L, it must be in the
first i elements.
We can binary search the first i elements in O(logi) comparisons.

Since the largest possible value of i = 2n 2, our algorithm takes O log(2n 2) = O(logn) comparisons.

4 votes

1.226 Sorting: GATE1999_1.12 top

Copyright GATE Overflow. All rights reserved.

-- Pragy Agarwal ( 13675 points)

gateoverflow.in/1465

GATE Overflow

April 2016

158 of 1876

A sorting technique is called stable if


A. it takes O(nlogn) 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

gate1999

algorithms

sorting

easy

Selected Answer

(b) If it maintains the relative order of occurrence of non-distinct elements.


(from definition of stable sorting)
-- Arjun Suresh ( 124085 points)

5 votes

1.227 Sorting: GATE2007_14 top

gateoverflow.in/1212

Which of the following sorting algorithms has the lowest worse-case complexity?

A. Merge sort
B. Bubble sort
C. Quick sort
D. Selection sort

gate2007

algorithms

sorting

time-complexity

easy

Selected Answer

A.
Irrespective of the input, Merge sort always have a time complexity of (nlogn).
5 votes

-- Gate Keeda ( 16619 points)

Merge sort has lowest worst case time complexity i.e O(nlogn)
2 votes

1.228 Sorting: GATE1995_1.5 top


Merge sort uses
A. Divide and conquer strategy
B. Backtracking approach
C. Heuristic search

Copyright GATE Overflow. All rights reserved.

-- Bhagirathi Nayak ( 10239 points)

gateoverflow.in/2592

GATE Overflow

April 2016

159 of 1876

D. Greedy approach

gate1995

algorithms

sorting

easy

Selected Answer

It is A.
One of the best examples of Divide and conquer strategy.
-- Gate Keeda ( 16619 points)

9 votes

1.229 Sorting: GATE1995_12 top

gateoverflow.in/2648

Consider the following sequence of numbers


92, 37, 52, 12, 11, 25

Use bubblesort to arrange the sequence in ascending order. Give the sequence at the end of each of the first five passes.
gate1995

algorithms

sorting

easy

Selected Answer

1st Pass: 37 52 12 11 25 92
2nd Pass: 37 12 11 25 52 92
3rd Pass: 12 11 25 37 52 92
4th Pass: 11 12 25 37 52 92
5th Pass: 11 12 25 37 52 92
8 votes

1.230 Space Complexity: GATE2005_81 top

-- Gate Keeda ( 16619 points)

gateoverflow.in/1403

double foo(int n)
{
int i;
double sum;
if(n == 0)
{
return 1.0;
}
else
{
sum = 0.0;
for(i = 0; i < n; i++)
{
sum += foo(i);
}
return sum;
}
}

(A) The space complexity of the above code is?


(a) O(1) (b) O(n) (c) O(n!) (d) nn
(b) Suppose we modify the above function foo() and stores the value of foo(i) 0 <= i < n, as and when they are computed.
With this modification the time complexity for function foo() is significantly reduced. The space complexity of the modified
function would be:

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

160 of 1876

(a) O(1) (b) O(n) (c) O(n2 ) (d) n!



gate2005

algorithms

space-complexity

normal

Selected Answer

A. The code here is storing only local variables. So, the space complexity will be the recursion depth- maximum happening
for the last iteration of the for loop- foo(n) - foo(n-1) - foo(n-2) - .... - foo(1) all live giving space complexity O(n).
B. To store the n values we need space complexity O(n). So, the space complexity won't change and will be O(n).
-- Arjun Suresh ( 124085 points)

5 votes

1.231 Spanning Tree: GATE1992_01,ix top

gateoverflow.in/549

Complexity of Kruskals algorithm for finding the minimum spanning tree of an undirected graph containing n vertices and m
edges if the edges are sorted is _______
gate1992

spanning-tree

algorithms

time-complexity

easy

Selected Answer

if all edges are already sorted then this problem will reduced to union-find problem on a graph with E edges and V
vertices.

for each edge (u,v) in E
if(FIND-SET(u) != FIND-SET(v))
UNION(u,v)

FIND-SET(v) and UNION(u,v) runs in (|V|)


where (n) is inverse ackermann function i.e log*(n)
So overall complexity becomes O(|E|.(|V|))
6 votes

1.232 Spanning Tree: TIFR2014-B-4 top

-- Vikrant Singh ( 10051 points)

gateoverflow.in/27174

Consider the following undirected graph with some edge costs missing.

Suppose the wavy edges form a Minimum Cost Spanning Tree for G. Then, which of the following inequalities NEED NOT
hold?

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

161 of 1876

a. cost(a, b) 6.
b. cost(b, e) 5.
c. cost(e, f) 5.
d. cost(a, d) 4.
e. cost(b, c) 4.

tifr2014

algorithms

graph-algorithms

spanning-tree

Now check this diagram , this is forest obtained from above given graph using kruskal algorithm .
So according to the question edge d-e has weight 5 and it is included in the formation of tree . Now if edges b-e and e-f
has weight greater than 5 than its not a problem because still we may get the given tree after connecting edge d-e .
cost of edge b-c 4 may also lead us to the same tree as above though kruskal algo will have choice between c-f and bc.
Now if the edge weight of a-d becomes 4 , in that case it is guaranteed that kruskal will not select edge d-e because its
edge cost is 5 , and hence the tree structure will change . But there can be the case where edge weight is greater than 4
and we still get the same tree . (Because in the question they asked to point out a unnecessary condition but this does not
seem unnecessary .)
Now notice option A . Does the existence of this condition really matter ? No . its not necessary always and hence a need
not condition .

Therefore option A is the answer .

-- Riya Roy ( 4769 points)

3 votes

1.233 Spanning Tree: GATE2005-IT_52 top

gateoverflow.in/3813

Let G be a weighted undirected graph and e be an edge with maximum weight in G. Suppose there is a minimum weight
spanning tree in G containing the edge e. Which of the following statements is always TRUE?

A)
B)
C)
D)

There exists a cutset in G having all edges of maximum weight.


There exists a cycle in G having all edges of maximum weight.
Edge e cannot be contained in a cycle.
All edges in G have the same weight.

gate2005-it

algorithms

spanning-tree

normal

Selected Answer

Option a is always true


Option b is not true when e is not part of a cycle.
Option c is not true when e is part of a cycle and all edge weights are same in that cycle
Option d is need not be true when e is not part of a cycle

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

162 of 1876

Option a is always true as only the min weight edge in a cut set will be part of a minimum spanning tree.
-- Bhagirathi Nayak ( 10239 points)

4 votes

Option A is correct.

Here, in this example we can easily see that B, C, D are false. So, B,C,D are not always true.
that's why A is always true.. A (Ans)
-- Himanshu Agarwal ( 8861 points)

2 votes

1.234 Spanning Tree: TIFR2011-B-35 top

gateoverflow.in/20842

Let G be a connected simple graph (no self-loops or parallel edges) on n 3 vertices, with distinct edge weights. Let
e1 , e2 , . . . , em be an ordering of the edges in decreasing order of weight. Which of the following statements is FALSE?
a. The edge e1 has to be present in every maximum weight spanning tree.
b. Both e1 and e2 have to be present in every maximum weight spanning tree.
c. The edge em has to be present in every minimum weight spanning tree.
d. The edge em is never present in any maximum weight spanning tree.
e. G has a unique maximum weight spanning tree.

tifr2011

algorithms

graph-algorithms

spanning-tree

Option D) The edge e m is never present in any maximum weight spanning tree

let the e m be the pendant edge then it has to be in max spanning tree.
-- Umang Raman ( 10379 points)

1 votes

1.235 Spanning Tree: GATE2012_29 top

gateoverflow.in/786

Let G be a weighted graph with edge weights greater than one and G be the graph constructed by squaring the weights of
edges in G. Let T and T be the minimum spanning trees of G and G , respectively, with total weights t and t . Which of the
following statements is TRUE?

(A) T = T with total weight t = t2

(B) T = T with total weight t < t2

(C) T T but total weight t = t2

(D) None of the above
gate2012

algorithms

spanning-tree

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

marks-to-all

GATE Overflow

April 2016

163 of 1876

When the edge weights are squared the minimum spanning tree won't change.
t < t2 , because sum of squares is always less than the square of the sums except for a single element case.
Hence, B is the general answer and A is also true for a single edge graph. Hence, in GATE 2012, marks were given to all.
-- gatecse ( 9515 points)

7 votes

1.236 Spanning Tree: GATE2001_15 top

gateoverflow.in/756

Consider a weighted undirected graph with vertex set V = {n1, n2, n3, n4, n5, n6} and edge set E = {(n1,n2,2), (n1,n3,8),
(n1,n6,3), (n2,n4,4), (n2,n5,12), (n3,n4,7), (n4,n5,9), (n4,n6,4)}. The third value in each tuple represents the weight of
the edge specified in the tuple.
a. List the edges of a minimum spanning tree of the graph.
b. How many distinct minimum spanning trees does this graph have?
c. Is the minimum among the edge weights of a minimum spanning tree unique over all possible minimum spanning trees
of a graph?
d. Is the maximum among the edge weights of a minimum spanning tree unique over all possible minimum spanning tree
of a graph?

gate2001

algorithms

spanning-tree

normal

Selected Answer

a) edges with weight: 2,3,4,7,9


b) no of distinct minimum spanning tree: 2 (2nd with different edge of weight 4)
c) yes
d) yes
3 votes

-- jayendra ( 5797 points)

Minimum spanning tree:

1 votes

1.237 Spanning Tree: GATE2010-51 top

-- jayendra ( 5797 points)

gateoverflow.in/43328

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}

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

164 of 1876

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. 10
gate2010

normal

algorithms

spanning-tree

Selected Answer


Answer is (B) 8. The possible path is: 1 - 0, 0 - 4, 4 - 2.
1 votes

1.238 Spanning Tree: GATE2011-54 top

-- Ashis Kumar Sahoo ( 721 points)

gateoverflow.in/2162

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.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

165 of 1876

What will be the cost of the minimum spanning tree (MST) of such a graph with n nodes?
1

A. 12 (11n2 5n)
B. n2 n + 1
C. 6n 11
D. 2n + 1

gate2011

algorithms

graph-algorithms

spanning-tree

normal

Selected Answer

Q 54. Answer is B

We observe a pattern in the weight of MST being formed For n=3 (1 + 2 + 3) + (1) For n=4 (1 + 2 + 3 + 4) + (1 + 2) For n=5 (1 + 2 + 3 + 4 + 5) + (1 + 2 + 3) These can be o

-- Sona Praneeth Akula ( 3473 points)

2 votes

1.239 Spanning Tree: GATE2011-55 top

gateoverflow.in/43325

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 withn = 10 is
A. 11
B. 25
C. 31
D. 41

gate2011

algorithms

graph-algorithms

spanning-tree

normal

Answer is C.
It can be easily obtained by drawing graph for up to 7 vertices.
-- Sona Praneeth Akula ( 3473 points)

1 votes

1.240 Spanning Tree: GATE2000_2.18 top

gateoverflow.in/665

L e t G be an undirected connected graph with distinct edge weights. Let emax be the edge with maximum weight and emin the edge with
minimum weight. Which of the following statements is false?

a. Every minimum spanning tree of G must contain emin


b. If emax is in a minimum spanning tree, then its removal must disconnect G
c. No minimum spanning tree contains emax
d. G has a unique minimum spanning tree

gate2000

algorithms

spanning-tree

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

166 of 1876

Selected Answer

C. the case should be written as "may or may not", to be true.


D will always be true as per the question saying that the graph has distinct weights.
-- Gate Keeda ( 16619 points)

7 votes

option a is true. e min should be there in all MST


option b is true - if e max there that means that is the only edge reachable to one of the incident vertices of it. Otherwise
we will select lesser weight edge incident on that vertex, Hence its removal will disconnect G
we cannot infer whether c and d are true always. sometimes they can be false
-- Sankaranarayanan P.N ( 7645 points)

1 votes

1.241 Spanning Tree: GATE2015-3_40 top

gateoverflow.in/8499

Let G be a connected undirected graph of 100 vertices and 300 edges. The weight of a minimum spanning tree of G is 500.
When the weight of each edge of G is increased by five, the weight of a minimum spanning tree becomes ______.
gate2015-3

algorithms

spanning-tree

easy

numerical-answers

Selected Answer

first find no of edges in mst...


mst has n-1 edges where n is no of vertices. 100-1 =99 edges
each 99 edges in mst increases by 5 so weight in mst increased 99*5=495
now total weight of mst =500+495=995
-- Anoop Sonkar ( 4167 points)

10 votes

No of edges =99 , now mention condition 99*5 = 495+500 = 995


-- chaman_amit ( 21 points)

1 votes

1.242 Spanning Tree: GATE1995_22 top


How many minimum spanning trees does the following graph have? Draw them. (Weights are assigned to edges).


gate1995

algorithms

graph-algorithms

Selected Answer

2 only.

Copyright GATE Overflow. All rights reserved.

spanning-tree

easy

gateoverflow.in/2660

GATE Overflow

April 2016

167 of 1876

{AB,BC,AE,BD} and {AB,BC,AE,CD}.


-- Gate Keeda ( 16619 points)

10 votes

1.243 Spanning Tree: GATE2015-1_43 top

gateoverflow.in/8313

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

gate2015-1

algorithms

spanning-tree

normal

Selected Answer

Consider the cycle ABC. AC and AB are part of minimum spanning tree. So, AB should be greater than max(AC, BC)
(greater and not equal as edge weights are given to be distinct), as otherwise we could add AB to the minimum spanning
tree and removed the greater of AC, BC and we could have got another minimum spanning tree. So, AB > 9.
Similarly, for the cycle DEF, ED > 6.
And for the cycle BCDE, CD > 15.
So, minimum possible sum of these will be 10 + 7 + 16 = 33. Adding the weight of spanning tree, we get the total sum of
edge weights
= 33 + 36 = 69
-- Arjun Suresh ( 124085 points)

14 votes

The minimum possible sum of weights of all 8 edges of this graph is 69..
rst we compare A to C and A to B we nd 9 at A to C it means A to B must greater than A to C and for minimum possible
greater value than 9 will b 10 .. so first we conclude 10.
after that we have again two conflict pair B to E and C to D in which we select B to E 15 which C to D possible weight 16.
now we have E to D and F to D in which we select F to D 6 means E to D must be greater than 6 so possible value greater
than 6 is 7 .
so missing weight are
A to B ---->10
C to D---->16
E to D---->7
-- Anoop Sonkar ( 4167 points)

4 votes

1.244 Spanning Tree: TIFR2014-B-5 top

gateoverflow.in/27180

Let G = (V, E) be an undirected connected simple (i.e., no parallel edges or self-loops) graph with the weight function w: E R
on its edge set. Let w(e1 ) < w(e2 ) < < w(em), where E =
of the following statements is FALSE?
a. The tree T has to contain the edge e1 .
b. The tree T has to contain the edge e2 .

Copyright GATE Overflow. All rights reserved.

{e1, e2, . . . , em }. Suppose T is a minimum spanning tree of G. Which

GATE Overflow

April 2016

168 of 1876

c. The minimum weight edge incident on each vertex has to be present in T.


d. T is the unique minimum spanning tree in G.
e. If we replace each edge weight wi = w(ei) by its square w2i , then T must still be a minimum spanning tree of this new
instance.
tifr2014

algorithms

spanning-tree

Selected Answer

Answer is E . The catch here is Edges weights belongs to real number . Therefore edge weight can be negative . In that
case the minimum spanning tree may be different .


-- Riya Roy ( 4769 points)

3 votes

1.245 Spanning Tree: GATE2007_49 top

gateoverflow.in/1247

Let w be the minimum weight among all edge weights in an undirected connected graph. Let e be a specific edge of weight w.
Which of the following is FALSE?

A. There is a minimum spanning tree containing e
B. If e is not in a minimum spanning tree T, then in the cycle formed by adding e to T, all edges have the same weight.
C. Every minimum spanning tree has an edge of weight w
D. e is present in every minimum spanning tree

gate2007

algorithms

spanning-tree

normal

Selected Answer

D is the false statement.


A minimum spanning tree must have the edge with the smallest weight (In Kruskal's algorithm we start from the smallest
weight edge). So, C is TRUE.
If e is not part of a minimum spanning tree, then all edges which are part of a cycle with e, must have weight e, as
otherwise we can interchange that edge with e and get another minimum spanning tree of lower weight. So, B and A are
also TRUE.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

169 of 1876
-- Arjun Suresh ( 124085 points)

4 votes

1.246 Spanning Tree: GATE2010-50 top

gateoverflow.in/2355

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 treeT?
A. 7
B. 8
C. 9
D. 10
gate2010

algorithms

spanning-tree

normal

Selected Answer


Answer is (D) 10. The edges of the spanning tree are: 0 - 1, 1 - 3, 3 - 4, 4 - 2. Total Weight = 10

8 votes

1.247 Spanning Tree: GATE1997_9 top

-- Ashis Kumar Sahoo ( 721 points)

gateoverflow.in/2269

Consider a graph whose vertices are points in the plane with integer co-ordinates (x, y) such that 1 x n and 1 y n, where

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

170 of 1876

n 2 is an integer. Two vertices (x1 , y1 ) and (x2 , y2 ) are adjacent iff x1 x2 1 and y1 y2 1. The weight of an edge
{(x1 , y1 ), (x2 , y2 )} is (x1 x2 )2 + (y1 y2 )2

a. What is the weight of a minimum weight-spanning tree in this graph? Write only the answer without any explanations.
b. What is the weight of a maximum weight-spanning tree in this graph? Write only the answer without any explanations.
gate1997

algorithms

spanning-tree

normal

Selected Answer

A. In the graph start applying Kruskal algorithm. So, we select all edges of cost 1 first.
For each y = i, there will be n 1 unit length path. Total cost = n(n 1)
Then we can join these n lines by one vertical line whose length is n 1.
Total:
n(n 1) + (n 1) = (n 1) (n + 1) = n2 1


B. We can apply Kruskal's algorithm by taking maximum weight edge (ref). Maximum weight edge here is 2 as we are
taking Euclidean distance as mentioned in question.
All diagonals will sum to:

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

171 of 1876

2(n 1) + 2 (2(n 2) + 2(n 3) + + 2 ) = 2(n 1) + 2. (n 1). (n 2) = 2. (n 1)2


(One main diagonal and (n 1) diagonals on either side of it).

Now, we can no more add any edge of weight 2 without forming a cycle.
So, we take 2(n 1) edges of weight 1 to interconnect these diagonals
=

2(n 1)2 + 2(n 1) = 2 (n 1) (n 1 + 2)

2 votes

-- Digvijay Pandey ( 26235 points)

1.248 Spanning Tree: GATE1991_03,vi top

gateoverflow.in/521

Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Kruskals algorithm for finding a minimum spanning tree of a weighted graph G with n vertices and m edges has the time
complexity of:
(a). O(n2 )
(b). O(mn)
(c). O(m + n)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

172 of 1876

(d). O(mlogn)
(e). O(m 2 )

gate1991

algorithms

spanning-tree

easy

Selected Answer

Answer: D
When Union-Find algorithm is used to detect cycle while constructing the MST.
Ref: http://www.geeksforgeeks.org/greedy-algorithms-set-2-kruskals-minimum-spanning-tree-mst/
-- Rajarshi Sarkar ( 27781 points)

3 votes

1.249 Spanning Tree: GATE1996_16 top

gateoverflow.in/2768

A complete, undirected, weighted graph G is given on the vertex {0, 1, , n 1} for any fixed n. Draw the minimum spanning
tree of G if
a. the weight of the edge (u, v) is u v
b. the weight of the edge (u, v) is u + v

gate1996

algorithms

graph-algorithms

spanning-tree

normal

Selected Answer

minimum spanning tree


5 votes

1.250 Spanning Tree: GATE2003_68 top


What is the weight of a minimum spanning tree of the following graph?

Copyright GATE Overflow. All rights reserved.

-- Anu ( 6733 points)

gateoverflow.in/955

GATE Overflow

April 2016

173 of 1876

A. 29
B. 31
C. 38
D. 41


gate2003

algorithms

spanning-tree

normal

Selected Answer

Apply Prim's algorithm, start from A as shown in figure below.


add all the weights in the given figure which would be equal to 31.
1 votes

-- Monanshi Jain ( 5787 points)

Solution: B
The minimum spanning tree is
AC,AD,BG,EI,BD,FH,HI,IJ,GH.
2 votes

1.251 Spanning Tree: GATE2014-2_52 top


The number of distinct minimum spanning trees for the weighted graph below is _____

Copyright GATE Overflow. All rights reserved.

-- Gowthaman Arumugam ( 1079 points)

gateoverflow.in/2019

GATE Overflow

April 2016

gate2014-2

algorithms

spanning-tree

numerical-answers

174 of 1876

normal

Selected Answer

6 is the answer.

-- Arjun Suresh ( 124085 points)

8 votes

1.252 Spanning Tree: GATE2006_11 top

gateoverflow.in/890

Consider a weighted complete graph G on the vertex set {v 1,v2,.....vn} such that the weight of the edge (v i, vj) is
. The weight of a minimum spanning tree of G is:
(A)
(B)

(C)
(D)
gate2006

algorithms

spanning-tree

normal

2(n-1) the spanning tree will traverse adjacent edges since they contain the least weight.
2 votes

None of the options match the Actual answer.


For connecting every i & i+1 node we have edge of weight 2 ,therefore We get 2*(n-1).

Copyright GATE Overflow. All rights reserved.

-- anshu ( 2155 points)

GATE Overflow

April 2016

175 of 1876
-- Akash ( 26265 points)

1 votes

1.253 Spanning Tree: GATE2006_47 top

gateoverflow.in/1823

Consider the following graph:

Which one of the following cannot be the sequence of edges added, in that order, to a minimum spanning tree using
Kruskals algorithm?
(A) (a b), (d f), (b f), (d c), (d e)
(B) (a b), (d f), (d c), (b f), (d e)
(C) (d f), (a b), (d c), (b f), (d e)
(D) (d f), (a b), (b f), (d e), (d c)

gate2006

algorithms

graph-algorithms

spanning-tree

normal

Selected Answer

in kruskal's algo the edges are added in non decreasing order of their weight. But in Option D edge d-e with weight 3 is
added before edge d-c with weight 2. Hence Option D is wrong option
-- Sankaranarayanan P.N ( 7645 points)

4 votes

1.254 Spanning Tree: GATE2005_6 top

gateoverflow.in/1348

An undirected graph G has n nodes. its adjacency matrix is given by an n n square matrix whose (i) diagonal elements are
0s and (ii) non-diagonal elements are 1s. Which one of the following is TRUE?

A. Graph G has no minimum spanning tree (MST)
B. Graph G has unique MST of cost n 1
C. Graph G has multiple distinct MSTs, each of cost n 1
D. Graph G has multiple spanning trees of different costs

gate2005

algorithms

spanning-tree

normal

Selected Answer

Graph has multiple distinct MSTs, each of cost n-1

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

176 of 1876

rom the given data given graph is a complete graph with all edge weights are 1. A MST will contain n-1 edges . Hence
weight of MST is n-1. The graph will have multiple MST. in fact all spanning trees of the given graph wll be MSTs also since
all edge weights are equal.
-- Sankaranarayanan P.N ( 7645 points)

3 votes

1.255 Spanning Tree: GATE2008-IT_45 top

gateoverflow.in/3355

For the undirected, weighted graph given below, which of the following sequences of edges represents a correct execution of
Prim's algorithm to construct a Minimum Spanning Tree?


A)
B)
C)
D)

(a, b), (d, f), (f, c), (g, i), (d, a), (g, h), (c, e), (f, h)
(c, e), (c, f), (f, d), (d, a), (a, b), (g, h), (h, f), (g, i)
(d, f), (f, c), (d, a), (a, b), (c, e), (f, h), (g, h), (g, i)
(h, g), (g, i), (h, f), (f, c), (f, d), (d, a), (a, b), (c, e)

gate2008-it

algorithms

graph-algorithms

spanning-tree

normal

Selected Answer

Prim's algorithm starts with from any vertex and expands the MST by adding one vertex in each step which is close to the
Intermediate MST(made till previous step).
Therefore correct answer would be (C).
(A): (d,f) is chosen but neither d nor f vertices are part of the previous MST(MST made till previous step).
(B): (g,h) is chosen but neither g or h vertices are part of the previous MST(MST made till previous step).
(D): (f,c) is chosen but at that point (f,d) is close to the intermediate MST.
4 votes

-- suraj ( 3299 points)

(C) is the answer.


First thing that we note is that Prims Algorithm, during execution, always GENERATES A SUBSET OF EDGES THAT IS
CONNECTED. So prims algo always generates a connected component during its execution.
second thing to note is that, only getting a connected graph does not suffice here. The edge chosen next must be the
smallest possible edge as per GREEDY strategy.
So lets check the options:
(A) (a,b) if fine .but second edge (d,f) is nowhere connected to previous edge. Therefore (A) is eliminated.
(B) I will sraight away go to the point. In choosing edge (g,h) we scan previous edges and DON'T find 'g' or 'h' in any of
the order pairs. So (g,h) is not adjacent to any of them. So (B) also eliminated. You can do this by marking the graph as
well.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

177 of 1876

(D) In (D) option, at every stage you will find the graph connected BUT lets check for other property: GREEDINESS. When
we choose (f,c) and (f,d) this order violate the greedy approach. Because (f,d) has cost 2 and should be included before
(f,c). Therefore false.
(C) this satisfies all the required properties. TRUE
-- Sandeep_Uniyal ( 5063 points)

2 votes

1.256 Spanning Tree: GATE2009_38 top

gateoverflow.in/1324

Consider the following graph:


Which one of the following is NOT the sequence of edges added to the minimum spanning tree using Kruskals 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)

gate2009

algorithms

spanning-tree

normal

Selected Answer

in option d b-c with weight 4 is added before a-c with weight 3 is added. In kruskal's algorithm edges should be added in
non decreasing order of weight
So option D may be correct
6 votes

1.257 Test Cases: GATE2013-51 top

-- Sankaranarayanan P.N ( 7645 points)

gateoverflow.in/43291

The procedure given below is required to find and replace certain characters inside an input character string supplied in array
A. The characters to be replaced are supplied in array oldc, while their respective replacement characters are supplied in
array newc. Array A has a fixed length of five characters, while arrays oldc and newc contain three characters each.
However, the procedure is flawed.
void find_and_replace (char *A, char *oldc, char *newc) {
for (int i=0; i<5; i++)
for (int j=0; j<3; j++)
if (A[i] == oldc[j])
A[i] = newc[j];
}
The procedure is tested with the following four test cases.
(1) oldc = abc, newc = dab (2) oldc = cde, newc = bcd
(3) oldc = bca, newc = cda (4) oldc = abc, newc = bac
If array A is made to hold the string abcde, which of the above four test cases will be successful in exposing the flaw in this
procedure?

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

178 of 1876

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

algorithms

test-cases

normal

Here when the element of array A and oldc match , we replace that array element of A with array element of newc . For
every element of A array update occurs maximum one time.
Similarly for (2) array element of A has updated with array element of newc less than or equal to one time,

Now, for (3) when i=0 , value of A match with oldc[2] i.e.'a' , and replace with newc[2] i.e. also 'a'. So, no changes
when i=1 value of array A[1]='b'
match with oldc[0]='b' and replace with newc[0]='c'.
Now, A[1]='c' which equal with next element of oldc[1]='c'.
So, replace again with newc[1]='d'.
Now, we can say here in array A[1] value replace with newc[0] value , and that newc[0] value replace with next newc[1]
value.

Similarly for (4) here 2 times replacement for A[0] with element newc[0] and newc[1]
Updating of newc value with another newc value is calling flaw here
So Ans (C)

0 votes

1.258 Test Cases: GATE2013-50 top

-- srestha ( 11537 points)

gateoverflow.in/1557

The procedure given below is required to find and replace certain characters inside an input character string supplied in array

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

179 of 1876

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

The procedure is tested with the following four test cases.


(1) oldc = abc, newc = dab (2) oldc = cde, newc = bcd
(3) oldc = bca, newc = cda (4) oldc = abc, newc = bac
The tester now tests the program on all input strings of length five consisting of characters a, b, c, d and e with
duplicates allowed. If the tester carries out this testing with the four test cases given above, how many test cases will be
able to capture the flaw?
A. Only one
B. Only two
C. Only three
D. All four
gate2013

algorithms

test-cases

normal

Selected Answer

Here when the element of array A and oldc match , we replace that array element of A with array element of newc . For
every element of A array update occurs maximum one time.
Similarly for (2) array element of A has updated with array element of newc less than or equal to one time,

Now, for (3) when i=0 , value of A match with oldc[2] i.e.'a' , and replace with newc[2] i.e. also 'a'. So, no changes
when i=1 value of array A[1]='b'
match with oldc[0]='b' and replace with newc[0]='c'.
Now, A[1]='c' which equal with next element of oldc[1]='c'.
So, replace again with newc[1]='d'.
Now, we can say here in array A[1] value replace with newc[0] value , and that newc[0] value replace with next newc[1]
value.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

180 of 1876


Similarly for (4) here 2 times replacement for A[0] with element newc[0] and newc[1]
Updating of newc value with another newc value is calling flaw here
So Ans B
1 votes

-- srestha ( 11537 points)

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

50. B
51. C
7 votes

-- Vikrant Singh ( 10051 points)

answers:
Q.50 = option B
Q.51 = option C
1 votes

1.259 Time Complexity: GATE2007_15 top


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 n + 1
B. n
C. log2 n

Copyright GATE Overflow. All rights reserved.

-- Amar Vashishth ( 17735 points)

gateoverflow.in/1213

GATE Overflow

April 2016

181 of 1876

D. log2 n + 1

gate2007

algorithms

time-complexity

normal

Selected Answer

Assuming that "comparisons made in the execution of the loop" means that comparison made while loop is executing, last
comparison is not counted.
Say we have j = 7.
Then successful comparisons are 1,2,4. (We get out in next comparison.) So 3 comparisons
Then
A) Incorrect as We get 4 !=3.
B) Incorrect, this is 8.
C) Correct
D) Correct
C & D both gave 3
In C & D for tie breaking, we can take j = 8. No of comparisons (Successful) -> 1,2,4,8.(We get out of loop in 16)
C) 3 != 4. Incorrect
D) 4 Correct

Answer -> D
-- Akash ( 26265 points)

1 votes

1.260 Time Complexity: GATE1990 What is the asymptotic behaviour of T(N)


top

gateoverflow.in/31625

Express T(N) in terms of Harmonic Number


1

Hn = nt=1 i n>= 1
Where T(n) satisfy the recurrance equation
n +1

T(n) = 2 * T(n-1) +1 for n>=2


T(1) = 1
What is the asymptotic behaviour of T(n) in terms of n ?
Please explain me what is harmonic number
time-complexity

algorithms

1.261 Time Complexity: GATE2008-74 top


Consider the following C functions:
int f1 (int n)
{
if(n == 0 || n == 1)
return n;

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/495

GATE Overflow

April 2016

182 of 1876

else
return (2 * f1(n-1) + 3 * f1(n-2));
}
int f2(int n)
{
int i;
int X[N], Y[N], Z[N];
X[0] = Y[0] = Z[0] = 0;
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];
}

The running time of f1(n) and f2(n) are


A. (n) and (n)
B. (2n) and (n)
C. (n) and (2 n)
D. (2n) and (2n)
gate2008

algorithms

time-complexity

normal

Selected Answer

Q.74 = option B
Q.75 = option C
Time complexity of f1 is given by
T(n) = T(n-1) + T(n-2), (multiplication by 2 and 3 won't affect complexity as it is a constant time operation)
T(0) = T(1) = 1
The solution to this (fibonacci series) is given by Golden ratio. https://en.wikipedia.org/wiki/Golden_ratio which is O(2 n).
(Using theta in question must be a mistake)
Time complexity of f2 is (n) as here all recursive calls are avoided by saving the results in an array (dynamic
programming).
So, answer to 74 is (B).
75. Both f1 and f2 are calculating the same function. So,
f1(2) = 2f1(1) + 3f1(0) = 2
f1(3) = 2f1(2) + 3f1(1) = 7
f1(4) = 20
f1(5) = 61
f1(6) = 182
f1(7) = 547
f1(8) = 1640 = f2(8)
6 votes

1.262 Time Complexity: GATE2004_82 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/1076

Let A[1, n] be an array storing a bit (1 or 0) at each location, and f(m) is a function whose time complexity is (m).
Consider the following program fragment written in a C like language:
counter = 0;
for (i=1; i<=n; i++)
{ if a[i] == 1) counter++;
else {f (counter); counter = 0;}
}

The complexity of this program fragment is



A. (n2 )
B. (nlogn) and O(n2 )
C. (n)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

183 of 1876

D. o(n)

gate2004

algorithms

time-complexity

normal

Selected Answer

The key part in the code is "counter = 0" in the else part as we can see below.
Lets take the best case. This happens when a[i] = 1 for all i, and then the loop executes with time complexity (1) for each
iteration and hence overall time complexity of (n) and we can say time complexity of the code fragment is (n) and hence
options a and b are false.
Now, consider the worst case. This happens when a[i] = 0 or when else part is executed. Here, the time complexity of each
iteration will be (counter) and after each else, counter is reset to 0. Let k iterations go to the else part during the worst
case. Then the worst case time complexity will be (x1 ) + (x2 ) + + (xk) + (n k), where xi is the value of the counter
when, A[i] = 0 and f(counter) is called. But due to counter = 0 after each call to f(), we have, x1 + x2 + + xk = n. So,
(x1 ) + (x2 ) + + (xk) + (n k) = (n) + (n k) = (n).

Since the time complexity is (n) and (n) we can say it is (n) - Option (C). (Option D is false because the small o needs
the growth rate to be STRICTLY lower and not equal to or lower as the case for big 0)
If counter = 0 was not there in else part, then time complexity would be (n) and O(n2 ) as in worst case we can have equal
number of 0's and 1's in array a giving time complexity (1) + (2) + + (n/2) + (n/2) would give O(n2 ).
5 votes

-- Arjun Suresh ( 124085 points)

Please note that inside the else condition, f() is called first, then counter is set to 0.
Consider the following cases:
a) All 1s in A[]: Time taken is (n) as
only counter++ is executed n times.
b) All 0s in A[]: Time taken is (n) as
only f(0) is called n times
c) Half 1s, then half 0s: Time taken is (n) as
only f(n/2) is called once.

1 votes

-- Ankit Chourasiya ( 289 points)

I think best case time complexity when all of the array elements contains 1 , then it will be (N) .
and in worst case time complexity when all of the array elements contains 0 . then it will be e(0)+e(0)+....+ e(0) (its totally

depends upon the e(m) . )

or the array elemnt is like this 11111 to m000.... then time complexity 1+1+1......+e(m)+e(m)+....+ e(m) ( then also its
totally depends upon the e(m) . )
1 votes

1.263 Time Complexity: GATE2014-1_42 top


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

Copyright GATE Overflow. All rights reserved.

-- Pranay Datta ( 6199 points)

gateoverflow.in/1920

GATE Overflow

April 2016

184 of 1876

(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.
(D) None of the above.

gate2014-1

algorithms

time-complexity

normal

Total number of multiplications



1

= ni=1 nj=i nk=j +1 1 = ni=1 nj=i(n j) = ni=1 (n i) + (n (i + 1)) + . . . . . + (n n) = 2 ni=1 (n i)(n i + 1) = 2 ni=1 (n2 + n + i2 (2n + 1)i) = 2 n3 + n2 + ni

Therefore, correct answer would be (C).
5 votes

-- suraj ( 3299 points)

i goes 1 to n
j goes i to n
k goes j+1 to n
let's take first iteration for i: as i=1
j goes 1 to n
for j=1 , k: 2 to n = (n-1) times
j=2 , k: 3 to n = (n-2) times
...
j=n-1 , k: n to n = 1 time
j= n , k: 0 times
so, for i=1,
number of multiplications : 1 + 2 + ... + (n-1)
similarly for i = 2,
1+2+ .... + (n-2)
and so on,
for i = (n-1)
1
for i = n
0

so, for every i say last term as T
we have for every i, 1+2+3+... + T = T(T+1)/2 = (T^2 + T)/2
where T goes from 1 to (n-1)
(T^2 + T)/2 , T goes 1 to (n-1) = (n-1)(n)(n+1)/ 6
so, option C is correct

1 votes

Copyright GATE Overflow. All rights reserved.

-- Himanshu Agarwal ( 8861 points)

GATE Overflow

April 2016

185 of 1876

C
Take a simple example with n=3
It will give 4multiplications. For verification take other example with n=4.
Only choice which satisfy is c
-- Anurag Semwal ( 4775 points)

1 votes

1.264 Time Complexity: GATE1999_11 top

gateoverflow.in/1510

a. Consider the following algorithms. Assume, procedure A and procedure B take O(1) and O(1/n) unit of time respectively.
Derive the time complexity of the algorithm in O-notation.
algorithm what (n)
begin
if n = 1 then call A
else
begin
what (n-1);
call B(n)
end
end.

b. Write a constant time algorithm to insert a node with data D just before the node with address p of a singly linked list.


gate1999

algorithms

time-complexity

normal

The recurrence relation for time complexity is


1

T(n) = T(n 1) + n + c (O(1/n) replaced with 1/n and so our answer will also be in O only and not ).

T(n) = T(n 2) +

n 1

+ 2c = T(1) +

++

+ (n 1)c = A(1) +

+ +

+ nc = 1 +

+ + n + nc = logn + nc

(Sum of the first n terms in harmonic series is (logn))


So, our time complexity will be O(n).

4 votes

let A,B,C,D,E,F are data ..


A---> B ----> C----> E ---->F
let pointer to E is p..
a node with data D has to be inserted before E..
i ll do one thing , add D just after node E .. it ll take constant time..
Pnext --->Address_of_D
Address_of_D.next------> Address_of_F
A---> B ----> C----> E -----> D---->F
take a temporary variable and swap the value E and D..
temp = p.data
p.data= p.next.data
p.next.data= temp

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

186 of 1876

now linked list wil look like ..


A---> B ----> C----> D-----> E ---->F
still one more work left.. now pointer p pointing to D so increment pointer p to point data E..
p= p--->next
-- Digvijay Pandey ( 26235 points)

4 votes

1.265 Time Complexity: TIFR2014-B-7 top

gateoverflow.in/27189

Which of the following statements is TRUE for all sufficiently large n?


a. (logn)log log n < 2log n < n1 / 4

b. 2log n < n1 / 4 < (logn)log log n

c. n1 / 4 < (logn)log log n < 2log n

d. (logn)log log n < n1 / 4 < 2log n

e. 2log n < (logn)log log n < n1 / 4

tifr2014

algorithms

time-complexity

Selected Answer

Let us take log before each value

1.(log n) log log n =(log log n)2


2. 2 logn = log n*(log22)= (log n)1/2
3. n 1/4 =1/4 log2n
Now take, n=22^x
1..(log n) log log n =(log log n)2=x2
2. 2 logn = log n*(log22)= (log n)1/2 =2x/2
3. n1/4 =1/4 log2n=1/4*2x
So, Here exponential growth of 2 x is greater than exponential growth of 2 x/2 . So, n1/4 > 2 logn
exponential growth of 2 x is greater than non linear growth of x 2 .So, n1/4>(log n) log log n

exponential growth of 2 x/2 is greater than non linear growth of x 2 .2 logn >(log n) log log n

Correct relation is n1/4 > 2 logn >(log n) log log n

So, (A) is correct answer


5 votes

1.266 Time Complexity: GATE1993_8.7 top

1 kn O(n), where O(n) stands for order n is:

a. O(n)
b. O(n2 )

Copyright GATE Overflow. All rights reserved.

-- srestha ( 11537 points)

gateoverflow.in/2305

GATE Overflow

April 2016

187 of 1876

c. O(n3 )
d. O(3n2 )
e. O(1.5n2 )

gate1993

algorithms

time-complexity

easy

Selected Answer

This is N added itself N times. So it is N 2 . Even if you consider as sum of O(1) + O(2) + .. O(n-1) + O(N). it will add up
to N 2
So answer is
A) O(N) this is false.
B,C,D,E ) All of this are true. We have N 2 here, so all options apart from A are correct.
In fact B = D = E this three options are same. and N 3 is always upper bound of N2. So O(N 3) is also true.
-- Akash ( 26265 points)

2 votes

1.267 Time Complexity: GATE2004_39 top

gateoverflow.in/1036

Two matrices M1 and M2 are to be stored in arrays A and B respectively. Each array can be stored either in row-major or
column-major order in contiguous memory locations. The time complexity of an algorithm to compute M1 M2 will be

A. best if A is in row-major, and B is in column-major order
B. best if both are in row-major order
C. best if both are in column-major order
D. independent of the storage scheme

gate2004

algorithms

time-complexity

easy

Selected Answer

D is correct
Here time complexity is asked, for each access of array element it will be constant,
So the time complexity will not depend upon storage. If at all program execution time is asked
a is true
7 votes

-- Anurag Semwal ( 4775 points)

ans a)
Matrix multiplication takes the rows of M 2 and columns of M 2 in order. So, if the array A is stored in row-major and array
B is stored in column-major, when the first element is accessed, the neighbouring elements (which will be immediately
needed) will also be brought to cache. So, this storage scheme is best for matrix multiplication in terms of execution time.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

188 of 1876
-- Aditi Dan ( 5103 points)

3 votes

1.268 Time Complexity: GATE2007_50 top

gateoverflow.in/1248

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 nlog2 n comparisons are needed
D. None of the above


gate2007

algorithms

time-complexity

easy

divide and conquer gives 1.5n - 2 comparison


-- Digvijay Pandey ( 26235 points)

3 votes

Option B. 3/2n - 2 comparsion Needed.



https://youtu.be/lEvzwEcjQ54?t=1823

-- Prasanna Ranganathan ( 2051 points)

1 votes

1.269 Time Complexity: GATE2007_51 top

gateoverflow.in/1249

Consider the following C program segment:


int IsPrime(n)
{
int i, n;
for (i=2; i<=sqrt(n);i++)
if(n%i == 0)
{printf("Not Prime \n"); return 0;}
return 1;
}

Let T(n) denote number of times the for loop is executed by the program on input n. Which of the following is TRUE?

A. T(n) = O( n) and T(n) = ( n)
B. T(n) = O( n) and T(n) = (1)
C. T(n) = O(n) and T(n) = ( n)
D. None of the above

gate2007

algorithms

time-complexity

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

189 of 1876

Answer = option B
Worst Case : T(n) = O( n)
Best Case : When n = 1 body of for loop is not executed. T(n) = (1)
-- Gate Keeda ( 16619 points)

3 votes

1.270 Time Complexity: GATE2007-IT_17 top

gateoverflow.in/3450

Exponentiation is a heavily used operation in public key cryptography. Which of the following options is the tightest upper
bound on the number of multiplications required to compute bn mod m, 0 b, n m ?

A

O(logn)

O( n)

O log n

O(n)

( )

gate2007-it

algorithms

time-complexity

normal

Selected Answer

Answer is (A)
We need to divide n recursively and compute like following:
n

C1 = b b . In this, we need to calculate b only once.


C2 = b b

C k = b2 b2

k = logn
n

( )

Recurrence relation: T(n) = T 2 + O(1)


T(n) = O(logn)
6 votes

1.271 Time Complexity: GATE2008_47 top

-- Sandeep_Uniyal ( 5063 points)

gateoverflow.in/459

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

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

190 of 1876


gate2008

algorithms

time-complexity

normal

Selected Answer

an insert operation on a binary heap takes O(logn) time, but an alternative approach we can use. which requires us to
insert n elements in heap without any computation i.e. in constant time. after which we can apply Heapify operation(this
operation creates heap in linear time) on the array of those element and Hence obtain a Heap in O(n) time.
-- Amar Vashishth ( 17735 points)

9 votes

Answer is B.
By build Heap method.
-- Gate Keeda ( 16619 points)

2 votes

1.272 Time Complexity: GATE2003_66 top

gateoverflow.in/258

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
by binary notation) is
(A) O(n) but not O(n0.5)
(B) O(n0.5) but not O((logn)k) for any constant k > 0
(C) O((logn)k) for some constant k > 0, but not O((loglogn)m) for any constant m > 0
(D) O((loglogn)k) for some constant k > 0.5, but not O((loglogn)0.5)


gate2003

algorithms

time-complexity

normal

Selected Answer

We can simply do a binary search in the array of natural numbers from 1..n and check if the cube of the number matches n
(i.e., check if a[i] a[i] a[i] == n). In this way we can find the cube root in O(logn). So, options (A) and (B) are wrong.
Now, a number is represented in binary using logn bit. Since each bit is important in finding the cube root, any cube root
finding algorithm must examine each bit at least once. This ensures that complexity of cube root finding algorithm cannot
be lower than logn. (It must be (logn)). So, (D) is also false and (C) is the correct answer.
12 votes

-- gatecse ( 9515 points)

1.273 Time Complexity: TIFR2015-B-3 top

gateoverflow.in/29846

Consider the following code fragment in the C programming language when run on a non-negative integer n.
int f (int n)
{
if (n==0 || n==1)
return 1;
else
return f (n - 1) + f(n - 2);
}

Assuming a typical implementation of the language, what is the running time of this algorithm and how does it compare to
the optimal running time for this problem?
a. This algorithm runs in polynomial time in n but the optimal running time is exponential in n.
b. This algorithm runs in exponential time in n and the optimal running time is exponential in n.
c. This algorithm runs in exponential time in n but the optimal running time is polynomial in n.
d. This algorithm runs in polynomial time in n and the optimal running time is polynomial in n.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

191 of 1876

e. The algorithm does not terminate.


tifr2015

time-complexity

Selected Answer

Ans : C
it is fibanacci series generation. it takes exponential time if we won't use dynamic programming.
if we use dynamic programming then it takes O(n)
-- pramod ( 2071 points)

4 votes

1.274 Time Complexity: GATE2010_12 top

gateoverflow.in/2185

Two alternative packages A and B are available for processing a database having 10k records. Package A requires 0.0001n2 time units and
package B requires 10nlog10n 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

gate2010

algorithms

time-complexity

easy

Selected Answer

10nlog10n 0.0001n2
 10 10klog1010k 0.0001(10k)2
 10k+1 k 0.0001 102k
 k 102kk1 4
 k 10k5
Trying the values, 5 doesn't satisfy this but 6 satisfies.
-- Arjun Suresh ( 124085 points)

8 votes

1.275 Time Complexity: GATE2015-2_22 top

gateoverflow.in/8113

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)

gate2015-2

algorithms

time-complexity

Copyright GATE Overflow. All rights reserved.

easy

GATE Overflow

April 2016

192 of 1876

Selected Answer

Ans O(1), because all elements are distinct, select any three numbers and output 2nd largest from them.
-- Vikrant Singh ( 10051 points)

21 votes

1.276 Time Complexity: GATE2008-75 top


Consider the following C functions:
int f1 (int n)
{
if(n == 0 || n == 1)
return n;
else
return (2 * f1(n-1) + 3 * f1(n-2));
}
int f2(int n)
{
int i;
int X[N], Y[N], Z[N];
X[0] = Y[0] = Z[0] = 0;
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];
}

f1(8) and f2(8) return the values


A. 1661 and 1640
B. 59 and 59
C. 1640 and 1640
D. 1640 and 1661
gate2008

normal

algorithms

time-complexity

Here Ans C. 1640 and 1640


f1(8)

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/43489

GATE Overflow

April 2016

193 of 1876

f2(8) will return

0 votes

1.277 Topological Sort: GATE2014-1_13 top


Consider the directed graph below given.

Which one of the following is TRUE?


(A) The graph does not have any topological ordering.

Copyright GATE Overflow. All rights reserved.

-- Manojk ( 3327 points)

gateoverflow.in/1779

GATE Overflow

April 2016

194 of 1876

(B) Both PQRS and SRQP are topological orderings.


(C) Both PSRQ and SPRQ are topological orderings.
(D) PSRQ is the only topological ordering.

gate2014-1

topological-sort

dfs

easy

Selected Answer

The C option has been copied wrongly


C) Both PSRQ and SPRQ are topological orderings
i)Apply DFS by choosing P or S as starting vertices
ii)As the vertex gets a finishing time assign it to the head of a linked list
iii)The linked list is your required topological ordering
4 votes

-- Akshay Jindal ( 311 points)

choose vertex in the graph which has 0 indegree . now see graph has such two vertices ie P,S so we can start totpological
sort either from vertex P or from Q .
lets first start from vertex P now remove this vertex from graph ,we left with three vertices named asQ,S,R from these
vertices see which vertex has INDEGREE 0,S vertex HAS indegree 0 therefore sequence IS P,S,R,Q
repeat the above step from wuth vertex S we get sequence as S,P,R,Q
5 votes

1.278 Topological Sort: GATE2009 Topological Sorting top

-- kunal chalotra ( 3573 points)

gateoverflow.in/31821

I really doubt this question is correct or not !


As far as my concept understanding topological sorting is done based on DAG
do DFS
write result in decrasing order of finishing time ( reverse post order )
To do DAG we need to select vertex as source .
Source vertex is nothing but that vertex from which no inbound activity. Here , vertex 2 happens to be the source .
So while writing in reverse postorder vertex 2 will begin.
Here all options starts with 1 .
Is my understanding correct ??
Please help me understand the concepts and please do answer this question :)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

topological-sort

algorithms

195 of 1876

graph-algorithms

option bcz d all start from 1


-- Manojk ( 3327 points)

0 votes

1.279 Topological Sort: GATE 2016-1-11 top

gateoverflow.in/39669

Consider the following directed graph:


The number of different topological orderings of the vertices of the graph is _____________.
gate2016-1

algorithms

topological-sort

normal

numerical-answers

Selected Answer

Answer is
a _ _ _ _ f.. blanks spaces are to be filled with b, c, d, e such that b comes before c, and d comes before e..
Number of ways to arrange b,c,d,e such that b comes before c and d comes before e.
4!/(2!*2!) = 6
-- Abhilash Panicker ( 6507 points)

11 votes

1.280 Transactions: GATE 2016-2-22 top

gateoverflow.in/39550

Suppose a database schedule S involves transactions T1 , . . . . . . . . , Tn . Construct the precedence graph of S with vertices
representing the transactions and edges representing the conflicts.If S is serializable, which one of the following orderings of
the vertices of the precedence graph is guaranteed to yield a serial schedule?
A). Topological order
B). Depth-first order
C). Breadth- first order
D). Ascending order of the transaction indices.

gate2016-2

databases

transactions

normal

Selected Answer

Topological Order.
6 votes

A.Topological sort

Copyright GATE Overflow. All rights reserved.

-- Sharathkumar Anbu ( 657 points)

GATE Overflow

April 2016

196 of 1876

In which we first we perform DFS, then we arrange the vertices in decreasing order of finishing time.
This leads to precedence graph and serial schedule only if graph does not contain cycle.
-- Shashank Chavan ( 2439 points)

1 votes

1.281 Trees: GATE2008-IT_12 top

gateoverflow.in/3272

Which of the following is TRUE?



1)
2)
3)
4)

The cost of searching an AVL tree is (log n) but that of a binary search tree is O(n)
The cost of searching an AVL tree is (log n) but that of a complete binary tree is (n log n)
The cost of searching a binary search tree is O (log n ) but that of an AVL tree is (n)
The cost of searching an AVL tree is (n log n) but that of a binary search tree is O(n)

gate2008-it

algorithms

trees

easy

Selected Answer

1) is true as AVL tree is a balanced search tree that has time complexity of searching
can have a completely left/right skewed tree, in which search is O(n).

, but in binary search tree, we

-- Happy Mittal ( 9253 points)

6 votes

1.282 Trees: GATE2014-3_41 top

gateoverflow.in/2075

Consider the pseudocode given below. The function DoSomething() takes as argument a pointer to the root of an arbitrary tree represented by the
leftMostChild rightSibling representation. Each node of the tree is of type treeNode.
typedef struct treeNode* treeptr;
struct treeNode
{
treeptr leftMostChild, rightSibling;
};
int DoSomething (treeptr tree)
{
int value=0;
if (tree != NULL) {
if (tree->leftMostChild == NULL)
value = 1;
else
value = DoSomething(tree->leftMostChild);
value = value + DoSomething(tree->rightSibling);
}
return(value);
}

When the pointer to the root of a tree is passed as the argument to DoSomething, the value returned by the function corresponds to the

(A) number of internal nodes in the tree.


(B) height of the tree.
(C) number of nodes without a right sibling in the tree.
(D) number of leaf nodes in the tree

gate2014-3

algorithms

trees

identify-function

normal

Selected Answer

Here, the condition for count value = 1 is


if (treeleftMostchild == Null)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

197 of 1876

so, if there is no left-most child of the tree (or the sub-tree or the current node called in recursion)
Which means there is no child to that particular node (since if there is no left-most child, there is no child at all as
per the tree representation given).
the node under consideration is a leaf node.
The function recursively counts, and adds to value, whenever a leaf node is encountered.
So, The function returns the number of leaf nodes in the tree.
-- Kalpish Singhal ( 1575 points)

5 votes

1.283 Trees: GATE2004_6 top

gateoverflow.in/1003

Level order traversal of a rooted tree can be done by starting from the root and performing

A. preorder traversal
B. in-order traversal
C. depth first search
D. breadth first search


gate2004

algorithms

trees

easy

Selected Answer

answer = option D
Breadth first seach.
-- anshu ( 2155 points)

2 votes

1.284 Trees: GATE2008-IT_46 top

gateoverflow.in/3356

The following three are known to be the preorder, inorder and postorder sequences of a binary tree. But it is not known
which is which.
I. MBCAFHPYK
II. KAMCBYPFH
III. MABCKYFPH
Pick the true statement from the following.

A)
B)
C)
D)

I and II are preorder and inorder sequences, respectively


I and III are preorder and postorder sequences, respectively
II is the inorder sequence, but nothing more can be said about the other two sequences
II and III are the preorder and inorder sequences, respectively

gate2008-it

algorithms

trees

normal

Selected Answer

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

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

198 of 1876

Therefore, 2 is the preorder and 1 is postorder and the left sequence i.e 3 will definitely be inorder.
So, option d is correct.
5 votes

-- Vivek sharma ( 1177 points)

Answer: D
Binary Tree is:
K
/ \
A Y
/ \ \
M C P
/ / \
B F H
2 votes

-- Rajarshi Sarkar ( 27781 points)

option D)
1 votes

1.285 TIFR2014-B-20 top

-- Laxmi ( 683 points)

gateoverflow.in/27354

Consider the following game. There is a list of distinct numbers. At any round, a player arbitrarily chooses two numbers a, b
from the list and generates a new number c by subtracting the smaller number from the larger one. The numbers a and b are
put back in the list. If the number c is non-zero and is not yet in the list, c is added to the list. The player is allowed to play
as many rounds as the player wants. The score of a player at the end is the size of the final list.
Suppose at the beginning of the game the list contains the following numbers: 48, 99, 120, 165 and 273. What is the score of the
best player for this game?
a. 40
b. 16
c. 33
d. 91
e. 123

tifr2014

algorithms

OPTION d is correct
Here the list is (48, 99, 120, 165 ,273.)
Gcd(48,99)=3 ,means if we subtract(99-48=51) that no is also % 3,
so the no's like (3,6,9----99) are added , total no's=99/3=33
//y Gcd(48,120)=24,so the no's %24 are added like (24,48,---120) ,total no's=120/24=5
//y Gcd(48,165)=3,so the nos(3,6,9,--24--48--99--120---165) are added ,totally 165/3=55
at end Gcd(48,273)=3,so the no's(3,6,9--24---48--99---120--165---273) are added(which covers all the above no's)
so total no"s added to this list=273/3=91
// up vote if you are agree
2 votes

Copyright GATE Overflow. All rights reserved.

-- venky.victory35 ( 363 points)

GATE Overflow

April 2016

199 of 1876

1.286 TIFR2012-B-15 top

gateoverflow.in/25212

Let T be a tree of n nodes. Consider the following algorithm, that constructs a sequence of leaves u1 , u2 . . . . Let u1 be some leaf
of tree. Let u2 be a leaf that is farthest from u1 . Let u3 be the leaf that is farthest from u2 , and, in general, let ui +1 be a leaf of T
that is farthest from ui (if there are many choices for ui +1 , pick one arbitrarily). The algorithm stops when some ui is visited
again. What can u say about the distance between ui and ui +1 , as i = 1, 2, . . . ?
a. For some trees, the distance strictly reduces in each step.
b. For some trees, the distance increases initially and then decreases.
c. For all trees, the path connecting u2 and u3 is a longest path in the tree.
d. For some trees, the distance reduces initially, but then stays constant.
e. For the same tree, the distance between the last two vertices visited can be different, based on the choice of the first
leaf u1 .
tifr2012

algorithms

This post explains it nicely


https://www.quora.com/How-does-following-algorithm-for-finding-longest-path-in-tree-work

1 votes

-- sudipta roy ( 279 points)

1.287 GATE 1999 - Time Complexity top

gateoverflow.in/31768

Match the following


1.T(n) = T(n-1) +n a. O(n)
2. T(n) = T(n/2) +n b.O(nlogn)
3.T(n) = T(n/2) +nlogn c.O(n^2)
4.T(n) = T(n-1) + logn d.O(log^2 n)

The first one I did by substitution and answer came O(n^2), for next two I used master and advanced master theorem and
for 2 i got O(n) and for 3 got O(nlogn) but dont know how to solve no 4,i tried it by substitution i got log(n!) by using
stirling approx which is nlogn also,as it is a gate qs,pls someone give me detailed solution.

algorithms

gate1999

Please see the solution for the 3rd and 4th one using the substitution method -3) T(n)=T(n/2)+nlogn
= nlogn + (n/2)log(n/2)+(n/4)log(n/4)+--------+T(n/2^k)
= nlogn + (n/2)(logn-1)+(n/4)(logn-2)+(n/8)(logn-3)+-----------+T(n/2^k)
= nlogn + (n/2)logn - n/2 + (n/4)logn - n/2 + (n/8)logn - 3n/8 + ------------ = nlogn(1 + 1/2 + 1/4 + 1/8 + -------------------) - n(1/2 + 1/2 + 3/8 + 1/4 + 5/32 + --------)
For the infinite series (1 + 1/2 + 1/4 + 1/8 + -------------------) solution will be 2.
= nlogn*2 - n*(very small value near around 2)
= O(nlogn)

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

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

200 of 1876

= logn + logn + logn + logn + ------------------------------ + logn (we are taking logn as upper bound for Big Oh
notation)
= O(logn * logn)
= O(log^2n)

-- piyushkr ( 213 points)

0 votes

1.288 TIFR2013-B-5 top

gateoverflow.in/25666

Given a weighted directed graph with n vertices where edge weights are integers (positive, zero, or negative), determining
whether there are paths of arbitrarily large weight can be performed in time
a. O(n)
b. O(n. log(n)) but not O(n)
c. O(n1.5) but not O(nlogn)
d. O(n3 ) but not O(n1.5)
e. O(2n ) but not O(n3 )

tifr2013

algorithms

I think arbitrary large weights means having positive weight cycle...so bellmanford algo can be used..O(VE)....changing
sign of weights of edges....
-- Er Lucky ( 309 points)

1 votes

1.289 TIFR2014-B-9 top

gateoverflow.in/27194

Given a set of n distinct numbers, we would like to determine the smallest three numbers in this set using comparisons.
Which of the following statements is TRUE?

a. These three elements can be determined using O log2 n comparisons.


b. O

log2 n

) comparisons do not suffice, however these three elements can be determined using n + O(1) comparisons.

c. n + O(1) comparisons do not suffice, however these three elements can be determined using n + O(logn) comparisons.
d. n + O(logn) comparisons do not suffice, however these three elements can be determined using O(n) comparisons.
e. None of the above.
tifr2014

algorithms

Selected Answer

Option (C) is correct .. Reason is as follows :

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

Here , At first level we are Given n elements , out of which we have to find smallest 3 numbers.
we compare 2 -2 elements as shown in figure & get n/2 elements at Second level.
Note: Minimum element is in these n/2 elements.
So, comparisons for this is n/2..
Similarly for next level we have n/4 Comparisons & n/2 elements..and so on..
Total Comparisons till now is n/2 + n/4 + n/8 + .... + 4 + 2 +1 = (2log n -1) = n-1 {Use G.P. sum}
Now we have to get smallest 3..
We have 1st smallest at last level already => 0 Comparison for this..
=> 2nd & 3rd smallest can be found in O(log n) time as shown below:

Minimum Element must have descended down from some path from top to Bottom..
=> SQUARES represent Candidates for 2nd minimum..
every element that is just below m1(first minimum) is a candidate for second minimum..

Copyright GATE Overflow. All rights reserved.

201 of 1876

GATE Overflow

April 2016

202 of 1876

So, O(log n ) Comparisons for finding second smallest..


=> similarly for 3rd minimum we get O(log n) time.. As, every element that is just below 1st & 2nd
minimum is a candidate for 3rd minimum ..

-- Himanshu Agarwal ( 8861 points)

2 votes

Compare two elements at a time.


n/2 + n/4 + n/8 + + 1 = n
So, with n comparisons we get the smallest element. The second smallest element must be compared with this smallest
element at some point and since we have done logn levels of comparisons, we have logn possibility for this second smallest
element. Similarly, we have an upper bound of logn comparisons for the third smallest element- but we need extra space
to achieve this time complexity. Option C.
-- Arjun Suresh ( 124085 points)

3 votes

All element are distinct


1.Using heap
Make a min heap tree = O(n)
Delete Three element from top = 3logn
+
n + 3logn = n+ O(logn) comparison
2.Using Selection sort
3 pass to get three minimum element
Comparison = n-1+ n-2 +n-3 = 3n-5
Swap =1+1+1 = 3
+
3n+2
3. for(i=0;i<=n;i++) // Min1 Min2 Min3 are first 3 element of array
{
if x < Min1 then, Min3 = Min2; Min2 = Min1; Min1 = x;
else if Min1 < x < Min2 then, Min3 = Min2; Min2 = x;
else if Min2 < x < Min3 then, Min3 = x;
else if Min3 < x skip
}
Worst case 3n comparision
4.using Divide and Conquer
minimum element = n-1 compare
second minimum = log 2n - 1 compare
third minimum = loglog 2n - 1 compare
total = n+log2n + loglog 2n- 3 = n + O(log 2n)
So i think three element can be retrieved in O(n){n + O(logn)} time but comparison cant be n + 0(1) since all 3 element
can be at n*(n-1)*(n-2) location and we have to scan the list at least once and compare the to 3 elements.
Option C.

3 votes

1.290 TIFR2013-B-18 top

-- Umang Raman ( 10379 points)

gateoverflow.in/25865

Let S be a set of numbers. For x S, the rank of x is the number of elements in S that are less than or equal to x. The
procedure Select (S, r) takes a set S of numbers and a rank r(1 r | S | ) and returns the element in S of rank r. The procedure
MultiSelect(S, R) takes a set of numbers S and a list of ranks R =

{r1 < r2 < . . . < rk }, and returns the list {x1 < x2 < . . . < xk } of

elements of S, such that the rank of xi is ri. Suppose there is an implementation for Select (S, r) that uses at most (constant

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

203 of 1876

| S | ) binary comparisons between elements of S. The minimum number of comparisons needed to implement MultiSelect (S, R)
is
a. constant | S | log | S |
b. constant | S |
c. constant | S | | R |
d. constant | R | log | S |
e. constant | S | (1 + log | R | )

tifr2013

algorithms

I think C should be the answer. Using randomized partition algo of quick sort, we can find out kth smallest element in S +
S/2 + S/4 + S/8 + ...... = constant.|S| number of comparisions. For proof see Randomized quick sort algo works in nlogn
time in worst case also.
So for R (equal to S in worst case) number of comparisions equals to constant.|S|.|R|. Correct me if i am wrong.
0 votes

1.291 TIFR2013-B-20 top

-- Aryan ( 223 points)

gateoverflow.in/25878

Suppose n processors are connected in a linear array as shown below. Each processor has a number. The processors need to
exchange numbers so that the numbers eventually appear in ascending order (the processor P1 should have the minimum
value and the the processor Pn should have the maximum value).

The algorithm to be employed is the following. Odd numbered processors and even numbered processors are activated
alternate steps; assume that in the first step all the even numbered processors are activated. When a processor is activated,
the number it holds is compared with the number held by its right-hand neighbour (if one exists) and the smaller of the two
numbers is retained by the activated processor and the bigger stored in its right hand neighbour.
How long does it take for the processors to sort the values?
a. nlogn steps
b. n2 steps
c. n steps
d. n1.5 steps
e. The algorithm is not guaranteed to sort
tifr2013

algorithms

Selected Answer

OPTION C is correct.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

204 of 1876

// up vote if you are agree


3 votes

-- venky.victory35 ( 363 points)

Exact N step take take worst case decresing oder . 1st elemnt come to its coreect place at n th step at the
same time all elemnt goes to its coreect place.
3 votes

1.292 TIFR2014-B-6 top

-- Anirudh Pratap Singh ( 4093 points)

gateoverflow.in/27183

Consider the problem of computing the minimum of a set of n distinct numbers. We choose a permutation uniformly at
random (i.e., each of the n! permutations of 1, . . . . , n is chosen with probability (1/n!) and we inspect the numbers in the
order given by this permutation. We maintain a variable MIN that holds the minimum value seen so far. MIN is initialized to
and if we see a value smaller than MIN during our inspection, then MIN is updated. For example, in the inspection given by
the following sequence, MIN is updated four times.
5 9 4 2 6 8 0 3 1 7
What is the expected number of times MIN is updated?
a. O(1)
b. H n = ni=1 1/i
c. n
d. n/2
e. n

tifr2014

algorithms

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

205 of 1876

Selected Answer

Let us consider 3 numbers {1,2,3}


We will consider the permutation along with min no of times MIN is updated .
Permutation : No of times MIN updated (Minimum)
1,2,3 1
1,3,2 1
2,1,3 2
2,3,1 2
3,1,2 2
3,2,1 3
Total number of times MIN updated is : 11 .
Average no of times MIN updated is : (11/6)
Now going by the options i am getting B .
H3 = 1 + 1/2 + 1/3 = 11/6 .
H3 is the answer and that is option B .
-- Riya Roy ( 4769 points)

4 votes

1.293 GATE2008-81 top

gateoverflow.in/43484

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

gate2008

algorithms

normal

ANS) C ,If LAST ROW and LAST COLUMN entry is 1, then there exists subset whose elements sum to W
-- Shivam Bhardwaj ( 11 points)

0 votes

1.294 TIFR2014-B-10 top

gateoverflow.in/27198

Given a set of n distinct numbers, we would like to determine both the smallest and the largest number. Which of the
following statements is TRUE?

a. These two elements can be determined using O log100 n comparisons.

b. O log100 n comparisons do not suffice, however these two elements can be determined using n + O(logn) comparisons.
c. n + O(logn) comparisons do not suffice, however these two elements can be determined using 3n/2 comparisons.
d. 3n/2 comparisons do not suffice, however these two elements can be determined using 2(n 1) comparisons.
e. None of the above.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

tifr2014

April 2016

206 of 1876

algorithms

I think ans will be C)


to be accurate it will be need 3n/2 -2 comparisons .
-- Pranay Datta ( 6199 points)

3 votes

1.295 GATE2010_34 top

gateoverflow.in/2208

The weight of a sequence a0 , a1 , , an 1 of real numbers is dened as a0 + a1 /2 + + an 1 /2n 1 . A subsequence of a sequence is obtained by
deleting some elements from the sequence, keeping the order of the remaining elements the same. Let X denote the maximum possible
weight of a subsequence of ao , a1 , , an 1 and Y the maximum possible weight of a subsequence of a1 , a2 , , an 1 . Then X is equal to
(A) max(Y, a0 + Y)
(B) max(Y, a0 + Y/2)
(C) max(Y, a0 + 2Y)
(D) a0 + Y/2

gate2010

algorithms

normal

Selected Answer

S = a0 , S1
S1 = a1 , a2 , a3 an 1
Two possible cases arise:
1. a0 is included in the max weight subsequence of S:
Y

In this case, X = weight a0 , S1 = a0 + 2



2. a0 is not included in the max weight subsequence of S:
In this case, X = weight(S1 ) = Y

Y

Since the value of a0 can be anything (negative or < 2 in general) { ai R}, it is possible that Y > a0 + 2 .
The maximum possible weight of a subsequence of S is given by:
Y
X = max Y, a0 + 2

Thus, option B is correct.


10 votes

1.296 GATE2006_15 top


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

Copyright GATE Overflow. All rights reserved.

-- Pragy Agarwal ( 13675 points)

gateoverflow.in/976

GATE Overflow

April 2016

207 of 1876

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)
(B)
(C)
(D)
gate2006

algorithms

normal

Selected Answer

Answer will be theta(n)


j = n/2+n/4+n/2+...+1
number of iteration will be 2^k = n or k = logn
this is in gp find sum till logn = thetha(n)
-- raunak bairoliya ( 329 points)

4 votes

is correct because i gets reduced log2(n) time say for eg


i=16 than
i=8 j=8
i=4 j=12
i=2 j=14
i=1 j=15
i=0
hence
-- ANKUR MAHIWAL ( 127 points)

3 votes

1.297 GATE2006_17 top

gateoverflow.in/978

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 (nlogn)
(D) Solves it in time (n2 )

gate2006

algorithms

normal

Selected Answer

Ans B should be correct.


We can move from right keeping a note of the maximum element(suppose current_max). At the start the right most element will

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

208 of 1876

always be a leader. If an element is greater than our current_max, it will a leader. Add this element to leaders. Set current_max to
this element and carry on leftward. Time Complexity would be O(n)
-- Madhur Rawat ( 2379 points)

5 votes

I think sorting the array using divide and conquer will be a better a idea so option c is correct
-- Bhagirathi Nayak ( 10239 points)

1 votes

1.298 GATE2003_69 top

gateoverflow.in/956

The following are the starting and ending times of activities A, B, C, D, E, F, G and H respectively in chronological order:
as bs cs ae ds ce es fs be de gs ee fe hs ge he. Here, xs denotes the starting time and xe denotes the ending time of activity X. We need to
schedule the activities in a set of rooms available to us. An activity can be scheduled in a room only if the room is reserved
for the activity for its entire duration. What is the minimum number of rooms required?
A. 3
B. 4
C. 5
D. 6

gate2003

algorithms

normal

Selected Answer

Solution: B
The problem can be modeled as a graph coloring problem. Construct a graph with one node corresponding to each activity
$$A,B,C,D,E,F,G and H. Connect the activities that occur between the start and end time of an activity now the chromatic
number of the graph is the number of rooms required.

5 votes

Answer: (B)
Explanation: Room1 As
Room2 Bs
Room3 As
now A ends (Ae) and now Room3 is free

Copyright GATE Overflow. All rights reserved.

-- Gowthaman Arumugam ( 1079 points)

GATE Overflow

April 2016

209 of 1876

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
Source: https://www.gatementor.com/viewtopic.php?f=267&t=2195
-- Prasanna Ranganathan ( 2051 points)

1 votes

1.299 GATE2002_1.5 top

gateoverflow.in/809

In the worst case, the number of comparisons needed to search a single linked list of length n for a given element is
A. logn
n

B. 2
C. log2 n 1
D. n

gate2002

algorithms

easy

Selected Answer

A & C is not correct as we can not do binary search in Linked list.


B seems like average case, be we are asked for worst case.
Worst case is we do not find the element in list. We might end up searching entire list & comparing with each element. So
answer -> D. n
-- Akash ( 26265 points)

1 votes

Since, It is not possible to do a Binary search in Linked List, the Only solution is linear search so its O(n).
-- Prasanna Ranganathan ( 2051 points)

1 votes

1.300 GATE2005_39 top

gateoverflow.in/784

Suppose there are logn sorted lists of n/logn elements each. The time complexity of producing a sorted list of all these
elements is: (Hint:Use a heap data structure)
gate2005

algorithms

normal

Selected Answer

Since we have logn lists we can make a min-heap of logn elements by taking the first element from each of the logn sorted
lists. Now, we start deleting the min-element from the heap and put the next element from the sorted list from which that
element was added to the heap. (This identity can be done by making a structure of two values, one for the number and
one for identifying the origin sorted list of that number and storing this structure in the heap). In this way each delete and
the corresponding insert will take O(loglogn) time as delete in heap of size n is O(logn) and inserting an element on a heap of

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

210 of 1876
n

size n is also O(logn). (here, heap size is logn). Now, we have a total of logn log n = n elements. So, total time will be
O(nloglogn).
-- gatecse ( 9515 points)

8 votes

1.301 GATE2004_41 top

gateoverflow.in/1038

Consider the following C program


main()
{
int x, y, m, n;
scanf("%d %d", &x, &y);
/* Assume x>0 and y>0*/
m = x; n = y;
while(m != n)
{
if (m > n)
m = m-n;
else
n = n-m;
}
printf("%d", n);
}

The program computes



A. x + y using repeated subtraction
B. x mod y using repeated subtraction
C. the greatest common divisor of x and y
D. the least common multiple of x and y


gate2004

algorithms

normal

Selected Answer

It is a simple algorithm of gcd


here while loop executes until m==n
take any two number as m,n and compute it , get the answer
Ans will be (C)
-- srestha ( 11537 points)

2 votes

1.302 GATE1999_1.13 top

gateoverflow.in/1466

Suppose we want to arrange the n numbers stored in any array such that all negative values occur before all positive ones.
Minimum number of exchanges required in the worst case is
A. n 1
B. n
C. n + 1
D. None of the above

gate1999

algorithms

normal

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

211 of 1876

Selected Answer

Answer is (d) None of these


We just require n/2 swaps in the worst case. The algorithm is as given below:
Find positive number from left side and negative number from right side and do exchange. Since, at least one of them
must be less than or equal to n/2, there cannot be more than n/2 exchanges. An implementation is given below:
http://gatecse.in/wiki/Moving_Negative_Numbers_to_the_Beginning_of_Array
-- Arjun Suresh ( 124085 points)

7 votes

1.303 GATE2006_54 top

gateoverflow.in/1832

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 0(3n ) and (2n ) time if hashing is permitted
(B) Takes 0(n3 ) and (n2.5) time in the key comparison mode
(C) Takes (n) time and space
(D) Takes O( n) time only if the sum of the 2n elements is an even number
gate2006

algorithms

normal

Selected Answer

Answer is (C). Following algorithm would do.


Since array is binary, the max sum will go until n and so the sum difference of the two arrays can vary between n and n.
We use array start to keep the starting index of each possible sum (hence of size 2n + 1) and array end to keep the ending
index (these two arrays work like hash tables and since we have only 2n + 1 possible keys, we can do a perfect hashing).
So, our required solution will be max(end[i]-start[i]) provided both are assigned values.
The algorithm works as follows:
1. Initialize diff array to contain the difference of sum of elements of array a and b. i.e., diff[i] = ni=0 a[i] b[i].
2. Now diff[i] can have values from n to n which gives 2n + 1 possible values and the first occurrence of a diff value
marks the beginning of a span and the last occurrence marks the end. We use start and end array for storing these
two positions for the 2n + 1 possible values.
3. Now, the largest value of end[i] - start[i] for any i, will be the largest span and the start of it will be start[i] + 1, and
end will be end[i]. If the span is starting from first position itself (arrays a and b have same first elements), then it
will start from start[i] itself.
#include <stdio.h>
#define size 100 //assume n is less than 100
int main()
{
int n, a[size], b[size];
int start[2*size+1], end[2*size+1];
int sum1 = 0, sum2 = 0, i;
int diff[size];
printf("Enter n: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("Enter a[%d]: ", i);
scanf("%d", &a[i]);
}
for(i = 0; i < n; i++)
{
printf("Enter b[%d]: ", i);
scanf("%d", &b[i]);
}

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

212 of 1876

for(i = 0; i < n; i++)


{
if(a[i]) sum1++;
if(b[i]) sum2++;
diff[i] = sum1 - sum2;
}
for(i = 0; i < 2*n; i++)
start[i] = -1,end[i] = -1;
start[n] = end[n] = 0;
//initially sum is 0 at the beginning of array and
//the first n-1 elements of start and end are used
//if sum of A till ith element is less than sum of B till ith element
for(i=0; i < n; i++)
{
if(start[diff[i] + n] == -1)//interested only in the first occurrence of diff[i]
start[diff[i] + n] = i;
end[diff[i] + n] = i;//interested in the last occurrence of diff[i]
}
int max = -1;
int savei = -1; //savei is for storing the sum having the largest span
for(i = 0; i < 2*n; i++)
{
if(start[i] > -1 && (end[i] - start[i] > max))
{
max = end[i] - start[i];
savei = i;
}
}
if(savei >= 0)
{
printf("The largest span is from %d to %d\n", start[savei]+(savei != n), end[savei]);
//when sum zero is having the largest span, span starts from first element itself.
//Else, the span starts from the next element from which the span does not change
}
else
{
printf("No span\n");
}
}

3 votes

-- Arjun Suresh ( 124085 points)

Answer is C.
3 votes

-- Gate Keeda ( 16619 points)

Simplest approach,
Take XNOR of two arrays, then search the largest span of 1's.
Hence space complexity = O(3n) = O(n) ... (one each for storing A and B and one for answer) , and
Time complexity = O(2n) = O(n) ...(first loop for XNOR, second loop for longest span of 1s)
Pseudo code:
Given: A[], B[]
for(i = 0..n)
C[i] = A[i] XNOR B[i]
max = 0;
counter = 0
for(i = 0..n)
if(C[i] == 1)
counter ++;
else
if(max < counter)
max = counter
counter = 0;

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

213 of 1876




-- ryan sequeira ( 1011 points)

2 votes

1.304 GATE2014-1_37 top

gateoverflow.in/1915

There are 5 bags labeled 1 to 5. All the coins in a given bag have the same weight. Some bags have coins of weight 10 gm, others have coins of weight 11 gm. I
pick 1, 2, 4, 8, 16 coins respectively from bags 1 to 5. Their total weight comes out to 323 gm. Then the product of the labels of the bags having 11 gm coins is
___.

gate2014-1

algorithms

numerical-answers

normal

Selected Answer

There are 5 bags , I assumed initially all bags are having 10 gm coins, and picked them as per the given condition
1,2,4,8,16 of all bags have 10 gm coins then total weight will come to
10 + 20 + 40 + 80+ 160 = 310 but total weight should be 323, but 13 is less, i divided 13 into 1 + 4 + 8
11 + 20 + 44+ 88 + 160, means 1st, 3rd and 4th bags have 11 gm coins. so product of labels will be 1*3*4 = 12
-- Manu Thakur ( 5261 points)

8 votes

Suppose x is no of coins of 11gm and Y is no of 10 gm coins


so according to question 11X+10Y= 323 ...(1)
X+Y=31.....(2) solving (1),(2) we get X=13 and Y=18 so here coins of 11gm are 13 ,and one
and only possible combination for 13= 1 coin from bag1+4 coins from bag3 +8 coins from bag4...
so product of label of bags will be =1*3*4=12..
-- sonam vyas ( 6439 points)

4 votes

1.305 GATE2006_50 top

gateoverflow.in/1828

A set X can be represented by an array x[n] as follows:


x[i] =

1
0

if i X
otherwise

Consider the following algorithm in which x y, and z are Boolean arrays of size n:
algorithm zzz(x[], y[], z[]) {
int i;
for(i=0; i<n; ++i)
z[i] = (x[i]

~y[i])

(~x[i]

y[i]);

The set Z computed by the algorithm is:


(A) (X Y)
(B) (X Y)
(C) (X Y) (Y X)
(D) (X Y) (Y X)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

214 of 1876


gate2006

algorithms

normal

Selected Answer

Option (d)
In the given algorithm the for loop c ontains a logical expression
z[i] = (x[i] ~y[i]) (~x[i] y[i]);
The equivalent set representation of a given logical expression if we assume z[i] = z, X[i] = X, Y[i] = Y then
z = ( X ^ Y' ) V ( X ' ^ Y)
z = ( X - Y ) V ( Y - X ) [A ^ B' = A - B]
-- Prasanna Ranganathan ( 2051 points)

2 votes

experesion AB' + A'B is XOR.. XOR has property that either of A or B is 1 then output is 1 but not both...
this can be achieved by option (D)..
-- Vicky Bajoria ( 3147 points)

2 votes

1.306 GATE1999_8 top

gateoverflow.in/1507

Let A be an n n matrix such that the elements in each row and each column are arranged in ascending order. Draw a
decision tree, which finds 1st, 2nd and 3 rd smallest elements in minimum number of comparisons.
gate1999

algorithms

normal

descriptive

If all elements are distinct we have to check 1st row and 1st column.So complexity will be O(n 2)
Here minimum no of comparison could be 1 , because a[0][0] will be minimum always, now we have to check between
a[0][1] and a[1][0]

if all elements are not distinct we have to search all elements of the array

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

215 of 1876

So, minimum comparison could be O(1)


-- srestha ( 11537 points)

1 votes

1.307 GATE1999_1.16 top

gateoverflow.in/1469

If n is a power of 2, then the minimum number of multiplications needed to compute an is


(a) log2 n
(b) n
(c) n 1
(d) n
gate1999

algorithms

normal

Selected Answer

a. logn
For n = 8, we can do
b=aa
b=bb
b = b b and we get b = a8
3 votes

1.308 GATE2000_16 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/687

A recursive program to compute Fibonacci numbers is shown below. Assume you are also given an array f [ 0......m] with all
elements initialized to 0
fib(n)
if
if
if
if

{
(n > M) error ();
(n == 0) return 1;
(n == 1)return 1;
()________________________(1)
return __________________(2)
t = fib(n - 1) + fib(n - 2);
_____________________________(3)
return t;

A. Fill in the boxes with expressions/statement to make fib() store and reuse computed Fibonacci values. Write the box
number and the corresponding contents in your answer book.
B. What is the time complexity of the resulting program when computing fib(n)?

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

216 of 1876


gate2000

algorithms

normal

Selected Answer

Array f is used to store the fib() values calculated in order to save repeated calls. Since n = 0 and n = 1 are special cases
we can store fib(2) to f[0], fib(3) to f[1] and so on. The missing code completed would be:
if (f[n - 2] != 0){
return f[n-2];
}
t = fib(n-1) + fib(n-2);
f[n-2] = t;
return t;

In this code, fib(i) will do a recursion only once as once fib(i) is calculated it is stored in array. So, the time complexity for
fib(n) would be (n).
PS: We can also store fib(n) in f(n), the above code just saves 2 elements' space in the array.
-- Arjun Suresh ( 124085 points)

5 votes

1.309 GATE2000_2.15 top

gateoverflow.in/662

Suppose you are given an array s[1....n] and a procedure reverse (s, i, j) which reverses the order of elements in s between positions i and j
(both inclusive). What does the following sequence do, where 1 k n:
reverse (s, 1, k);
reverse (s, k+1, n);
reverse (s, 1, n);

a. Rotates s left by k positions


b. Leaves s unchanged
c. Reverses all elements of s
d. None of the above
gate2000

algorithms

normal

Selected Answer

Answer is (a)
Effect of the above 3 reversal for any K is equivalent to left rotation of the array of size n by k.
Let , S[1......7]
1

so, n=7 ,k = 2
reverse(S,1,2) we get [2,1,3,4,5,6,7]
reverse(S,3,7) we get [2,1,7,6,5,4,3]
reverse(S,1,7) we get [3,4,5,6,7,1,2]
hence option (a) Rotates s left by k position is correct

8 votes

1.310 GATE2008_40 top


Copyright GATE Overflow. All rights reserved.

-- Kalpna Bhargav ( 2931 points)

gateoverflow.in/452

GATE Overflow

April 2016

217 of 1876

The minimum number of comparisons required to determine if an integer appears more than 2 times in a sorted array of n
integers is

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

gate2008

normal

algorithms

Selected Answer

answer = option B
n

whenever there exists an element which is present in the array : more than 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
n

No matter how we push that stream of More than 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 occurrences in O(logn) time.
8 votes

-- Amar Vashishth ( 17735 points)

To check whether a given number is repeated n/2 times in the array can be done in O(log n) time.
Algo
1. find the first occurrence (index i) of x(given number) in the array which can be done in O(log n) time (a variant of
binary search).
2. check if A[i] == A[n/2+i]
return true
3. else return false



9 votes

1.311 GATE2008_43 top

-- Vikrant Singh ( 10051 points)

gateoverflow.in/455

Consider the Quicksort algorithm. Suppose there is a procedure for finding a pivot element which splits the list into two sublists 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

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

218 of 1876

B. T(n) T(n/5) + T(4n/5) + n


C. T(n) 2T(4n/5) + n
D. T(n) 2T(n/2) + n

gate2008

algorithms

easy

Selected Answer

T(n) T(n/5) + T(4n/5) + n


One part contains n/5 elements
and the other part contains 4n/5 elements
+n is common to all options, so we need not to worry about it.
Hence, answer = option B
-- Amar Vashishth ( 17735 points)

5 votes

The answer is B.
With 1/5 elements on one side giving T(n/5) and 4n/5 on the other side, giving T(4n/5).
and n is the pivot selection time.
-- Gate Keeda ( 16619 points)

1 votes

1.312 GATE2012_18 top

gateoverflow.in/50

Let W(n) and A(n) denote respectively, the worst case and average case running time of an algorithm executed on an input of
size n. Which of the following is ALWAYS TRUE?
(A) A(n) = (W(n))
(B) A(n) = (W(n))
(C) A(n) = O(W(n))
(D) A(n) = o(W(n))

gate2012

algorithms

easy

Selected Answer

Worst case complexity can never be lower than the average case complexity, but it can be higher. So, (C) is the answer.
A(n) = O(W(n))
-- Arjun Suresh ( 124085 points)

5 votes

1.313 GATE2012_16 top


The recurrence relation capturing the optimal execution time of the TowersofHanoi problem with n discs is
(A) T(n) = 2T(n 2) + 2
(B) T(n) = 2T(n 1) + n
(C) T(n) = 2T(n/2) + 1
(D) T(n) = 2T(n 1) + 1
gate2012

algorithms

easy

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/48

GATE Overflow

April 2016

219 of 1876

Selected Answer

Recurrence relation for Towers of Hanoi is


T(1) = 1
T(n) = 2 T( n-1 ) +1
So Answer should be (D)
-- Narayan Kunal ( 369 points)

7 votes

1.314 GATE2012_5 top

gateoverflow.in/37

The worst case running time to search for an element in a balanced binary search tree with n2n elements is
(A) (nlogn) (B) (n2n ) (C) (n) (D) (logn)
gate2012

algorithms

normal

Selected Answer

Binary search takes (logn) for n elements in the worst case. So, with (n2n ) elements, the worst case time will be
(log(n2n ))
= (logn + log2n )
= (logn + n)
= (n)
-- Arjun Suresh ( 124085 points)

5 votes

1.315 GATE1999_2.20 top

gateoverflow.in/466

The minimum number of record movements required to merge five files A (with 10 records), B (with 20 records), C (with 15
records), D (with 5 records) and E (with 25 records) is:
(a) 165 (b) 90 (c) 75 d) 65
gate1999

algorithms

normal

Selected Answer

Arrange files in increasing order of records


D A C B E
5 10 15 20 25
75
30 45
15 15(C) 20 (B) 25(E)
5(D) 10(A)
No of movements=15+30+45+75=165

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

220 of 1876
-- Pooja ( 22745 points)

4 votes

Sort the files: 5, 10, 15, 20, 25.


Merge the smallest two records 15, 15, 20, 25
Merge 30, 20, 25
Sort 20, 25, 30
Merge 45, 30
75. So C is the answer
-- Keith Kr ( 5467 points)

2 votes

1.316 GATE2008-80 top

gateoverflow.in/498

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] X[i, j ai]
B. X[i, j] = X[i 1, j] X[i 1, j ai]
C. X[i, j] = X[i 1, j] X[i, j ai]
D. X[i, j] = X[i 1, j] X[i 1, j ai]
gate2008

algorithms

normal

I think answers are


80. (B)


81. (C)
// Returns true if there is a subset of set[] with sun equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
// The value of subset[i][j] will be true if there is a subset of set[0..j-1]
// with sum equal to i
bool subset[sum+1][n+1];
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
subset[0][i] = true;
// If sum is not 0 and set is empty, then answer is false
for (int i = 1; i <= sum; i++)
subset[i][0] = false;
// Fill the subset table in botton up manner
for (int i = 1; i <= sum; i++)
{
for (int j = 1; j <= n; j++)
{
subset[i][j] = subset[i][j-1];
if (i >= set[j-1])
subset[i][j] = subset[i][j] || subset[i - set[j-1]][j-1];
}
}
/* // uncomment this code to print table
for (int i = 0; i <= sum; i++)
{
for (int j = 0; j <= n; j++)
printf ("%4d", subset[i][j]);
printf("\n");
} */
return subset[sum][n];
}

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

221 of 1876

-- Sona Praneeth Akula ( 3473 points)

1 votes

1.317 GATE2000_1.15 top

gateoverflow.in/638

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 statement is true?

a. t (n) is 0(1)
b. n t(n) n log2 n
n

c. n log2 n t(n) < 2


n

d. t(n) =

()
2



gate2000

easy

algorithms

Selected Answer

Because array is always sorted just check the 1st two elements. option a.
-- anshu ( 2155 points)

7 votes

1.318 GATE2000_1.13 top

gateoverflow.in/636

The most appropriate matching for the following pairs


X: depth first search
Y: breadth-first search
Z: sorting

1: heap
2: queue
3: stack

is:

a. X - 1 Y - 2 Z - 3
b. X - 3 Y - 1 Z - 2
c. X - 3 Y - 2 Z - 1
d. X - 2 Y - 3 Z - 1

gate2000

algorithms

easy

Answer: C
4 votes

-- Rajarshi Sarkar ( 27781 points)

X - 3 DFS uses stack implicitly


Y-2 BFS uses queue explicitly in Algo
Z-1 Heap-Heapsort
Answer C
3 votes

1.319 GATE1992_08 top

-- Akash ( 26265 points)

gateoverflow.in/587

Let T be a Depth First Tree of a undirected graph G. An array P indexed by the vertices of G is given. P[V] is the parent of

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

222 of 1876

vertex V, in T. Parent of the root is the root itself.


Give a method for finding and printing the cycle formed if the edge (u, v) of G not in T (i.e., e G T) is now added to T.
Time taken by your method must be proportional to the length of the cycle.
Describe the algorithm in a PASCAL like language. Assume that the variables have been suitably declared.
gate1992

algorithms

descriptive

Union-Find Algorithm can be used to find the cycle.


Ref: http://www.geeksforgeeks.org/union-find/
-- Rajarshi Sarkar ( 27781 points)

3 votes

1.320 GATE1991_03,viii top

gateoverflow.in/523

Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Consider the following Pascal function:
Function X(M:integer):integer;
Var i:integer;
Begin
i := 0;
while i*i < M
do i:= i+1
x := i
end

The function call X(N), if N is positive, will return


(a).  N
(b).  N + 1
(c).  N
(d).  N + 1
(e). None of the above
gate1991

algorithms

easy

Selected Answer

The function returns  N + 1. For 17 it returns 5, and for 16 also it returns 5.


-- Rajarshi Sarkar ( 27781 points)

2 votes

1.321 GATE2014-1_39 top

gateoverflow.in/1917

The minimum number of comparisons required to find the minimum and the maximum of 100 numbers is ________

gate2014-1

algorithms

numerical-answers

normal

Selected Answer

Ans: minimum number of comparison require to find minimum and maximum is: Approach is divide and conquer ....
T(n) = T(floor(n/2)) + T(ceil(n/2)) + 2
T(2) = 1 // if two element then compare both and return max and min

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

223 of 1876

T(1) = 0 // if one element then return both max and min same

If n is a power of 2, then we can write T(n) as:


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

After solving above recursion, we get


T(n)

= 3/2n -2

Thus, the approach does 3/2n -2 comparisons if n is a power of 2. And it does more than 3/2n -2 comparisons if n is
not a power of 2.
So, here in this case put n=100 and we will get (3/2)(100) - 2 = 148 comparison .....
10 votes

-- Jayesh Malaviya ( 1075 points)

The answer is based on computing minimum and maximum in pairs of two


say number of elements in even and array is
5 1 2 5 6 8 9 10
than code goes as follows
fun(){
int mn,mx;
if(arr[0]>arr[1]){ mn=arr[1];mx=arr[0];} // 1 comparison for 2 elements
else{ mx=arr[1];mn=arr[0]; }
for(int i=2;i<n;i=i+2){ // picking every pair of element
// we will calculate the minimum and maximum of this pair and then compare with global minimum and maximum hence total of 3 comparisons
for a pair
int t_mn,int t_mx;
if(arr[i]>arr[i+1]){ t_mn=arr[i+1]; t_mx=arr[i];} // 1st comparison
else { t_mn=arr[i]; t_mx=arr[i+1];}


if(mx>t_mx) mx=t_mx; // 2nd comparions
if(mn<t_mx) mn=t_mx; // 3rd comparioson
}

cout << mx << " " << mn << endl;


return 0;
}
hence if n is number of elements
than comparisons=1+((n-2)/2)*3
hence in n=100 ans=148
similarly in odd number of elements 1st element will be max as well as min
hence comparisons=((n-1)/2)*3

refer to CLRS book


2 votes

Copyright GATE Overflow. All rights reserved.

-- ANKUR MAHIWAL ( 127 points)

GATE Overflow

April 2016

224 of 1876

1.322 GATE2014-2_37 top

gateoverflow.in/1996

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 = ___.

gate2014-2

algorithms

normal

34
qprr
Pqrr
qpqr
In first string
If we want to get 4 as max len den lcs should end with either rr or qr
Only 4combinations possible for lcs with len 4
qpqr
qqrr
pqrr
qprr

Now check for matching sequences in second string, except for qqrr all possible
-- Anurag Semwal ( 4775 points)

5 votes

1.323 GATE2015-1_6 top

gateoverflow.in/8088

Match the following:


(P) Prim's algorithm for minimum spanning tree (i) Backtracking
(Q) Floyd-Warshall algorithm for all pairs shortest
(ii) Greedy method
paths
(R) Mergesort


(iii)
programming

Dynamic

(S) Hamiltonian circuit

(iv) Divide and conquer



A. P-iii, Q-ii, R-iv, S-i
B. P-i, Q-ii, R-iv, S-iii
C. P-ii, Q-iii, R-iv, S-i
D. P-ii, Q-i, R-iii, S-iv
gate2015-1

algorithms

normal

Selected Answer

option c is correct ..
6 votes

1.324 GATE2015-2_36 top


Copyright GATE Overflow. All rights reserved.

-- Anoop Sonkar ( 4167 points)

gateoverflow.in/8161

GATE Overflow

April 2016

225 of 1876

Given below are some algorithms, and some algorithm design paradigms.
1. Dijkstra's Shortest Path
i. Divide and Conquer
2. Floyd-Warshall algorithm to compute all
ii. Dynamic Programming
pairs shortest path
3. Binary search on a sorted array
4. Backtracking search on a graph

iii. Greedy design


iv. Depth-first search
v. Breadth-first search

Match the above algorithms on the left to the corresponding design paradigm they follow.

A. 1-i, 2-iii, 3-i, 4-v
B. 1-iii, 2-iii, 3-i, 4-v
C. 1-iii, 2-ii, 3-i, 4-iv
D. 1-iii, 2-ii, 3-i, 4-v
gate2015-2

algorithms

easy

Answer: C
-- Rajarshi Sarkar ( 27781 points)

7 votes

C.
Dijkstra's Shortest path algorithm uses greedy method while Floyd Warshall Algorithm to compute all shortest paths uses
Dynamic Programming
Binary search uses Divide and Conquer and Back tracking traversal to a graph uses Depth First Search (DFS) .
-- Raghuveer Dhakad ( 849 points)

2 votes

1.325 GATE2005-IT_58 top

gateoverflow.in/3819

Let a be an array containing n integers in increasing order. The following algorithm determines whether there are two
distinct numbers in the array whose difference is a specified number S > 0.
i = 0; j = 1;
while (j < n ){
if (E) j++;
else if (a[j] - a[i] == S) break;
else i++;
}
if (j < n) printf("yes") else printf ("no");

Choose the correct expression for E.



A)
B)
C)
D)
gate2005-it

a[j] - a[i] > S


a[j] - a[i] < S
a[i] - a[j] < S
a[i] - a[j] > S

algorithms

normal

Selected Answer

Answer is (B)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

226 of 1876

For some 'i' if we find that difference of ( A[j] - A[i] <S )we increment 'j' to make this difference wider so that
it becomes equal to S .
If at times difference becomes greater than S we know that it wont reduce further for same 'i' and so we
increment the 'i'.
We do it for each 'i' if not found in previous iteration. until i=n
-- Sandeep_Uniyal ( 5063 points)

5 votes

1.326 GATE2005-IT_53 top

gateoverflow.in/3814

The following C function takes two ASCII strings and determines whether one is an anagram of the other. An anagram of a
string s is a string obtained by permuting the letters in s.
int anagram (char *a, char *b) {
int count [128], j;
for (j = 0; j < 128; j++) count[j] = 0;
j = 0;
while (a[j] && b[j]) {
A;
B;
}
for (j = 0; j < 128; j++) if (count [j]) return 0;
return 1;
}

Choose the correct alternative for statements A and B.



A)
B)
C)
D)

A : count [a[j]]++ and B : count[b[j]]-A : count [a[j]]++ and B : count[b[j]]++


A : count [a[j++]]++ and B : count[b[j]]-A : count [a[j]]++and B : count[b[j++]]--

gate2005-it

algorithms

programming

normal

Selected Answer

The answer is D
#include <stdio.h>
int main(void) {
return 0;
}
int anagram (char *a, char *b) {
/*
ASCII characters are of 7-bits
so we use count array to represent all the ASCII characters
(ranging 0-127)
*/
int count [128], j;
/*
so this loop will initialize count of all the ASCII characters to be
0 (zero)
*/
for (j = 0; j < 128; j++) count[j] = 0;
j = 0;
/*
"a[j] && b[j]" ensures that anagram returns 0 (false) in case both
strings have different length. Because different length strings cannot
be anagram of each other
*/
/*
Logic:
Below while loop increments ASCII equivalent position for its occurence
in array 'a'in count array; and decrements ASCII equivalent position
for its occurence in array 'b'in count array.
Example: a = "ISS" and b = "SIS"
ASCII equivalent of:
I - 73
S - 83
j = 0: Statement A will increment count[ASCII of 'I']==>count[73]
count[73] = 0 --> 1
Statement B will decrement count[ASCII of 'S'] ==> count[83]

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

227 of 1876

count[83] = 0 --> -1 and will increment j j = 0 --> 1


j = 1: Statement A will increment count[ASCII of 'S'] ==> count[83]
count[83] = -1 --> 0
Statement B will decrement count[ASCII of 'I'] ==> count[73]
count[73] = 1 --> 0 and will increment j j = 1 --> 2
j = 2: Statement A will increment count[ASCII of 'S'] ==> count[83]
count[83] = 0 --> 1
Statement B will decrement count[ASCII of 'S'] ==> count[83]
count[83] = 1 --> 0 and will increment j j = 2 --> 3
*** END OF LOOP ***
*/
while (a[j] && b[j]) {
A; //count [a[j]]++
/*
Note: j will be increment after count[]-- will execute
Resource: http://www.c4learn.com/c-programming/increment-operator-inside-printf
*/
B; //count[b[j++]]-}
/*
This loop checks that the number of occurences of the individual ASCII
characters is same or not.
If count[i] = 0 ---> same number of occurences for ASCII chracter i
---> return 1 (true)
if count[i]!= 0 ---> different number of occurences for ASCII chracter i
---> return 0 (false)
*/
for (j = 0; j < 128; j++) if (count [j]) return 0;
return 1;
}


-- Sohil Ladhani ( 123 points)

3 votes

Answer is (D)
A: Increments the Count by 1 at each index that is equal to the ASCII value of the alphabet it is pointing at
B: Decrements the count by 1 at each index that is equal to the ASCII value of the alphabet it is pointing at
.
Also it increments the loop counter for next iteration.
If one string is permutation of other ,there would have been equal increments and decrements at each index of array and
So count should contain zero at each index.that is what the loop checks at last and if any non-zero elements
is found, it returns 0 indicating that strings are not anagram to each other.
-- Sandeep_Uniyal ( 5063 points)

2 votes

1.327 GATE2005-IT_15 top

gateoverflow.in/3760

In the following table, the left column contains the names of standard graph algorithms and the right column contains the
time complexities of the algorithms. Match each algorithm with its time complexity.
1. Bellman-Ford
algorithm
2. Kruskals algorithm
3. Floyd-Warshall
algorithm
4. Topological sorting


1)
2)
3)
4)
gate2005-it

1 C, 2 A, 3 B, 4 D
1 B, 2 D, 3 C, 4 A
1 C, 2 D, 3 A, 4 B
1 B, 2 A, 3 C, 4 D

algorithms

normal

Copyright GATE Overflow. All rights reserved.

A : O ( m log
n)
B : O (n3)
C : O (nm)
D : O (n + m)

GATE Overflow

April 2016

228 of 1876

Selected Answer

1. Bellman-Ford algorithm =>: O (nm) Assuming n as edges , m as vertices, for every vertex we relax all edges. m*n ,
O(mn)
2. Kruskals algorithm => Remaining Option ,A : O ( m log n)
3. Floyd-Warshall algorithm => Dynamic Programming Algo, O(N3)
4. Topological sorting => Boils Down to DFS, O(V+E) D
Answer A)
-- Akash ( 26265 points)

1 votes

Answer: A
-- Rajarshi Sarkar ( 27781 points)

1 votes

1.328 GATE2015-2_45 top

gateoverflow.in/8243

Suppose you are provided with the following function declaration in the C programming language.
int partition(int a[], int n);

The function treats the first element of a[ ] as a pivot and rearranges the array so that all elements less than or equal to the
pivot is in the left part of the array, and all elements greater than the pivot is in the right part. In addition, it moves the pivot
so that the pivot is the last element of the left part. The return value is the number of elements in the left part.
The following partially given function in the C programming language is used to find the kth smallest element in an array a[ ]
of size n using the partition function. We assume k n.
int kth_smallest (int a[], int n, int k)
{
int left_end = partition (a, n);
if (left_end+1==k) {
return a[left_end];
}
if (left_end+1 > k) {
return kth_smallest (___________);
} else {
return kth_smallest (___________);
}
}

The missing arguments lists are respectively



A. (a, left_end, k) and (a+left_end+1, n-left_end-1, k-left_end-1)
B. (a, left_end, k) and (a, n-left_end-1, k-left_end-1)
C. (a, left_end+1, n-left_end-1, k-left_end-1) and (a, left_end, k)
D. (a, n-left_end-1, k-left_end-1) and (a, left_end, k)
gate2015-2

algorithms

normal

Ans A.
2 votes

1.329 GATE2015-1_31 top


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

Copyright GATE Overflow. All rights reserved.

-- Vikrant Singh ( 10051 points)

gateoverflow.in/8263

GATE Overflow

April 2016

229 of 1876

return q;


Which one of the following most closely approximates the return value of the function fun1?
A. n3
B. n(log n)2
C. n log n
D. n log(log n)


gate2015-1

algorithms

normal

Selected Answer

i loop is executing n times. j loop is executing log n times for each i, and so value of p is log n. k loop is executing log p
times, which is log log n times for each iteration of i. In each of these q is incremented. So, over all iterations of i, q will
be incremented n log log n times. So, D choice.
13 votes

-- Arjun Suresh ( 124085 points)

answer is d
2 votes

-- naresh1845 ( 1135 points)

Here for loop of i is executing n times


j is executing log n time
Now, k is incrementing log p times
what that p is?
p is no of time j executes
j executes log n times
So, value of p is also log n
So, from here k executes log log n times
So, return value of fun1 is n log log n
Complexity of program O(n log log n)
1 votes

1.330 TIFR2011-B-38 top


Consider the class of recursive and iterative programs. Which of the following is false?
a. Recursive programs are more powerful than iterative programs.
b. For every iterative program there is an equivalent recursive program.
c. Recursive programs require dynamic memory management.
d. Recursive programs do not terminate sometimes.
e. Iterative programs and recursive programs are equally expressive.
tifr2011

algorithms

Copyright GATE Overflow. All rights reserved.

-- srestha ( 11537 points)

gateoverflow.in/20923

GATE Overflow

April 2016

230 of 1876

Selected Answer

answer = option E
Computable function: those which can be incorporated in a program using for/while loops.
Total Function: Defined for all possible inputs
Well Defined: if its definition assigns it a unique value.
It was a belief in early 1900s that every Computable function was also Primitively Recursive. But the discovery of Ackermann function
provided a counter to it.
The class of primitive recursive functions is a small subclass of the class of recursive functions. This means that there are some functions
which are Well-Defined Total Functions and are Computable BUT Not primitively recursive; eg. Ackermann function.
This makes all options from option A to option D as True.
But option E as FALSE. As iterative programs are equivalent to only Primitively Recursive class.

2 votes

1.331 TIFR2011-B-29 top

-- Amar Vashishth ( 17735 points)

gateoverflow.in/20576

You are given ten rings numbered from 1 to 10, and three pegs labeled A, B, and C. Initially all the rings are on peg A,
arranged from top to bottom in ascending order of their numbers. The goal is to move all the rings to peg B in the minimum
number of moves obeying the following constraints:
(i) In one move, only one ring can be moved.
(ii) A ring can only be moved from the top of its peg to the top of a new peg.
(iii) At no point can a ring be placed on top of another ring with a lower number.
How many moves are required?
a. 501
b. 1023
c. 2011
d. 10079
e. None of the above.
tifr2011

algorithms

I think its Tower of Hanoi problem.


Therefore Total number of function call 2n-1 = 1023 option B
1 votes

1.332 GATE-2012 top

-- Umang Raman ( 10379 points)

gateoverflow.in/19597

Let G be a weighted graph with edge weights greater than one and G' be the graph constructed by squaring the
weight of edges in G.Let T and T' be the minimum spanning trees of G and G' respectively with total weights t
and t'. Which of the following statements is true?
a) T'=T with total weight t'=t^2
b)T'=T with total weight t'
c)T' !=T but total weight t'=t^2
d)None of the above

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

231 of 1876

Answer: (D)
Explanation: Squaring the weights of the edges in a weighted graph will not change the minimum spanning tree. Assume the
opposite to obtain a contradiction. If the minimum spanning tree changes then at least one edge from the old graph G in the old minimum
spanning tree T must be replaced by a new edge in tree T from the graph G with squared edge weights. The new edge from G must have a
lower weight than the edge from G. This implies that there exists some weights C1 and C2 such that C1 < C2 and C12 >= C22. This is a
contradiction.
Source: http://www.cs.nyu.edu/courses/spring06/V22.0310-001/hw3.htm
Sums of squares of two or more numbers is always smaller than square of sum.
Example: 2^2 + 2^2 < (4)^2 But
there is one counter example when the graph has only one edge.
In that case, the two values are same.

Source:
http://geeksquiz.com/gate-gate-cs-2012-question-29/
-- Prasanna Ranganathan ( 2051 points)

0 votes

1.333 TIFR2010-B-24 top

gateoverflow.in/18742

Consider the following program operating on four variables u, v, x, y, and two constants X and Y.
x, y, u, v:= X, Y, Y, X;
While (x y)
do
if (x > y) then x, v := x - y, v + u;
else if (y > x) then y, u:= y - x, u + v;
od;
print ((x + y) / 2); print ((u + v) / 2);


Given X > 0 Y > 0, pick the true statement out of the following:
a. The program prints gcd(X, Y) and the first prime larger than both X and Y.
b. The program prints gcd(X, Y) followed by lcm(X, Y).
1

c. The program prints gcd(X, Y) followed by 2 lcm(X, Y).


1

d. The program prints 2 gcd(X, Y) followed by 2 lcm(X, Y).


e. The program does none of the above.
tifr2010

algorithms

It prints with gcd(x,y) and lcm(x,y)


consider x,y,u,v=17,3,3,17
X=14, v=20
X=11,v=23
X=8, v=26
X=5,v=29
X=2,v=32
Y=1,u=35
X=1,v=67

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

232 of 1876

This is the value obtained


lastly print (x+y)/2 and (v+u)/2 gives 1 and 51
-- zambus ( 159 points)

1 votes

1.334 GATE2004-IT_58 top

gateoverflow.in/3701

Consider the following C program which is supposed to compute the transpose of a given 4 x 4 matrix M. Note that, there is
an X in the program which indicates some missing statements. Choose the correct option to replace X in the program.

#include<stdio.h>
#define ROW 4
#define COL 4
int M[ROW][COL] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
main()
{
int i, j, t;
for (i = 0; i < 4; ++i)
{
X
}
for (1 = 0; i < 4; ++i)
for (j = 0; j < 4; ++j)
printf ("%d", M[i][j]);
}


for(j = 0; j < 4; ++j){
t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}

A)


for(j = 0; j < 4; ++j){
M[i][j] = t;
t = M[j][i];
M[j][i] = M[i][j];
}

B)


for(j = i; j < 4; ++j){
t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}

C)


for(j = i; j < 4; ++j){
M[i][j] = t;
t = M[j][i];
M[j][i] = M[i][j];
}

D)

gate2004-it

algorithms

easy

Selected Answer

option C:
look at the initial value of j, if j starts with 0, then double for loop will swap M[i][j] with M[j][i] and also M[j][i]
and M[i][j] so the matrix M will remain unchanged, so to avoid this double swapping we need to initialize j = i and
swap only upper triangular matrix with lower triangular matrix.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

233 of 1876

for(j = i; j < 4; ++j){


// code for swapping M[i][j] with M[j][i]
t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}
-- Vikrant Singh ( 10051 points)

6 votes

option C
-- prakash ( 245 points)

1 votes

1.335 GATE2004-IT_52 top

gateoverflow.in/3695

A program attempts to generate as many permutations as possible of the string, 'abcd' by pushing the characters a, b, c, d
in the same order onto a stack, but it may pop off the top character at any time. Which one of the following strings CANNOT
be generated using this program?

A)
abcd
B)
dcba
C)
cbad
D)
cabd
gate2004-it

algorithms

normal

Selected Answer

A. push a & pop a, push b & pop b, push c & pop c, and finally push d and pop d
sequence of popped elements will come to abcd
B. first push abcd, and after that pop one by one sequence of popped elements will come to dcba
C. push abc, and after that pop one by one sequence of popped elements will come to cba, now push d and pop d, final
sequence comes to cbad
D. this sequence is not possible because 'a' can not be pooped before 'b' any how
-- Manu Thakur ( 5261 points)

4 votes

1.336 GATE1997_1.5 top


The correct matching for the following pairs is
(A) All pairs shortest path
(1) Greedy
(B) Quick Sort
(2) Depth-First search
(C) Minimum weight spanning
(3) Dynamic Programming
tree
(D) Divide and and
(D) Connected Components
Conquer
A. A-2 B-4 C-1 D-3
B. A-3 B-4 C-1 D-2
C. A-3 B-4 C-2 D-1
D. A-4 B-1 C-2 D-3
gate1997

algorithms

normal

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/2221

GATE Overflow

April 2016

234 of 1876

Selected Answer

answer B
-- ankitrokdeonsns ( 7941 points)

6 votes

1.337 GATE1997_4.2 top

gateoverflow.in/2243

Let a = (aij) be an n-rowed square matrix and I12 be the matrix obtained by interchanging the first and second rows of the nrowed Identify matrix. Then AI12 is such that its first
A. row is the same as its second row
B. row is the same as the second row of A
C. column is the same as the second column of A
D. row is all zero
gate1997

linear-algebra

easy

Selected Answer

c is the answer, in AI12 matrix will result into the same matrix as A but first column will be exchanged with second
column.
A matrix:
a b c
d e f
g h i
I12 matrix
0 1 0
1 0 0
0 0 1
resulted matrix
b a c
e d f
h g i
-- Manu Thakur ( 5261 points)

5 votes

1.338 GATE2012_4 top

gateoverflow.in/36

Assuming P NP, which of the following is TRUE?


(A) NP-complete = NP
(B) NP-complete P =
(C) NP-hard = NP
(D) P = NP-complete
gate2012

algorithms

normal

Selected Answer

Answer is (B) NP-complete P =


Since, P NP, there is at least one problem in NP, which is harder than all P problems. Lets take the hardest such problem, sayX. Since,
P NP, X P .

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

235 of 1876

Now, by denition, NP-complete problems are the hardest problems in NP and so X problem is in NP-complete. And being in NP, X can be
reduced to all problems in NP-complete, making any other NP-complete problem as hard as X. So, since X P, none of the other NPcomplete problems also cannot be in P.
-- Arjun Suresh ( 124085 points)

6 votes

1.339 GATE2011_25 top

gateoverflow.in/2127

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.
Initialize Ln 1 = 1.
For all i such that 0 i n 2

Li =

1 + Li +1

if A[i] < A[i+1]

Otherwise

Finally the the length of the longest monotonically increasing sequence is Max (L0 , L1 , , Ln 1 ).
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

gate2011

algorithms

easy

Selected Answer

(A) is the answer.


The algorithm is storing the optimal solutions to subproblems at each point (for each i), and then using it to derive the
optimal solution of a bigger problem. And that is dynamic programming approach. And the program has linear time
complexity.
http://stackoverflow.com/questions/1065433/what-is-dynamic-programming
Now, branch and bound comes when we explore all possible solutions (branch) and backtracks as soon as we find we
won't get a solution (in classical backtracking we will retreat only when we won't find the solution). So, backtracking gives
all
possible
solutions
while
branch
and
bound
will
give
only
the
optimal
one. http://www.cs.cornell.edu/~wdtseng/icpc/notes/bt2.pdf
The given algorithm here is neither backtracking nor branch and bound. Because we are not branching anywhere in the
solution space.
And the algorithm is not divide and conquer as we are not dividing the problem and then merging the solution as in the
case of merge sort (where merge is the conquer step).
https://en.wikipedia.org/wiki/Divide_and_conquer_algorithms
8 votes

1.340 GATE2014-3_37 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/2071

Suppose you want to move from 0 to 100 on the number line. In each step, you either move right by a unit distance or you take a shortcut. A shortcut is simply a
pre-specied pair of integers i, j with i < j. Given a shortcut i, j if you are at position i on the number line, you may directly move to j. Suppose T(k) denotes the

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

236 of 1876

smallest number of steps needed to move from k to 100. Suppose further that there is at most 1 shortcut involving any number, and in particular from 9 there is a
shortcut to 15. Let y and z be such that T(9) = 1 + min (T(y), T(z)). Then the value of the product yz is _____.

gate2014-3

algorithms

normal

Selected Answer

T(9) = Distance from 9 to 100


T(9)=1+ min(T(y),T(z))=1+min(Distance from y to 100 , Distance from z to 100)
There are only two such values where we can reach from 9 , one is simple step to right on number line , i.e 10 and
another is 15 (given shortcut)
Hence , y=10 , z=15
yz=10x15 = 150
-- Srinath Sri ( 2665 points)

6 votes

1.341 GATE1994_1.22 top

gateoverflow.in/2465

Which of the following statements is false?


A. Optimal binary search tree construction can be performed efficiently using dynamic programming
B. Breadth-first search cannot be used to find connected components of a graph
C. Given the prefix and postfix walks over a binary tree, the binary tree cannot be uniquely constructed.
D. Depth-first search can be used to find connected components of a graph

gate1994

algorithms

normal

Answer: B
(a) True.
(b) False.
(c) True.
(d) True.
-- Rajarshi Sarkar ( 27781 points)

5 votes

1.342 GATE1994_7 top

gateoverflow.in/2503

An array A contains n integers in locations A[0], A[1], A[n 1]. It is required to shift the elements of the array cyclically to the
left by K places, where 1 K n 1. An incomplete algorithm for doing this in linear time, without using another array is
given below. Complete the algorithm by filling in the blanks. Assume all variables are suitably declared.
min:=n;
i=0;
while _____ do
begin
temp:=A[i];
j:=i;
while ____ do
begin
A[j]:=____;
j:=(j+K) mod n;
if j<min then
min:=j;
end;
A[(n+i-K)mod n]:=____;
i:=______;
end;


gate1994

algorithms

normal

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

237 of 1876

1.343 GATE2008-IT_4 top

gateoverflow.in/3264

What is the size of the smallest MIS(Maximal Independent Set) of a chain of nine nodes?

A)
B)
C)
D)

5
4
3
2

gate2008-it

algorithms

normal

Selected Answer

Answer: C
1--2--3--4--5--6--7--8--9
(2,5,8) is the maximal independent set for a chain of 9 nodes. If we add any other node to the set then it will not be MIS.
-- Rajarshi Sarkar ( 27781 points)

3 votes

1.344 GATE1996_2.13 top

gateoverflow.in/2742

The average number of key comparisons done on a successful sequential search in a list of length n is
(a) logn
n 1

(b) 2
n

(c) 2
n +1

(d) 2
gate1996

algorithms

easy

Selected Answer

Expected number of comparisons


= 1 Probability of first element be x + 2 Probability of second element be x + .... +n Probability of last element
be x.
1

= n + n + n + .... + n

n (n + 1 )
2

=
n +1

= 2
7 votes

-- Arjun Suresh ( 124085 points)

First consider smaller example...


say list given = {3,1,2} and say you want to search element '2' in sequential way.So first you will visit first element and
compare it with '2' .If it is '2' then your search will end at first element with only 1 comparison. But if it is not equal to

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

238 of 1876

'2',then you compare it with second element. so second element is '1' so again search was unsuccessful and comparison
required was total '2' i.e. b/w '2' & '3' and b/w '2' & '1' and so on.
So if required element is found at first position , no of comparison = 1;
if required element is found at second position , no of comparison = 2 ...and so on.
Now since our list is not sorted so it can be anything e.g. list can be {1,2,3} or {3,2,1} or {2,3,1}etc.So the element we
are looking for may be present at any of these three positions with equal chances of 1/3.
Now consider our list containing 'n' elements. So element to be searched can be present at any of these 'n' positions in the
list with equal chance(probability) of 1/n.
Total comparison required = No.of comparison if element present in 1st position + No.of comparison if element present in
2nd position + .......+ No.of comparison if element present in nth position
= 1 + 2 + 3+ ......+n = n(n+1)/2
Since there are 'n' elements in the list.
So avg. no. of comparison = Total comparison/total no of elements = [n(n+1)/2] / n = (n+1)/2.
2 votes

-- Shashank Kumar ( 2029 points)

ans is D
1 votes

1.345 GATE1995_2.22 top

-- neha pawar ( 3561 points)

gateoverflow.in/2634

Which of the following statements is true?


I. As the number of entries in a hash table increases, the number of collisions increases.
II. Recursive programs are efficient
III. The worst case complexity for Quicksort is O(n2 )
IV. Binary search using a linear linked list is efficient

A. I and II
B. II and III
C. I and IV
D. I and III

gate1995

algorithms

Selected Answer

Its D according to me.


Binary search using linked list is not efficient as it will not give O(logn), because we will not be able to find the mid in
constant time. Finding mid in linked list takes O(n) time.
Recursive programs are not efficient because they take a lot of space, Recursive methods will often throw
StackOverflowException while processing big sets. moreover it has its own advantages too.
11 votes

1.346 GATE1995_2.9 top


A language with string manipulation facilities uses the following operations
head(s): first character of a string
tail(s): all but the first character of a string
concat(s1, s2): s1s2

For the string acbc what will be the output of

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

gateoverflow.in/2621

GATE Overflow

April 2016

239 of 1876

concat(head(s), head(tail(tail(s))))

A. ac
B. bc
C. ab
D. cc

gate1995

algorithms

normal

Selected Answer

C.
concat(a,head(tail(tail(acbc))))
concat(a,head(tail(cbc)))
concat(a,head(bc))
concat(a,b)
ab.
-- Gate Keeda ( 16619 points)

7 votes

1.347 TIFR2012-B-6 top


Let n be a large integer. Which of the following statements is TRUE?
n

a. 22log n < log n < n1 / 3


n

b. log n < n1 / 3 < 22log n


n

c. 2 2log n < n1 / 3 < log n

d.

n1 / 3

<2

2log n

<

log n

e. log n < 2 2log n < n1 / 3

tifr2012

algorithms

Selected Answer

Ans will be C
Take n = 21024
Now, 2 (2log n ) 245
1
3
n 2341

n/logn = 21024 /1024 21014


Just one value is not enough to confirm growth rate. So, take n = 1024.
Now, 2 (2log n ) 24
1
3
n 23

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/25106

GATE Overflow

April 2016

240 of 1876

n/logn = 210 /10 27


So, as n increases the gap between second and third function increases and also the second function overtakes the first.
So, f1 < f2 < f3.
2 votes

Copyright GATE Overflow. All rights reserved.

-- srestha ( 11537 points)

GATE Overflow

April 2016

241 of 1876

Compiler Design top

2.1 Assembler: GATE1992_3,i top

gateoverflow.in/578

Write short answers to the following:


(i). Which of the following macros can put a macro assembler into an infinite loop?
.MACRO MI,X
.IF EQ,X
M1 X+1
.ENDC
.IF NE,X
.WORD X
.ENDC
.ENDM

.MACRO M2,X
.IF EQ,X
M2 X
.ENDC
.IF NE,X
.WORD X+1
.ENDC
.ENDM


Give an example call that does so.
gate1992

compiler-design

assembler

normal

2.2 Assembler: GATE1992_03,ii top

gateoverflow.in/579

Mention the pass number for each of the following activities that occur in a two pass assembler:
a. object code generation
b. literals added to literal table
c. listing printed
d. address resolution of local symbols

gate1992

compiler-design

assembler

easy

Selected Answer

a) 2
b) 1
c) 1
d) 1
P.S. : In first pass, symbol table is created and In second pass, machine code is generated.
2 votes

2.3 Assembler: GATE1993_7.6 top


A simple two-pass assembler does the following in the first pass:
A. It allocates space for the literals.
B. It computes the total length of the program.
C. It builds the symbol table for the symbols and their values.
D. It generates code for all the load and store register instructions.
E. None of the above.

Copyright GATE Overflow. All rights reserved.

-- Aditya Gaurav ( 1831 points)

gateoverflow.in/2294

GATE Overflow

gate1993

April 2016

compiler-design

assembler

242 of 1876

easy

Selected Answer

a, b, c are TRUE.
http://www01.ibm.com/support/knowledgecenter/ssw_aix_53/com.ibm.aix.aixassem/doc/alangref/assembler_passes.htm%23a108f0609
-- Arjun Suresh ( 124085 points)

8 votes

answer - C
-- ankitrokdeonsns ( 7941 points)

1 votes

2.4 Assembler: GATE1992-01,viii top

gateoverflow.in/553

The purpose of instruction location counter in an assembler is _______


gate1992

compiler-design

assembler

normal

Each section of an assembler language program has a location counter used to assign storage addresses to your program's statements. As the instructions of
a source module are being assembled, the location counter keeps track of the current location in storage.
-- Rohan Ghosh ( 1515 points)

1 votes

2.5 Code Optimization: GATE2008_12 top

gateoverflow.in/410

Some code optimizations are carried out on the intermediate code because

A. They enhance the portability of the compiler to the target processor
B. Program analysis is more accurate on intermediate code than on machine code
C. The information from dataflow analysis cannot otherwise be used for optimization
D. The information from the front end cannot otherwise be used for optimization

gate2008

normal

code-optimization

compiler-design

Selected Answer

Ans is (A)
Intermediate codes are machine independent codes. So, intermediate code can be used for code optimization since a given
source code can be converted to target machine code.
6 votes

-- Keith Kr ( 5467 points)

What does the optimization has to do with the PORTABILITY of code. Why would you want to optimize the code just to
make that portable !!
Your GENERATING the intermediate code itself ENHANCES the portability of the front end and hence the code.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

243 of 1876

Optimization is something that does not matter in case you are talking of portability.
So even if you DON'T optimize your intermediate code further that is nowhere going to harm your portability. According to
me optimizations on intermediate codes are easy and a wide range of optimizations are actually available for
INTERMEDIATE code only because it is EASIER to optimize intermediate code rather than machine code where you need to
consider the machine architecture as well.
So answer to this question is (B).
-- Sandeep_Uniyal ( 5063 points)

1 votes

2.6 Code Optimization: GATE2014-1_17 top

gateoverflow.in/1784

Which one of the following is FALSE?

A. A basic block is a sequence of instructions where control enters the sequence at the beginning and exits at the end.
B. Available expression analysis can be used for common subexpression elimination.
C. Live variable analysis can be used for dead code elimination.
D. x = 4 5 x = 20 is an example of common subexpression elimination.
gate2014-1

compiler-design

code-optimization

normal

A) A basic block is a sequence of instructions where control enters the sequence at the beginning and exits at the end is
TRUE.
(B) Available expression analysis can be used for common subexpression elimination is TRUE. Available expressions is an
analysis algorithm that determines for each point in the program the set of expressions that need not be recomputed.
Available expression analysis is used to do global common subexpression elimination (CSE). If an expression is available
at a point, there is no need to re-evaluate it.
(C)Live variable analysis can be used for dead code elimination is TRUE.

(D) x = 4 5 => x = 20 is an example of common subexpression elimination is FALSE. Common subexpression
elimination (CSE) refers to compiler optimization replaces identical expressions (i.e., they all evaluate to the same value)
with a single variable holding the computed value when it is worthwhile to do so Source: Geeksforgeeks
-- Pyuri sahu ( 1237 points)

2 votes

answer - D
-- ankitrokdeonsns ( 7941 points)

1 votes

2.7 Context Free: GATE2008-IT_78 top

gateoverflow.in/3392

A CFG G is given with the following productions where S is the start symbol, A is a non-terminal and a and b are terminals.
S aS AA aAb bAa
Which of the following strings is generated by the grammar above?

1)
2)
3)
4)
gate2008-it

aabbaba
aabaaba
abababb
aabbaab

compiler-design

context-free

Selected Answer

Copyright GATE Overflow. All rights reserved.

grammar

normal

GATE Overflow

April 2016

244 of 1876

S aS
S aA
S aaAb
S aabAab
S aabbAaab
S aabbaab
hence d is d answer
-- Shreyans Dhankhar ( 2265 points)

16 votes

2.8 Dag Representation: GATE2014-3_34 top

gateoverflow.in/2068

Consider the basic block given below.


a
c
d
e
a

=
=
=
=
=

b
a
b
d
e

+
+
+
+

c
d
c
b
b

The minimum number of nodes and edges present in the DAG representation of the above basic block respectively are
(A) 6 and 6
(B) 8 and 10
(C) 9 and 12
(D) 4 and 4

gate2014-3

compiler-design

dag-representation

normal

Selected Answer

A normal DAG construction will give 8 nodes and 10 edges as shown below.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

245 of 1876

Since, this question asks for minimum possible, we can assume algebraic simplification is allowed. So, d = b + c, e = d b; can be simplified to d = b + c; e = c; Similarly, e = d - b; a = e + b; can be simplified to a = d. This gives the
following DAG with 6 nodes and 6 edges.

https://cs.nyu.edu/~gottlieb/courses/2006-07-fall/compilers/lectures/lecture-14.html
10 votes

2.9 Grammar: GATE1997_1.6 top


In the following grammar

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/2222

GATE Overflow

April 2016

246 of 1876

X::= X Y Y
Y::= Z Y Z
Z::= id
Which of the following is true?
a. ' ' is left associative while ' ' is right associative
b. Both ' ' and ' ' are left associative
c. ' ' is right associative while ' ' is left associative
d. None of the above
gate1997

compiler-design

grammar

normal

Selected Answer

It will be A. For multiple ' ', the derivation is possible only via ' X' which is on left side of ' ' in the production. Hence it is
left associative.
For multiple ' ', the derivation is possible only via ' Y' which is on the right side of ' ' in the production. Hence it is right
associative.
If both left and right derivations were possible, the grammar would have been ambiguous and we couldn't have given
associativity.
-- Gate Keeda ( 16619 points)

11 votes

2.10 Grammar: GATE2004_45 top


Consider the grammar with the following translation rules and E as the start symbol
E E1 # T
|T
T T1 & F
|F
F num

{E. value = E1. value T. value }


{E. value = T. value}
{T. value = T1 . value + F. value}
{T. value = F. value}
{F. value = num. value}


Compute E.value for the root of the parse tree for the expression:2 # 3 & 5 # 6 & 4

A. 200
B. 180
C. 160
D. 40

gate2004

compiler-design

grammar

normal

Selected Answer

we can do in simple manner ...


here # is multiplication and & is addition by semantics rules given in the question ...
and by observation of productions ..
1. here &(+) is higher precedence than #(*). bcoz & is far from starting symbol ...
2. and both &,# are left associative so we can solve the express in this way ...
((2*(3+5))*(6+4)) =160 so ans should be (C).

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/1042

GATE Overflow

April 2016

247 of 1876
-- sonam vyas ( 6439 points)

7 votes

2.11 Grammar: GATE2004_88 top

gateoverflow.in/1082

Consider the following grammar G:


S bS aA b
A bA aB
B bB aS a
Let Na (w) and Nb (w) denote the number of as and bs in a string respectively.
The language L(G) over {a, b} + generated by G is

A.

{w Na(w) > 3Nb(w) }

B.

{w Nb(w) > 3Na(w) }

C.

{w Na(w) = 3k, k {0, 1, 2, } }

D.

{w Nb(w) = 3k, k {0, 1, 2, } }


gate2004

compiler-design

grammar

normal

Selected Answer

above CFG generate string b, aaa..


b will eliminate options A and D
aaa eliminate options B.
C is answer i.e. number of a = 3k, k =0,1,2....
-- Digvijay Pandey ( 26235 points)

6 votes

2.12 Grammar: GATE1997_11 top

gateoverflow.in/2271

Consider the grammar


S bSe
S PQR
P bPc
P
Q cQd
Q
R dRe
R
where S, P, Q, R are non-terminal symbols with S being the start symbol; b, c, d, e are terminal symbols and is the empty
string. This grammar generates strings of the form bi, cj, dk, em for some i, j, k, m 0.
a. What is the condition on the values of i, j, k, m?
b. Find the smallest string that has two parse trees.
gate1997

compiler-design

grammar

Copyright GATE Overflow. All rights reserved.

normal

theory-of-computation

GATE Overflow

April 2016

248 of 1876

Selected Answer

A) i+k=j+m
where i,j,k,m>=0
B) bcde
-- Danish ( 1967 points)

2 votes

2.13 Grammar: GATE2006_32 top

gateoverflow.in/995

Consider the following statements about the context free grammar


G = {S SS, S ab, S ba, S }

I. G is ambiguous
II. G produces all strings with equal number of as and bs
III. G can be accepted by a deterministic PDA.
Which combination below expresses all the true statements about G?
(A) I only
(B) I and III only
(C) II and III only
(D) I, II and III
gate2006

compiler-design

grammar

normal

Selected Answer

I. True. G is ambiguous. E.g. the string ab has multiple derivation trees like S SS abS ab, and S ab.

II. False. G does not produce all strings with equal no. of a`s and b`s. (aabb cannot be generated, since every a
must immediately be followed by a b, and vice-versa).

III. True. The given grammar G generates the language (ab + ba) , which is Regular and therefore also DCFL. So, a DPDA can be designed for G.

Hence, the answer is option B.
-- Pooja ( 22745 points)

14 votes

2.14 Grammar: GATE2007_52 top


Consider the grammar with non-terminals N =

gateoverflow.in/1250

{S, C, S1 },

terminals T = {a, b, i, t, e}, with S as the start symbol, and the

following set of rules:


S iCtSS1 a
S1 eS
Cb
The grammar is NOT LL(1) because:

A. it is left recursive

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

249 of 1876

B. it is right recursive
C. it is ambiguous
D. it is not context-free

gate2007

compiler-design

grammar

normal

Selected Answer

here, we can expand any one of S1 to and other to ea, but which one will it be need not matter, coz in the end we will
still get the same string.

this means that the Grammar is Ambiguous. LL(1) cannot be ambiguous. Here's a Proof for that.

answer = option C
7 votes

-- Amar Vashishth ( 17735 points)

it is ambiguous grammer answer c is correct


2 votes

2.15 Grammar: GATE2004_8 top

-- koushiksngh264 ( 203 points)

gateoverflow.in/1005

Which of the following grammar rules violate the requirements of an operator grammar? P, Q, R are nonterminals, and r, s, t
are terminals.
I. P Q R
II. P Q s R
III. P

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

250 of 1876

IV. P Q t R r

A. (I) only
B. (I) and (III) only
C. (II) and (III) only
D. (III) and (IV) only

gate2004

compiler-design

grammar

normal

Selected Answer

answer is B .because operator grammer does not contain 1) nullable variable 2) 2 adjacent non-terminal on rhs of
production
-- koushiksngh264 ( 203 points)

6 votes

2.16 Grammar: GATE2010_38 top

gateoverflow.in/2339

The grammar S aSa bS c is


(A) LL(1) but not LR(1)
(B) LR(1) but not LL(1)
(C) Both LL(1) and LR(1)
(D) Neither LL(1) nor LR(1)

gate2010

compiler-design

grammar

normal

Selected Answer

It will be C.
For LL(1) take First(S). and do intersection between the result. if intersection is Phi then LL(1) else not.
Making a parsing table and checking if there are two or more entries under any terminal. If yes then neither LL(1) nor
LR(1).
-- Gate Keeda ( 16619 points)

10 votes

2.17 Grammar: GATE2005_59 top

gateoverflow.in/1382

Consider the grammar:


E E+nEnn
For a sentence n + n n, the handles in the right-sentential form of the reduction are:

A. n, E + n and E + n n
B. n, E + n and E + E n
C. n, n + n and n + n n
D. n, E + n and E n

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

gate2005

compiler-design

grammar

251 of 1876

normal

Selected Answer

n+n*n
E+n*n
E*n
E
string in red indicates handle here
so ans is d

-- Pooja ( 22745 points)

3 votes

2.18 Grammar: GATE2006_59 top

gateoverflow.in/1837

Consider the following translation scheme.


S ER

R E print( ); R

E F + E print( + );

}F

F S id{print(id. value); }
Here id is a token that represents an integer and id.value represents the corresponding integer value. For an input '2 * 3 +
4', this translation scheme prints
(A) 2 * 3 + 4
(B) 2 * +3 4
(C) 2 3 * 4 +
(D) 2 3 4+*

gate2006

compiler-design

grammar

normal

It will be D. make a tree and perform post order evaluation.


5 votes

2.19 Grammar: GATE1999_2.15 top


A grammar that is both left and right recursive for a non-terminal, is

A. Ambiguous
B. Unambiguous
C. Information is not sufficient to decide whether it is ambiguous or unambiguous
D. None of the above

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

gateoverflow.in/1493

GATE Overflow

April 2016

252 of 1876


gate1999

compiler-design

grammar

normal

Selected Answer

Let grammar is like this :


Sa
A AbA
This grammar is left as well as right recursive but still unambiguous.. A is useless production but still part of grammar..
A grammar having both left as well as right recursion may or may not be ambiguous ..
-- Digvijay Pandey ( 26235 points)

8 votes

answer - C
-- ankitrokdeonsns ( 7941 points)

2 votes

2.20 Grammar: GATE1999_9 top

gateoverflow.in/1508

Let synthesized attribute val give the value of the binary number generated by S in the following grammar. For example, on
input 101.101, S.val = 5.625.
S L. L L
L LB B
B01
Write S-attributed values corresponding to each of the productions to find S.val.

gate1999

compiler-design

grammar

normal

2.21 Grammar: GATE2006_84,85 top

gateoverflow.in/1856

Statement for Linked Answer Questions 84 & 85:


84. Which one of the following grammars generates the language L =
(A)
S AC CB
C aCb a b
A aA
B Bb
(B)
S aS Sb a b
(C)
S AC CB
C aCb
A aA

Copyright GATE Overflow. All rights reserved.

{a b i j} ?
i j

GATE Overflow

April 2016

253 of 1876

B Bb
(D)
S AC CB
C aCb
A aA a
B Bb b

85. In the correct grammar above, what is the length of the derivation (number of steps starring from S) to generate the
string albm with l m
(A) max(l, m) + 2
(B) l + m + 2
(C)l + m + 3
(D)max(l, m) + 3
gate2006

compiler-design

grammar

normal

Selected Answer

84, answer = option D 85 answer = option A


Q 84 .
option A
C a
or, C b
or, C aCb aaCbb aaaCbbb .. soon
at last you have to put either C a or C b
so production C is used to derive a n+1bn or a nbn+1 n>=0
S AC [Aa nbn+1] can make a n+1bn+1 as single a can be derived from A [A aA a as A ] , similarly S CB
simple way, ab can be derived from grammar as S AC aAC aC ab
option A is wrong
option B , language is used to drive a +b* or a*b + , ab will be derived as S aS ab
option B is wrong
Option C
C
or C aCb aaCbb aaaCbbb .. soon at last need to put C
Production C will generate a nbn n>=0
S AC can generate a nbn as A can be , similarly S CB
option C is wrong
Option D .
production C is used for generate a nbn as in option C
S AC will increase no of a's before a nbn
as A will generate a or aa or aaa... i,e a + , so S AC will generate a +anbn , i.e a ibj i>j
S CB will generate a nbnb+ i.e aibj i<j

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

254 of 1876

option D is right .

Q 85
L =a lbm l m means either l > m or l < m
Case I[l > m]
if l >m ,a lbm can be written as al-m ambm [l-m cannot be 0 as l should be > m ]
S AC , one step
al-m use l-m steps using productions of A
[as l-m = 1 , one step A a
l-m =2 , two steps A aA aa
l-m = 3 , three steps , A aA aaA aaa.. so on]
ambm will be generate in m + 1 steps using production C
[ as m = 0 one step C
m= 1 , two steps C aCb ab
m= 2, three steps C aCb aaCbb aabb.. so on ]

so if l>m total steps = 1+l-m +m+1 = l +2
Case II [l<m]
simillar if l< m , a lbm can be written as alblbm-l [m-l cannot be 0 as m should be > l ]
S CB one step
albl will be derives using l+1 steps
bm-l will be derived using m- l steps
total = 1 +l+1+m-l = m +2
so L =albm l m will take max(l,m)+2 steps
10 votes

-- Praveen Saini ( 34297 points)

Q 85
Let us take aabbb as an example to check in the options[l=2, m=3]
Productions used in this sequence:
S-->CB
C-->aCb
C-->aCb
C-->
B-->b
total 5 sequences are used. Only option A satisfies this.
So, correct answer is option A
3 votes

Q. 84

Copyright GATE Overflow. All rights reserved.

-- Dhananjay ( 657 points)

GATE Overflow

April 2016

255 of 1876

By seeing the question, we know the strings of form ab, aabb, aaabbb...... are not possible. Epsilon is also not possible.
Now, just check the options with the string ab.
Option A, B, C are generating ab.
So, correct answer is D.
-- Dhananjay ( 657 points)

3 votes

Q.84 answer = Option D


Q.85 answer = Option A
try generating random strings from the given grammars in the options that provide may a counter to the given Language.
Once done with that values of l and m will clear out, try value putting with an adequate big string in length to check which option is correct.

-- Amar Vashishth ( 17735 points)

1 votes

2.22 Grammar: GATE2014-2_17 top

gateoverflow.in/1973

Consider the grammar defined by the following production rules, with two operators and +

S TP
T U TU
P Q+P Q
Q Id
U Id

Which one of the following is TRUE?
A. + is left associative, while is right associative
B. + is right associative, while is left associative
C. Both + and are right associative
D. Both + and are left associative
gate2014-2

compiler-design

grammar

normal

Selected Answer

P->Q+P here P is to right of +


so + is right associative
Similarly for T->T *U

* is left associative as T is to left of *

so ans is b

3 votes

-- Pooja ( 22745 points)

answer - B
2 votes

Copyright GATE Overflow. All rights reserved.

-- ankitrokdeonsns ( 7941 points)

GATE Overflow

April 2016

2.23 Grammar: GATE2007-78 top

256 of 1876

gateoverflow.in/1272

Consider the CFG with {S, A, B} as the non-terminal alphabet, {a, b} as the terminal alphabet, S as the start symbol and the
following set of production rules:
S aB S bA
B b A a
B bS A aS
B aBB S bAA
Which of the following strings is generated by the grammar?
A. aaaabb
B. aabbbb
C. aabbab
D. abbbba
gate2007

compiler-design

grammar

normal

Selected Answer

S -> aB
-> aaBB
-> aabB
-> aabbS
-> aabbaB
-> aabbab
-- Arjun Suresh ( 124085 points)

7 votes

ans c) b)
-- Aditi Dan ( 5103 points)

1 votes

2.24 Grammar: GATE2008_50 top

gateoverflow.in/395

Which of the following statements are true?


I. Every left-recursive grammar can be converted to a right-recursive grammar and vice-versa
II. All -productions can be removed from any context-free grammar by suitable transformations
III. The language generated by a context-free grammar all of whose productions are of the form X w or X wY (where, w
is a string of terminals and Y is a non-terminal), is always regular
IV. The derivation trees of strings generated by a context-free grammar in Chomsky Normal Form are always binary trees

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

gate2008

normal

compiler-design

grammar

Selected Answer

Answer is C:
Statement 1 is true: Using GNF we can convert Left recursive grammar to right recursive and by using reversal of CFG

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

257 of 1876

and GNF we can convert right recursive to left recursive.


Statement 2 is false: because if is in the language then we can't remove production from Start symbol. (For example L
= a*)
Statement 3 is true because right linear grammar generates regular set
Statement 4 is true, only two non-terminals are there in each production in CNF. So it always form a binary tree.
-- Vikrant Singh ( 10051 points)

10 votes

2.25 Grammar: GATE2003_58 top

gateoverflow.in/946

Consider the translation scheme shown below.


S T R
R + T {print(+);} R
T num {print(num.val);}
Here num is a token that represents an integer and num.val represents the corresponding integer value. For an input string
9 + 5 + 2, this translation scheme will print
A. 9 + 5 + 2
B. 9 5 + 2 +
C. 9 5 2 + +
D. + + 9 5 2


gate2003

compiler-design

grammar

normal

Selected Answer

answer = option B
9 5 + 2 +

-- Amar Vashishth ( 17735 points)

6 votes

Input

Translation

9 + 5 + 2 S T R

Copyright GATE Overflow. All rights reserved.

Output

GATE Overflow

April 2016

9 + 5 + 2
Input
+ 5 + 2
5 + 2
+ 2

T num {print(num.val);}
Translation
R + T {print(+);} R
T num {print(num.val);}
R + T {print(+);} R

T num {print(num.val);} 2+

258 of 1876

9
Output
(the + is simply consumed as there is no print corresponding to it)
5+


So, output 95+2+. Option B.
-- Arjun Suresh ( 124085 points)

5 votes

2.26 Grammar: GATE2007_53 top

gateoverflow.in/1251

Consider the following two statements:


P: Every regular grammar is LL(1)
Q: Every regular set has a LR(1) grammar
Which of the following is TRUE?

A. Both P and Q are true
B. P is true and Q is false
C. P is false and Q is true
D. Both P and Q are false

gate2007

compiler-design

grammar

normal

P:- This is false. Every regular set is LL(1). But we can not say same about every regular Grammar. As every regular set
can be represented by Left & Right Linear Grammar.Where Left Linear Grammar is not LL(1) , but Right linear is.
Example aa* we can represent this as S->Sa|a which is not LL(1) ,but S->a|aS is LL(1).
Q:- This is true because of every LL(1) is LR(1). All regular sets have Right recursive grammar, which is LL(1) & Every
LL(1) is LR(1).
We can also say that LR(1) accepts DCFL & Regular sets are subset of DCFL.

So Answer is C.
10 votes

-- Aakash Kanse ( 245 points)

answer = option C
LL Grammar
Grammars which can be parsed by an LL parser.
LL parser
Parses the input from Left to right, and constructs a Leftmost derivation of the sentence(i.e. it is always the leftmost nonterminal which is rewritten). LL parser is a top-down parser for a subset of context-free languages .
An LL parser is called an LL(k) parser if it uses k tokens of lookahead when parsing a sentence and can do it without
backtracking.
Consider a Grammar G:
S a | aa
this grammar is Regular but cannot be parsed by a LL(1) parser w/o backtracking, coz here, lookahead is of 1 symbol
only and in the grammar for both productions, parser while looking at just one(first) symbol, which is a, fails to select the
correct rule for parsing.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

259 of 1876

Hence, not every Regular grammar is LL(1); Statement P is False.



LR Grammar
Grammars which can be parsed by LR parsers.
LR Parsers
thery are a type of bottom-up parsers that efficiently handle deterministic context-free languages(DCFL) in guaranteed
linear time.
all Regular Languages are also DCFL hence, They all can be parsed by a LR(1) grammar.
Hence, Statement Q is True.
-- Amar Vashishth ( 17735 points)

4 votes

2.27 Grammar: GATE1994_3.5 top

gateoverflow.in/2482

Match the following items


(i) Backus-Naur form

(a) Regular expressions

(ii) Lexical analysis


(iii) YACC

(b) LALR(1) grammar


(c) LL(1) grammars

(iv) Recursive
parsing

descent (d)
General
grammars

context-free


gate1994

compiler-design

grammar

normal

Selected Answer

answer i - d
ii - a
iii - b
iv - c
3 votes

2.28 Grammar: GATE 2016-2-45 top


Which one of the following grammars is free from left recursion?
(A) S AB
A Aa | b
B c
(B) S Ab | Bb | c
A Bd |
B e
(C) S Aa | B
A Bb | Sc |
B d

Copyright GATE Overflow. All rights reserved.

-- ankitrokdeonsns ( 7941 points)

gateoverflow.in/39594

GATE Overflow

April 2016

260 of 1876

(D) S Aa | Bb | c
A Bd |
B Ae |


gate2016-2

compiler-design

grammar

easy

Selected Answer

Option (a) has immediate left recursion."A Aa"


ASc

Option (c) has indirect left recursion "S Aa  Sca"


BAe

Option (d) has indirect left recursion "A Bd  Aed"


Option (b) is free from left recursion. No direct left recursion. No indirect left recursion.
option B is correct
-- Ashish Deshmukh ( 1229 points)

6 votes

2.29 Grammar: GATE2007-IT_9 top

gateoverflow.in/3442

Consider an ambiguous grammar G and its disambiguated version D. Let the language recognized by the two grammars be
denoted by L(G) and L(D) respectively. Which one of the following is true ?

A)
B)
C)
D)
gate2007-it

L (D) L (G)
L (D) L (G)
L (D) = L (G)
L (D) is empty

compiler-design

grammar

normal

Selected Answer

c) grammar may change but language remain the same.


14 votes

-- Arpit Dhuriya ( 1791 points)

c)L (D) = L (G) , Both must represent same language .Also if we are converting a grammar from Ambiguous to
UnAmbiguous form , we must ensure that our new new grammar represents the same language as previous grammar.
For ex G1: S->Sa/aS/a; {Ambiguous (2 parse trees for string 'aa')}
G1':S->aS/a;{Unambiguous}
Both represents language represented by regular expression: a^+
2 votes

2.30 Grammar: GATE1996_11 top

Copyright GATE Overflow. All rights reserved.

-- Anurag Semwal ( 4775 points)

gateoverflow.in/2763

GATE Overflow

April 2016

261 of 1876

Let G be a context-free grammar where G = ({S, A, B, C}, {a, b, d}, P, S) with the productions in P given below.
S ABAC
A aA
B bB
Cd
( denotes the null string). Transform the grammar G to an equivalent context-free grammar G that has no productions
and no unit productions. (A unit production is of the form x y, and x and y are non terminals).

gate1996

compiler-design

grammar

normal

C->d is a unit production.


so first production will become S -> ABAd | BAd | AAd | ABd | Bd | d
A -> aA | a
B -> bB | b
-- jayendra ( 5797 points)

1 votes

2.31 Grammar: GATE 2016-2-46 top

gateoverflow.in/39598

A student wrote two context-free grammars G1 and G2 for generating a single C-like array declaration. The dimension of the
array is at least one. For example,
int a[10] [3];

The grammars use D as the start symbol, and use six terminal symbols int ; id [ ] num.
Grammar G1 Grammar G2
D int L; D int L;
L id [E L id E
E num ] E E [num]
E num ] [E E [num]
Which of the grammars correctly generate the declaration mentioned above?
A. Both G1 and G2
B. Only G1
C. Only G2
D. Neither G1 nor G2


gate2016-2

compiler-design

grammar

Selected Answer

Option A Both G1 and G2

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

262 of 1876

-- Shashank Chavan ( 2439 points)

10 votes

2.32 Grammar: GATE1991-10a top

gateoverflow.in/537

Consider the following grammar for arithmetic expressions using binary operators and / which are not associative
E E T T
T T/F F
F (E) id
(E is the start symbol)
Is the grammar unambiguous? Is so, what is the relative precedence between and /? If not, give an unambiguous
grammar that gives / precedence over .
gate1991

grammar

compiler-design

normal

descriptive

It is unambiguous grammar and the precedence of / is higher than -.


-- shashi shekhar ( 327 points)

0 votes

2.33 Grammar: GATE1991-10c top

gateoverflow.in/43605

Consider the following grammar for arithmetic expressions using binary operators and / which are not associative
E E T T
T T/F F
F (E) id
(E is the start symbol)
Does the grammar allow expressions with redundant parentheses as in (id/id) or in id (id/id)? If so, convert the grammar into
one which does not generate expressions with redundant parentheses. Do this with minimum number of changes to the
given production rules and adding at most one more production rule.
Convert the grammar obtained above into one that is not left recursive.
gate1991

grammar

compiler-design

normal

Non left recursive grammar is:


ETE'
E' -TE'

Copyright GATE Overflow. All rights reserved.

descriptive

GATE Overflow

April 2016

263 of 1876

TFT'
T'/FT'
F(E) id
-- Manojk ( 3327 points)

0 votes

2.34 Grammar: GATE1991-10b top

gateoverflow.in/43604

Consider the following grammar for arithmetic expressions using binary operators and / which are not associative
E E T T
T T/F F
F (E) id
(E is the start symbol)
Does the grammar allow expressions with redundant parentheses as in (id/id) or in id (id/id) ? If so, convert the grammar into
one which does not generate expressions with redundant parentheses. Do this with minimum number of changes to the
given production rules and adding at most one more production rule.
gate1991

grammar

compiler-design

normal

descriptive

2.35 Grammar: GATE2007-79 top

gateoverflow.in/43512

Consider the CFG with {S, A, B} as the non-terminal alphabet, {a, b} as the terminal alphabet, S as the start symbol and the
following set of production rules:
S aB S bA
B b A a
B bS A aS
B aBB S bAA
For the string aabbab, how many derivation trees are there?
A. 1
B. 2
C. 3
D. 4
gate2007

compiler-design

grammar

normal

Selected Answer

S -> aB
-> aaBB
-> aabB
-> aabbS
-> aabbaB
-> aabbab
S -> aB
-> aaBB (till now, only 1 choice possible)
-> aabSB (last time we took B - > b, now taking B->bS)
-> aabbAB
-> aabbaB
-> aabbab
So, totally 2 possible derivation trees.
1 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

2.36 Grammar: GATE2001_1.18 top

264 of 1876

gateoverflow.in/711

Which of the following statements is false?


(A) An unambiguous grammar has same leftmost and rightmost derivation
(B) An LL(1) parser is a top-down parser
(C) LALR is more powerful than SLR
(D) An ambiguous grammar can never be LR(k) for any k
gate2001

compiler-design

grammar

normal

Selected Answer

(A) is the answer.


(A) We can not have different Left Most Derivation and Right Most Derivation parse trees BUT we can certainly have
different LMD and RMD for a given string.(LMD and RMD here refers to the order of various productions used for derivation
which could be different.)
(D) is wrong w.r.t. question because IT IS TRUE that any LR(k) IS NEVER AMBIGUOUS and so an ambiguous can never be
an LR(K) for any k, no matter how large k becomes.
(B) and (C) can not be the answer because LL(1) is TOP-DOWN parser and LALR is powerful than SLR. So both are TRUE.
-- Sandeep_Uniyal ( 5063 points)

7 votes

2.37 Grammar: GATE2000_2.21 top

gateoverflow.in/668

Given the following expression grammar:


E EF F+E F
F F F id
Which of the following is true?
A.
B.
C.
D.

has higher precedence than +


has higher precedence than
+ and have same precedence
+ has higher precedence than

gate2000

grammar

normal

compiler-design

Selected Answer

I guess its B.
Operator which is at lower level in the grammar is termed to have higher precedence.
7 votes

2.38 Grammar: GATE1996_2.10 top


The grammar whose productions are
-> if id then <stmt>
-> if id then <stmt> else <stmt>
-> id := id

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

gateoverflow.in/2739

GATE Overflow

April 2016

265 of 1876

is ambiguous because
(a) the sentence
if a then if b then c:= d

has more than two parse trees


(b) the left most and right most derivations of the sentence
if a then if b then c:= d

give rise to different parse trees


(c) the sentence
if a then if b then c:= d else c:= f

has more than two parse trees


(d) the sentence
if a then if b then c:= d else c:= f

has two parse trees



gate1996

compiler-design

grammar

normal

Selected Answer

(d) the sentence


if a then if b then c: = d else c:= f
has two parse trees as follows:

if a then (if b then c:= d) else c:= f
and
if a then (if b then c:=d else c:= f)
-- Arjun Suresh ( 124085 points)

9 votes

2.39 Grammar: GATE1995_9 top

gateoverflow.in/2644

a. Translate the arithmetic expression a (b + c) into syntax tree.


b. A grammar is said to have cycles if it is the case that
A +A
Show that no grammar that has cycles can be LL(1).

gate1995

compiler-design

grammar

normal

A grammer having left recursion generates a cycle.


And no left recursive grammer is LL(1) grammer.
2 votes

2.40 Grammar: GATE1995_1.10 top

Copyright GATE Overflow. All rights reserved.

-- simran ( 57 points)

gateoverflow.in/2597

GATE Overflow

April 2016

266 of 1876

Consider a grammar with the following productions


S ab bc aB
S S b
S bb ab
S bdb b
The above grammar is:
A. Context free
B. Regular
C. Context sensitive
D. LR(k)

gate1995

compiler-design

grammar

normal

Selected Answer

S ->
This violates the conditions of context-free and hence the grammar becomes context-sensitive.
-- Arjun Suresh ( 124085 points)

8 votes

2.41 Grammar: GATE1998_14 top

gateoverflow.in/1728

a. Let G 1 = (N, T, P, S1 ) be a CFG where, N = {S1 A, B}, T = {a, b} and P is given by


S1 aS1 b

S1 aBb

S1 aAb

B Bb

A aA

Bb

Aa

What is L(G 1 )?
b. Use the grammar in Part(a) to give a CFG for L2 = {aibiakbl i, j, k, 1 1, i = j or k = l} by adding not more than 5 production
rules.
c. Is L2 inherently ambiguous?

gate1998

compiler-design

grammar

descriptive

2.42 Grammar: GATE1994_1.18 top


Which of the following features cannot be captured by context-free grammars?
A. Syntax of if-then-else statements
B. Syntax of recursive procedures
C. Whether a variable has been declared before its use

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/2461

GATE Overflow

April 2016

267 of 1876

D. Variable names of arbitrary length



gate1994

compiler-design

grammar

normal

Selected Answer

It will be C.
Since CFG's are used to show syntactic rules while designing compiler, and syntactic rules don't check for meaningful
things such as if a variable has been declared before its use or not. Such things are meant to be handled by Semantic
Analysis phase (requires power of a context sensitive grammar).
-- Gate Keeda ( 16619 points)

11 votes

2.43 Grammar: GATE2001_17 top

gateoverflow.in/758

The syntax of the repeat-until statement is given by the following grammar


S repeat S1 until E
where E stands for expressions, S and S1 stand for statements. The non-terminals S and S1 have an attribute code that
represents generated code. The non-terminal E has two attributes. The attribute code represents generated code to evaluate
the expression and store its value in a distinct variable, and the attribute varName contains the name of the variable in
which the truth value is stored? The truth-value stored in the variable is 1 if E is true, 0 if E is false.
Give a syntax-directed definition to generate three-address code for the repeat-until statement. Assume that you can call a
function newlabel() that returns a distinct label for a statement. Use the operator '\\' to concatenate two strings and the
function gen(s) to generate a line containing the string s.
gate2001

compiler-design

grammar

normal

2.44 Grammar: GATE2003_56 top


Consider the grammar shown below
S i E t S S | a
S e S |
E b
In the predictive parse table, M, of this grammar, the entries M[S , e] and M[S , $] respectively are
A. {S
B. {S
C. {S
D. {S

e S} and {S }
e S} and { }
} and {S }
e S, S } and {S }


gate2003

compiler-design

grammar

Selected Answer

First (S)={i,a}
First(S')={e, episolon)
First(E)={b}
Follow(S')={e,$}

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/944

GATE Overflow

April 2016

268 of 1876

Only when first contains episolon we need to consider follow


M[S',e]={S'->eS(first),S'->episolon(considering follow)}
M[S',$}={S->episolon}

S S->a S->ietSS'

S'

S'->episolon

E->b

S'->eS
S'->episolon

answer is d
-- Pooja ( 22745 points)

7 votes

2.45 Grammar: GATE2001_18 top

gateoverflow.in/759

(a) Remove left-recursion from the following grammar:


S Sa Sb a b
(b) Consider the following grammar:
S aSbS bSaS
Construct all possible parse trees for the string abab. Is the grammar ambiguous?
gate2001

compiler-design

grammar

Selected Answer

a) S->aS'/bS'
S'->aS'/bS'/e
b)S->aSbS->abS->abaSbS>ababS->abab
S->aSbS->abSaSbS->abaSbS->ababS->abab
Two derivation so it is ambiguous
-- Pooja ( 22745 points)

5 votes

2.46 Grammar: GATE1994_20 top

gateoverflow.in/2516

A grammar G is in Chomsky-Normal Form (CNF) if all its productions are of the form A BC or A a, where A, B and C, are
non-terminals and a is a terminal. Suppose G is a CFG in CNF and w is a string in L(G) of length n, then how long is a
derivation of w in G?
gate1994

compiler-design

grammar

normal

Selected Answer

its answer is 2n-1 for n length string, because in CNF at every step only 1 terminal can replace a variable, for example
S-AB
A-a
B-c

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

269 of 1876

for generating string 'ac' 3 production will be used.


-- Manu Thakur ( 5261 points)

8 votes

2.47 Intermediate Code: GATE1992-11b top

gateoverflow.in/43583

Write 3 address intermediate code (quadruples) for the following boolean expression in the sequence as it would be
generated by a compiler. Partial evaluation of boolean expressions is not permitted. Assume the usual rules of precedence of
the operators.
(a + b) > (c + d) or a > c and b < d

gate1992

compiler-design

syntax-directed-translation

intermediate-code

descriptive

2.48 Intermediate Code: GATE2015-1_55 top

gateoverflow.in/8365

The least number of temporary variables required to create a three-address code in static single assignment form for the
expression q + r / 3 + s - t * 5 + u * v/w is__________________.
gate2015-1

compiler-design

intermediate-code

normal

Selected Answer

Answer is 8.
In compiler design, static single assignment form (often abbreviated as SSA form or simply SSA) is a property of an intermediate representation (IR), which
requires that each variable is assigned exactly once, and every variable is dened before it is used. Existing variables in the original IR are split into versions,
new variables.

We will need a temporary variable for storing the result of each binary operation as SSA (Static Single Assignment) implies
the variable cannot be repeated on LHS of assignment.
q + r / 3 + s - t * 5 + u * v/w
t1 = r/3;
t2 = t*5;
t3 = u*v;
t4 = t3/w;
t5 = q + t1;
t6 = t5 + s;
t7 = t6 - t2;
t8 = t7 + t4

http://web.stanford.edu/class/archive/cs/cs143/cs143.1128/handouts/240%20TAC%20Examples.pdf
17 votes

-- Arjun Suresh ( 124085 points)

The given expression is


q + r / 3 + s - t * 5 + u * v/w
To store result of each binary operation , we need a temporary variable. Three Address Code (TAC) and Static Single
Assignment form (SSA) implies the variable cannot be repeated.
So,
t1 = r/3;
t2 = t*5;
t3 = u*v;
t4 = t3/w;
t5 = q + t1;

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

270 of 1876

t6 = t5 + s;
t7 = t5 - t2;
t8 = t7 + t4
There should be at least 8 temporary variables required to create TAC.
-- Raghuveer Dhakad ( 849 points)

1 votes

2.49 Intermediate Code: GATE1994_1.12 top

gateoverflow.in/2453

Generation of intermediate code based on an abstract machine model is useful in compilers because
A. it makes implementation of lexical analysis and syntax analysis easier
B. syntax-directed translations can be written for intermediate code generation
C. it enhances the portability of the front end of the compiler
D. it is not possible to generate code for real machines directly from high level language programs

gate1994

compiler-design

intermediate-code

easy

Selected Answer

C. stating the actual use of the Intermediate Code.


Also optimizations can be done on intermediate code enhancing the portability of the optimizer.
-- Gate Keeda ( 16619 points)

8 votes

2.50 Intermediate Code: GATE2015-1_8 top

gateoverflow.in/8096

For computer based on three-address instruction formats, each address field can be used to specify which of the following:
(S1) A memory operand
(S2) A processor register
(S3) An implied accumulator register
A. Either S1 or S2
B. Either S2 or S3
C. Only S2 and S3
D. All of S1, S2 and S3
gate2015-1

compiler-design

intermediate-code

normal

Selected Answer

Three address Instruction


Computer with three addresses instruction format can use each address field to specify either processor register or
memory operand.
ADD R1, A, B A1 M [A] + M [B]
ADD R2, C, D R2 M [C] + M [B] X = (A + B) * (C + A)
MUL X, R1, R2 M [X] R1 * R2
The advantage of the three address formats is that it results in short program when evaluating arithmetic expression. The
disadvantage is that the binary-coded instructions require too many bits to specify three addresses.
-

Copyright GATE Overflow. All rights reserved.

See

more

at:

GATE Overflow

April 2016

271 of 1876

http://www.laureateiit.com/projects/bacii2014/projects/coa_anil/instruction_formate.html#sthash.7y6Hcwvd.dpuf

-- Prasanna Ranganathan ( 2051 points)

6 votes

option A either A memory operand or A processor register.


-- Anoop Sonkar ( 4167 points)

11 votes

2.51 Intermediate Code: GATE2014-2_34 top

gateoverflow.in/1993

For a C program accessing X[i] [j] [k], the following intermediate code is generated by a compiler. Assume that the size of an integer is 32 bits and the
size of a character is 8 bits.
t0
t1
t2
t3
t4
t5

=
=
=
=
=
=

i 1024
j 32
k 4
t1 + t0
t3 + t2
X[t4]

Which one of the following statements about the source code for the C program is CORRECT?

(A) X is declared as "int X[32] [32] [8].
(B) X is declared as "int X[4] [1024] [32].
(C) X is declared as "char X[4] [32] [8].
(D) X is declared as "char X[32] [16] [2].

gate2014-2

compiler-design

intermediate-code

programming-in-c

normal

Selected Answer

k is multiplied by 4, means sizeof(dataype) is int.


j is multiplied by 32, means the inner most dimension of array is 32/4 = 8 (we have to divide by the size of the inner
dimension- which here is a simple integer)
i is multiplied by 1024, means the second dimension of array is 1024/32 = 32 (32 = 8*4 is the size of the inner dimension
here)
So, (A) is correct. The first dimension is not needed for code generation and that is why in C language while passing an
array to a function, we can omit the value of the first dimension but not any others.
10 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

272 of 1876


X is of type integer and dimensions of X are r 1 X r 2 X r 3.
value of r 2 = 32
r3 = 8

-- Vikrant Singh ( 10051 points)

6 votes

2.52 Intermediate Code: GATE2015-2_29 top


Consider the intermediate code given below.
(1) i=1
(2) j=1
(3) t1 = 5 * i
(4) t2 = t1 + j
(5) t3 = 4 * t2
(6) t4 = t3
(7) a[t4] = -1
(8) j = j + 1
(9) if j <= 5 goto (3)
(10) i = i +1
(11) if i < 5 goto (2)

The number of nodes and edges in control-flow-graph constructed for the above code, respectively, are

A. 5 and 7
B. 6 and 7
C. 5 and 5
D. 7 and 8
gate2015-2

compiler-design

intermediate-code

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/8139

GATE Overflow

April 2016

273 of 1876

Answer is 6,7 if we add an explicit start and end nodes. This follows from the definition of CFG in the below IITM link
http://www.cse.iitm.ac.in/~krishna/cs3300/pm-lecture1.pdf
But many of the standard books/universities don't follow this definition.
-- Arjun Suresh ( 124085 points)

7 votes

answer is b
-- naresh1845 ( 1135 points)

1 votes

2.53 Intermediate Code: GATE2014-3_17 top

gateoverflow.in/2051

One of the purposes of using intermediate code in compilers is to


(A) make parsing and semantic analysis simpler.
(B) improve error recovery and error reporting.
(C) increase the chances of reusing the machine-independent code optimizer in other compilers.
(D) improve the register allocation.

gate2014-3

compiler-design

intermediate-code

easy

Selected Answer

C.
that is the actual use of intermediate code generator in a compiler.
8 votes

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

GATE Overflow

April 2016

2.54 Intermediate Code: GATE1992-11a top

274 of 1876

gateoverflow.in/590

Write syntax directed definitions (semantic rules) for the following grammar to add the type of each identifier to its entry in
the symbol table during semantic analysis. Rewriting the grammar is not permitted and semantic rules are to be added to
the ends of productions only.
D TL;
T int
T real
L L, id
L id

gate1992

compiler-design

syntax-directed-translation

intermediate-code

normal

quadruples consists of the 4-section they are operator, operand1, operand2, result
operator operand1 operand2 result
+ a b t1
+ c d t2
> t1 t2 t3
> a c t4
< b d t5
and t4 t5 t6
or t3 t6 t7
-- Anupoju Satish Kumar ( 219 points)

3 votes

PRODUCTION RULE SEMANTIC ACTIONS


D->TL L.in:=T.type
T->int T.type:=integer
T->real T.type:=real
L->L,id L1.in=L.in
Enter_type(id.entry, L.in)
L->id Enter_type(id.entry, L.in)
-- Anupoju Satish Kumar ( 219 points)

1 votes

2.55 Lexical Analysis: GATE2011_1 top


In a compiler, keywords of a language are recognized during
(A) parsing of the program
(B) the code generation
(C) the lexical analysis of the program
(D) dataflow analysis

gate2011

compiler-design

lexical-analysis

Copyright GATE Overflow. All rights reserved.

easy

gateoverflow.in/2103

GATE Overflow

April 2016

275 of 1876

Selected Answer

Typically, the lexical analysis phase of compilation breaks the input text up into sequences of lexemes that each belongs to some particular
token type that's useful in later analysis. Consequently, keywords are usually rst recognized during lexical analysis in order to make
parsing easier. Since parsers tend to be implemented by writing context-free grammars of tokens rather than of lexemes (that is,
the category of the lexeme rather than the contents of the lexeme), it is signicantly easier to build a parser when keywords are marked
during lexing. Any identifier is also a token so it is recognized in lexical Analysis .
Hence option C is True.
ref@ http://stackoverflow.com/questions/5202709/phases-of-a-compiler

-- Mithlesh Upadhyay ( 2633 points)

4 votes

2.56 Lexical Analysis: GATE2010_13 top

gateoverflow.in/2186

Which data structure in a compiler is used for managing information about variables and their attributes?
A. Abstract syntax tree
B. Symbol table
C. Semantic stack
D. Parse table

gate2010

compiler-design

lexical-analysis

easy

Selected Answer

Symbol table is answer . It can be implemented by using array , hash table , tree and eve some time with the help of
lInked list !
-- Dexter ( 1917 points)

1 votes

B. It uses array to implement.


-- Gate Keeda ( 16619 points)

10 votes

2.57 Lexical Analysis: GATE2011_19 top

gateoverflow.in/2121

The lexical analysis for a modern computer language such as Java needs the power of which one of the following machine models in a
necessary and sufficient sense?
(A) Finite state automata
(B) Deterministic pushdown automata
(C) Non-deterministic pushdown automata
(D) Turing machine

gate2011

compiler-design

lexical-analysis

easy

answer - A
lexical analysis can be done via a simple DFA
3 votes

Copyright GATE Overflow. All rights reserved.

-- ankitrokdeonsns ( 7941 points)

GATE Overflow

April 2016

2.58 Lexical Analysis: GATE2000_1.18 top

276 of 1876

gateoverflow.in/641

The number of tokens in the following C statement


printf("i=%d, &i=%x", i, &i);
is

A. 3
B. 26
C. 10
D. 21
gate2000

compiler-design

lexical-analysis

easy

Selected Answer

answer - C
Tokens are:
1. printf
2. (
3. "i=%d, &i=%x"
4. ,
5. i
6. ,
7. &
8. i
9. )
10. ;
10 votes

-- ankitrokdeonsns ( 7941 points)

1.printf
2.(
3."i=%d, &i=%x"
4.,
5.i
6.,
7.&
8.i
9.)
10.;
option C

1 votes

2.59 Linking: GATE2003_76 top

-- Umang Raman ( 10379 points)

gateoverflow.in/962

Which of the following is NOT an advantage of using shared, dynamically linked libraries as opposed to using statistically
linked libraries?
A. Smaller sizes of executable files
B. Lesser overall page fault rate in the system
C. Faster program startup

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

277 of 1876

D. Existing programs need not be re-linked to take advantage of newer versions of libraries
gate2003

compiler-design

runtime-environments

linking

easy

Selected Answer

option c) DLL takes more time in program setup (in loading and linking phase to set up the global offset table and load and
link the required libraries)
Since DLLs are separated from executable, the size of executable becomes smaller.
Since DLLs are shared among multiple executables, the total memory usage of the system goes down and hence overall
page fault rate decreases.
Dynamic linking takes place during program runtime. So, if a DLL is replaced to a new version, it will automatically get
linked during runtime. There is no explicit relinking required as in the case of static linking. (This works by linking the DLL
calls to Global Offset Table and the contents of this table is filled during program run. A simple jump in static linking
becomes an indirect jump in dynamic linking).
-- GateMaster Prime ( 1263 points)

13 votes

2.60 Live Variable: GATE2015-1_50 top

gateoverflow.in/8356

A variable x is said to be live at a statement s i in a program if the following three conditions hold simultaneously:
i. There exists a statement S j that uses x
ii. There is a path from S i to S j in the flow graph corresponding to the program
iii. The path has no intervening assignment to x including at S i and S j

The variables which are live both at the statement in basic block 2 and at the statement in basic block 3 of the above control
flow graph are
A. p, s, u
B. r, s, u
C. r, u
D. q, v
gate2015-1

compiler-design

live-variable

normal

Selected Answer

r, u.
p, and s are assigned to in 1 and there is no intermediate use of them before that. Hence p, and s are not live in both 2
and 3.
q is assigned to in 4 and hence is not live in both 2 and 3.
v is live at 3 but not at 2.
u is live at 3 and also at 2 if we consider a path of length 0 from 2 - 2.
So, r, u is the answer.
5 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

2.61 Macros: GATE1995_1.11 top

278 of 1876

gateoverflow.in/2598

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 parameters
D. Formal parameters

gate1995

compiler-design

macros

easy

Selected Answer

ans is D
-- jayendra ( 5797 points)

3 votes

2.62 Macros: GATE1996_2.16 top

gateoverflow.in/2745

Which of the following macros can put a macro assembler into an infinite loop?
(i)
i. .MACRO M1, X

.IF EQ, X
;if X=0 then
M1 X + 1
.ENDC
.IF NE, X
;if X O then
.WORD X ;address (X) is stored here
.ENDC
.ENDM

(ii)
ii. .MACRO M2, X
.IF EQ, X
M2 X
.ENDC
.IF NE, X
.WORD X + 1
.ENDC
.ENDM

A. (ii) only
B. (i) only
C. both (i) and (ii)
D. None of the above

gate1996

compiler-design

macros

normal

Selected Answer

if M2 macro is called with x=0, then it'll go into an infinite loop.


Hence correct option would be A.
1 votes

Copyright GATE Overflow. All rights reserved.

-- suraj ( 3299 points)

GATE Overflow

April 2016

279 of 1876

2.63 Macros: GATE1997_1.9 top

gateoverflow.in/2225

The conditional expansion facility of macro processor is provided to


a. test a condition during the execution of the expanded program
b. to expand certain model statements depending upon the value of a condition during the execution of the expanded
program
c. to implement recursion
d. to expand certain model statements depending upon the value of a condition during the process of macro expansion
gate1997

compiler-design

macros

easy

Selected Answer

Macro is expanded during the process of macro expansion. Hence, correct answer would be (d).
-- suraj ( 3299 points)

5 votes

2.64 Macros: GATE1992_01,vii top

gateoverflow.in/552

Macro expansion is done in pass one instead of pass two in a two pass macro assembler because _________
gate1992

compiler-design

macros

easy

2.65 Parameter Passing: GATE1991_03,x top

gateoverflow.in/524

Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Indicate all the true statements from the following:
(a). Recursive descent parsing cannot be used for grammar with left recursion.
(b). The intermediate form for representing expressions which is best suited for code optimization is the postfix form.
(c). A programming language not supporting either recursion or pointer type does not need the support of dynamic memory
allocation.
(d). Although C does not support call-by-name parameter passing, the effect can be correctly simulated in C
(e). No feature of Pascal typing violates strong typing in Pascal.

gate1991

compiler-design

parameter-passing

programming

difficult

A for sure, not sure about E


2 votes

2.66 Parameter Passing: GATE 2016-1-36 top

-- Shaun Patel ( 5445 points)

gateoverflow.in/39701

What will be the output of the following pseudo-code when parameters are passed by reference and dynamic scoping is
assumed?
a = 3;
void n(x) { x = x * a; print (x); }
void m(y) { a = 1 ; a = y - a; n(a); print (a); }
void main () { m(a); }

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

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

280 of 1876


gate2016-1

parameter-passing

normal

Selected Answer

It is a bit confusing as variable declaration is not explicit. But we can see that "a=3" and "a=1" are declaring new
variables, one in global and other in local space.
Main is calling m(a). Since there is no local 'a', 'a' here is the global one.
In m, we have "a = 1" which declares a local "a" and gives 1 to it. "a = y-a" assigns 3-1 = 2 to 'a'.
Now, in n(x), 'a' is used and as per dynamic scoping this 'a' comes from 'm()' and not the global one. So, "x=x*a" assigns
"2*2 = 4" to "x" and 4 is printed. Being passed by reference, "a" in m() also get updated to 4. So, D is the answer here.
-- Arjun Suresh ( 124085 points)

11 votes

A is the answer
-- Sathish Satz ( 157 points)

5 votes

Answer is B
-- Deepak Sharma ( 367 points)

1 votes

2.67 Parsing: GATE1998_1.26 top

gateoverflow.in/1663

Which of the following statements is true?


A. SLR paper is more powerful than LALR
B. LALR parser is more powerful than Canonical LR parser
C. Canonical LR parser is more powerful than LALR parser
D. The parsers SLR, Canonical CR, and LALR have the same power

gate1998

compiler-design

parsing

normal

answer - C
5 votes

2.68 Parsing: GATE2006_07 top


Consider the following grammar
S S * E
S E
E F + E
E F
F id
Consider the following LR(0) items corresponding to the grammar above
(i) S S *.E
(ii) E F. + E
(iii) E F + .E

Copyright GATE Overflow. All rights reserved.

-- ankitrokdeonsns ( 7941 points)

gateoverflow.in/886

GATE Overflow

April 2016

281 of 1876

Given the items above, which two of them will appear in the same set in the canonical sets-of-items for the grammar?
(A) (i) and (ii)
(B) (ii) and (iii)
(C) (i) and (iii)
(D) None of the above

gate2006

compiler-design

parsing

normal

Selected Answer

ans is D.

-- jayendra ( 5797 points)

3 votes

There will be 9 sets I 0 to I 8


(I) will be in set I 5
(II) will be in set I 3
(III) will be in set I 6
So (D)
-- Danish ( 1967 points)

1 votes

2.69 Parsing: GATE1998_22 top

gateoverflow.in/1737

a. An identifier in a programming language consists of up to six letters and digits of which the first character must be a
letter. Derive a regular expression for the identifier.
b. Build an LL(1) parsing table for the language defined by the LL(1) grammar with productions
Program begin d semi X end
X d semi X sY
Y semi sY

gate1998

compiler-design

parsing

descriptive

a.
(letter)(letter + digit + epsilon)^5
b.
1.program ---> begin s end
2. X -----> d semi x

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

282 of 1876

3. | sY
4. Y -----> semi sY
5. | epsilon
begin d semi s end $
program 1
X 2 3
Y 4 5
-- Digvijay Pandey ( 26235 points)

1 votes

2.70 Parsing: GATE1995_8 top

gateoverflow.in/2643

Construct the LL(1) table for the following grammar.


1. Expr _Expr
2. Expr (Expr)
3. Expr Var ExprTail
4. ExprTail _Expr
5. Expr
6. Var Id VarTail
7. VarTail (Expr)
8. VarTail
9. Goal Expr$

gate1995

compiler-design

parsing

normal

2.71 Parsing: GATE2003_16 top

gateoverflow.in/906

Which of the following suffices to convert an arbitary CFG to an LL(1) grammar?



A. Removing left recursion alone
B. Factoring the grammar alone
C. Removing left recursion and factoring the grammar
D. None of the above

gate2003

compiler-design

parsing

easy

Selected Answer

LL(1) parser is top down parser.


For top down paraers, the grammar should be unambiguous, deterministic and should not be left recursive.
All the 3 conditions must be satisfied for LL(1) parsers and not just 2.
So, option D is correct.
5 votes

-- Monanshi Jain ( 5787 points)

D. Removing left recursion and factoring the grammar do not suffice to convert an arbitrary CFG to LL(1) grammar.
4 votes

-- Vikrant Singh ( 10051 points)

Answer is d . Removing left recursion and left factoring is necessary but not sufficent condition for LL(1)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

283 of 1876
-- Dexter ( 1917 points)

1 votes

LL(1) properties:
1. Un ambiguous
2. Not left recursive
3. Deterministic
I think C does not make the CFG unambiguous all the time.
-- Saumya ( 489 points)

1 votes

2.72 Parsing: TIFR2012-B-8 top

gateoverflow.in/25108

Consider the parse tree

Assume that has higher precedence than + , and operators associate right to left (i.e (a + b + c = (a + (b + c))). Consider
(i) 2 + a b
(ii) 2 + a b a + b
(iii) 2 + ((a b) (a + b)))
(iv) 2 + (a b) (a + b)
The parse tree corresponds to
a. Expression (i)
b. Expression (ii)
c. Expression (iv) only
d. Expression (ii), (iii), and (iv)
e. Expression (iii) and (iv) only
tifr2012

compiler-design

parsing

Selected Answer

e is correct
Because as the expression evaluated right to left , so in (ii) 2+(a-(b*(a+b))) this evaluation performed, which is not a
correct evaluation as the parse tree
2 votes

2.73 Parsing: GATE2013_9 top

-- srestha ( 11537 points)

gateoverflow.in/1418

What is the maximum number of reduce moves that can be taken by a bottom-up parser for a grammar with no epsilon and
unit-production (i.e., of type A and A a) to parse a string with n tokens?
(A) n/2

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

284 of 1876

(B) n 1
(C) 2n 1
(D) 2n
gate2013

compiler-design

parsing

normal

Selected Answer

Ans will be B
A->BC
B->aa
C->bb
now suppose string is aabb
then
A->BC(reduction 3)
->aaC(reduction 2)
->aabb (reduction 1)
n = 4
and number of reductions are 3 so n-1
-- raunak bairoliya ( 329 points)

6 votes

The answer is C.
Take,
S-->AB
A-->a
B-->b.
Derive ab. you'll have 3 reduce moves.
-- Gate Keeda ( 16619 points)

2 votes

2.74 Parsing: GATE2003_17 top

gateoverflow.in/907

Assume that the SLR parser for a grammar G has n1 states and the LALR parser for G has n2 states. The relationship
between n1 and n2 is

A. n1 is necessarily less than n2
B. n1 is necessarily equal to n2
C. n1 is necessarily greater than n2
D. None of the above

gate2003

compiler-design

parsing

Copyright GATE Overflow. All rights reserved.

easy

GATE Overflow

April 2016

285 of 1876

Selected Answer

no of states in slr and lalr are equal


and no of states in slr and lalr are less than or equal to lr(1)
-- Pooja ( 22745 points)

5 votes

ans b)
-- Aditi Dan ( 5103 points)

3 votes

2.75 Parsing: TIFR2012-B-17 top

gateoverflow.in/25215

Which of the following correctly describes LR(k) parsing?


a. The input string is alternately scanned left to right and right to left with k reversals.
b. Input string is scanned once left to right with rightmost derivation and k symbol look-ahead.
c. LR(k) grammers are expressively as powerful as context-free grammers.
d. Parser makes k left-to-right passes over input string.
e. Input string is scanned from left to right once with k symbol to the right as look-ahead to give left-most derivation.

tifr2012

compiler-design

parsing

Selected Answer

A) Does not make any sense. false.


B) This is definition of LR(K) Parser. True
C) False. LR(K) is subset of CFL.
D) False.
E) LR(K) , bottom up parser . We have Right most derivation. This is False.
Answer :- B
-- Akash ( 26265 points)

4 votes

https://www.google.co.in/?gfe_rd=cr&ei=DQY4VuOPMe_I8Aenm4GIBw#q=lr(k)+parser
Ans will be b
-- srestha ( 11537 points)

1 votes

2.76 Parsing: GATE2002_22 top

gateoverflow.in/875

a. Construct all the parse trees corresponding to i + j * k for the grammar


E E+E
E E*E
E id
b. In this grammar, what is the precedence of the two operators * and +?
c. If only one parse tree is desired for any string in the same language, what changes are to be made so that the resulting
LALR(1) grammar is unambiguous?
gate2002

compiler-design

parsing

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

286 of 1876

Selected Answer

a. two parse tree for i+j*k.


b. + and * having same precedence..
c. to make grammer LALR compatible give priority to + over * or vice versa.
following grammar is LALR(1)
E -----> E + T
| T
T ------> T * F
| F
F ------> id
-- Digvijay Pandey ( 26235 points)

3 votes

2.77 Parsing: GATE2003_57 top

gateoverflow.in/945

Consider the grammar shown below.


S C C
C c C | d
This grammar is
A. LL(1)
B. SLR(1) but not LL(1)
C. LALR(1) but not SLR(1)
D. LR(I) but not LALR(1)


gate2003

compiler-design

grammar

parsing

normal

Selected Answer

ans is a
First(S)=First(C)={c,d}
there are no multiple in single row of parsing table hence grammar is LL1
note : if we have A->B/C for grammar to be LL(1) first(B)intersection First(C) should be null otherwise grammar is not
LL1.If First(B) contains epislon then Follow(A) intersection First(C) should be null.Using this we can say grammar is LL(1)
or not without constructing parsing table.
An free LL(1) grammar is also SLR(1) and hence LALR(1) and LR(1) too.
3 votes

2.78 Parsing: GATE2001_16 top

-- Pooja ( 22745 points)

gateoverflow.in/757

Consider the following grammar with terminal alphabet {a, (, ), + , } and start symbol E. The production rules of the grammar
are:
E aA
E (E)
A +E
A E

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

287 of 1876

A
a. Compute the FIRST and FOLLOW sets for E and A.
b. Complete the LL(1) parse table for the grammar.
gate2001

compiler-design

parsing

normal

Selected Answer

First (E) = { a,( }


First (A) = { +,*, }
Follow (E) = Follow (A) = { $ ,) }
LL(1) Parsing Table :
a ( ) + *

E E-> aA E-> (E)


A A-> A->+E A->*E A->

-- Aditya Gaurav ( 1831 points)

4 votes

2.79 Parsing: GATE2005-IT_83a top

gateoverflow.in/3849

Consider the context-free grammar


E E + E
E (E * E)
E id
where E is the starting symbol, the set of terminals is {id, (,+,),*}, and the set of nonterminals is {E}.
Which of the following terminal strings has more than one parse tree when parsed according to the above grammar?


A)
id + id + id + id
B)
id + (id* (id * id))
C)
(id* (id * id)) + id
D)
((id * id + id) * id)
gate2005-it

compiler-design

grammar

parsing

easy

Selected Answer

Answer is A.
7 votes

-- Gate Keeda ( 16619 points)

5 parse trees
1 votes

2.80 Parsing: GATE2005-IT_83b top


Consider the context-free grammar

Copyright GATE Overflow. All rights reserved.

-- jayendra ( 5797 points)

gateoverflow.in/3850

GATE Overflow

April 2016

288 of 1876

E E + E
E (E * E)
E id
where E is the starting symbol, the set of terminals is {id, (,+,),*}, and the set of non-terminals is {E}.

For the terminal string id + id + id + id, how many parse trees are possible?

A)
5
B)
4
C)
3
D)
2
gate2005-it

compiler-design

parsing

normal

Selected Answer

5 parse trees are possible.


-- ujjwal saini ( 301 points)

4 votes

2.81 Parsing: GATE2015-1_13 top

gateoverflow.in/8187

Which one of the following is TRUE at any valid state in shift-reduce parsing?
A. Viable prefixes appear only at the bottom of the stack and not inside
B. Viable prefixes appear only at the top of the stack and not inside
C. The stack contains only a set of viable prefixes
D. The stack never contains viable prefixes
gate2015-1

compiler-design

parsing

normal

Selected Answer

C) should be the answer


-- GateMaster Prime ( 1263 points)

7 votes

2.82 Parsing: GATE1998_1.27 top

gateoverflow.in/1664

Type checking is normally done during


(a) lexical analysis
(b) syntax analysis
(c) syntax directed translation
(d) code optimization
gate1998

compiler-design

parsing

easy

Selected Answer

The answer is C .
The use of syntax analyser is used to create parse Tree. But along with Grammar as input to Syntax Analyser we add
even semantic rules which form the basis of Syntax Directed Translation That help us in Evaluation of Expression
.Remember that
Syntax Directed Translation are used in following cases

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

289 of 1876

1. Conversion of infix to Postfix


2.Calculation of infix expression
3.For creating a Acyclic graph
4.Type Checking
5.Conversion of Binary number to Decimal
6.Counting the numbers of bits (0 or 1 ) in a binary number
7.Creation of syntax tree
8. To generate Intermediate code
9. Storing the data into Symbol table
-- spriti1991 ( 1127 points)

6 votes

2.83 Parsing: GATE2000_1.19 top

gateoverflow.in/642

Which of the following derivations does a top-down parser use while parsing an input string? The input is assumed to be
scanned in left to right order.
A. Leftmost derivation
B. Leftmost derivation traced out in reverse
C. Rightmost derivation
D. Rightmost derivation traced out in reverse

gate2000

compiler-design

parsing

normal

Selected Answer

ans a)
-- Aditi Dan ( 5103 points)

3 votes

2.84 Parsing: GATE2008-IT_79 top

gateoverflow.in/3393

A CFG G is given with the following productions where S is the start symbol, A is a non-terminal and a and b are terminals.
S aS AA aAb bAa
For the correct answer in above Question http://gateoverflow.in/3392/gate2008-it_78, how many steps are required to
derive the string and how many parse trees are there?

A)

6 and 1

B)

6 and 2

C)
D)

7 and 2
4 and 2

gate2008-it

compiler-design

context-free

parsing

Selected Answer

S aS 1

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

290 of 1876

S aA 2
S aaAb 3
S aabAab 4
S aabbAaab 5
S aabbaab 6
Thus 6 steps are needed and only one way to derive the string so only one parse tree.
-- Shreyans Dhankhar ( 2265 points)

13 votes

2.85 Parsing: GATE1993_25 top

gateoverflow.in/2321

A simple Pascal like language has only three statements.


i. assignment statement e.g. x:=expression
ii. loop construct e.g. for i:=expression to expression do statement
iii. sequencing e.g. begin statement ;; statement end

A. Write a context-free grammar (CFG) for statements in the above language. Assume that expression has already been
defined. Do not use optional parenthesis and * operator in CFG.
B. Show the parse tree for the following statements:
for j:=2 to 10 do
begin
x:=expr1;
y:=expr2;
end



gate1993

compiler-design

parsing

normal

2.86 Parsing: GATE2015-3_16 top

gateoverflow.in/8413

Among simple LR (SLR), canonical LR, and look-ahead LR (LALR), which of the following pairs identify the method that is
very easy to implement and the method that is the most powerful, in that order?

A. SLR, LALR
B. Canonical LR, LALR
C. SLR, canonical LR
D. LALR, canonical LR
gate2015-3

compiler-design

parsing

normal

Selected Answer

Answer is C.
SLR is the simplest to implement and Canonical LR is the most powerful.
http://en.wikipedia.org/wiki/LALR_parser_generator
14 votes

2.87 Parsing: GATE1992_02,xiv top

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/571

GATE Overflow

April 2016

291 of 1876

Choose the correct alternatives (more than one may be correct ) and write the corresponding letters only:
Consider the SLR(1) and LALR(1) parsing tables for a context free grammar. Which of the following statement is/are true?
(a). The goto part of both tables may be different.
(b). The shift entries are identical in both the tables.
(c). The reduce entries in the tables may be different.
(d). The error entries in tables may be different

gate1992

compiler-design

normal

parsing

Selected Answer

Goto part & shift entry must be same.


Reduce entry & error entry may b different due to conflicts.
-- Digvijay Pandey ( 26235 points)

5 votes

2.88 Parsing: GATE2015-3_31 top

gateoverflow.in/8488

Consider the following grammar G


S F | H
F p | c
H d | c
Where S, F, and H are non-terminal symbols, p, d, and c are terminal symbols. Which of the following statement(s) is/are
correct?
S1: LL(1) can parse all strings that are generated using grammar G
S2: LR(1) can parse all strings that are generated using grammar G

A. Only S1
B. Only S2
C. Both S1 and S2
D. Neither S1 and S2
gate2015-3

compiler-design

parsing

normal

Selected Answer

A parser works on the basis of given grammar. It takes the grammar as it is. Parser does not work on the
basis of the yield of the grammar. Also, while constructing the LL(1) parser table, that entry for terminal 'c'
will contain multiple entries. SO LL(1) parser cannot be constructed for the given grammar.
S F | H
F p | c
H d | c

That {p, d, c} are the strings generated by the grammar is absolutely correct. But LL(1) and LR(1) can parse these strings
successfully only if the grammar is unambiguous and like given below...

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

292 of 1876

S P | D | C
P p
D d
C c

Please note the dierence between these two grammars. Both derive the same strings, but in dierent manner. With the
grammar given in the question, both top-down and bottom-up parsers will get confused while deriving "c". Top-down
parser will get confused between F c and H c. Similarly, bottom-up parser will get confused while reducing "c". This
confusion in case of bottom-up parsing is technically termed as "reduce-reduce" conflict.
While top-down parsing, follow(F) and follow(H) are not disjoint, so the grammar cannot be LL(1). Therefore, LL(1) parser
cannot parse it.
Hence, the answer should be option (D). Neither S1 nor S2.
17 votes

-- ashishacm ( 251 points)

Answer is D
Grammar is ambiguous
6 votes

2.89 Parsing: TIFR2015-B-15 top

-- overtomanu ( 1023 points)

gateoverflow.in/30079

Consider the following grammar (the start symbol is E) for generating expressions.
E T E | T + E | T
T T F | F
F 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
With respect to this grammar, which of the following trees is the valid evaluation tree for the expression 2 3 4 5 6 + 7?
(a)

(b)

(c)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

293 of 1876

(d)

(e)

tifr2015

parsing

Selected Answer

Answer is option B.
The corresponding parse tree is drawn for the given expression according to the given grammar .

5 votes

Copyright GATE Overflow. All rights reserved.

-- Riya Roy ( 4769 points)

GATE Overflow

April 2016

294 of 1876

Answer will be (B)


Evaluation will be ((2*3)*4)-((5*6)+7)
-- srestha ( 11537 points)

1 votes

2.90 Parsing: GATE1999_1.17 top

gateoverflow.in/1470

Which of the following is the most powerful parsing method?


A. LL (1)
B. Canonical LR
C. SLR
D. LALR
gate1999

compiler-design

parsing

easy

ans b)
2 votes

-- Aditi Dan ( 5103 points)

Canonical LR is most powerful method


LR>LALR>SLR
so ans is b
1 votes

2.91 Parsing: GATE2006_58 top


Consider the following grammar:

Copyright GATE Overflow. All rights reserved.

-- Pooja ( 22745 points)

gateoverflow.in/1836

GATE Overflow

April 2016

295 of 1876

S FR
R S
F id
In the predictive parser table, M, of the grammar the entries M[S,id] and M[R,$] respectively are
(A) {S FR} and {R }
(B) {S FR} and {}
(C) {S FR} and {R S}
(D) {F id} and {R }

gate2006

compiler-design

parsing

normal

First S={id}
Follow R={$}
so M[S,id]=S->FR
M[S,/$]=R->episolon
so ans is a
3 votes

2.92 Parsing: GATE2011_27 top

-- Pooja ( 22745 points)

gateoverflow.in/2129

Consider two binary operators and with the precedence of operator being lower than that of the operator .
Operator is right associative while operator is left associative. Which one of the following represents the parse tree for
expression (7 3 4 3 2)
(A)

(B)

(C)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

296 of 1876

(D)

gate2011

compiler-design

parsing

normal

Selected Answer

Answer is B.

-- Sona Praneeth Akula ( 3473 points)

7 votes

2.93 Parsing: GATE2013_40 top

gateoverflow.in/1551

Consider the following two sets of LR(1) items of an LR(1) grammar.


X c.X, c/d
X .cX, c/d
X .d, c/d

X c.X, $
X .cX, $
X .d, $

Which of the following statements related to merging of the two sets in the corresponding LALR parser is/are FALSE?
1. Cannot be merged since look aheads are different.
2. Can be merged but will result in S-R conflict.
3. Can be merged but will result in R-R conflict.
4. Cannot be merged since goto on c will lead to two different sets.
(A) 1 only (B) 2 only (C) 1 and 4 only (D) 1, 2, 3 and 4
gate2013

compiler-design

parsing

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

297 of 1876

Selected Answer

The TRUE statements are about merging of two states for LALR(1) parser from RR(1) parser.i.e.
1. These can be merged because kernel of these are same, look ahead don't matter in merging
2. Two states are not containing reduces item , so after merging , the merged states can not be contain any S-R
conflict.
3. There is no reduction possible so no R-R conflict
4. Merging of states does not depend on further GOTO part on any terminal.
Therefore , ALL given statement in question are FALSE , so option (d) is correct.

-- Viral Kapoor ( 1777 points)

7 votes

2.94 Parsing: GATE2009_42 top

gateoverflow.in/1328

Which of the following statements are TRUE?


I. There exist parsing algorithms for some programming languages whose complexities are less than (n3 )
II. A programming language which allows recursion can be implemented with static storage allocation.
III. No L-attributed definition can be evaluated in the framework of bottom-up parsing.
IV. Code improving transformations can be performed at both source language and intermediate code level.

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


gate2009

compiler-design

parsing

normal

Selected Answer

Answer is B.
A: Yes there does exist parsing algos less than

Copyright GATE Overflow. All rights reserved.

(n3).

GATE Overflow

April 2016

298 of 1876

B: It cannot be implemented with static storage allocation. It needs dynamic memory allocation.
C: If the L-attributed definitions contain synthesized attributes then it can be evaluated.
D: True.
-- Gate Keeda ( 16619 points)

6 votes

2.95 Parsing: GATE2012-53 top

gateoverflow.in/43312

For the grammar below, a partial LL(1) parsing table is also presented along with the grammar. Entries that need to be filled
are indicated as E1, E2, and E3. is the empty string, $ indicates end of input, and, separates alternate right hand sides
of productions.
S aAbB bAaB
AS
BS

S E1

E2

$
S

A A S A S error
B B S B S E3
The appropriate entries for E1, E2, and E3 are
(A)
E1: S aAbB, A S
E2: S bAaB, B S
E1: B S

(B)
E1: S aAbB, S
E2: S bAaB, S
E3: S

(C)
E1: S aAbB, S
E2: S bAaB, S
E3: B S

(D)
E1: A S, S
E2: B S, S
E3: B S

normal

gate2012

compiler-design

Copyright GATE Overflow. All rights reserved.

parsing

GATE Overflow

April 2016

299 of 1876

Entry E1 is S aAbB, S (Follow of S contains a)


E2 is S bAaB, S (Follow of S contains b)
E3 is B S (Follow of B contains $)
Hence, the answer to question 53 is option C.

-- Pooja ( 22745 points)

1 votes

Make your own parse table. Firstly calculate First and Follow from the given grammar.
First(S)={a,b,epsilon}
First(A)={a,b,epsilon}
First(B)={a,b,epsilon}
Follow(S)= {a,b,$}
Follow(A)= {a,b}
Follow(B)= {a,b,$}
Now make LL(1) parse table
Non
Terminal
S
A
B

S-> aAbB

S-> bAbB

S-> epsilon

S-> epsilon

A->S
B->S

A->S
B-> S

S-> epsilon

B->S

Here is the explanation of entries asked in question


1) For E1 and E2 Look into First(S)={a,b,epsilon}. a is because of S-> aAbB and b is because of B-> bAaB so M[S,a] and
M[S,b] will contain S-> aAbB and B-> bAaB respectively. For epsilon Look into Follow(S)= {a,b, $}. So S-> epsilon will be
in M[S,a], M[S,b] and M[S,$]
2) Now for E2 look into First(B)= {a,b,$}. a and b are because of B->S so M[B,a] and M[B.b] will contain B->S and for
epsilon look into Follow(B)= {a,b,$}. Hence M[B,$] will contain B->S
Now we got the answer E1 is S-> aAbB, S-> epsilon, E2 is S-> bAaB, S-> epslion and E3 is B->S
.
Hence Option (C) is correct.
1 votes

-- Ashwani Kumar ( 73 points)

Ans C
Here First(S)={,a,b} ,
Follow (S)={ $,a,b}
Follow (B)={$,a,b}
1 votes

2.96 Parsing: GATE2005_83 top


Statement for Linked Answer Questions 83a & 83b:

Copyright GATE Overflow. All rights reserved.

-- Manojk ( 3327 points)

gateoverflow.in/1405

GATE Overflow

April 2016

300 of 1876

Consider the following expression grammar. The semantic rules for expression evaluation are stated next to each grammar
production.
E. val = number.val

E number
| E '+' E
| E ' ' E

E (1 ) . val = E (2 ) . val + E (3 ) . val


E (1 ) . val = E (2 ) . val E (3 ) . val

(A) The above grammar and the semantic rules are fed to a yaac tool (which is an LALR(1) parser generator) for parsing
and evaluating arithmetic expressions. Which one of the following is true about the action of yaac for the given grammar?
A. It detects recursion and eliminates recursion
B. It detects reduce-reduce conflict, and resolves
C. It detects shift-reduce conflict, and resolves the conflict in favor of a shift over a reduce action
D. It detects shift-reduce conflict, and resolves the conflict in favor of a reduce over a shift action

(B) Assume the conflicts in Part(a) of this question are resolved and an LALR(1) parser is generated for parsing arithmetic
expressions as per the given grammar. Consider an expression 3 2 + 1. What precedence and associativity properties does
the generated parser realize?
A. Equal precedence and left associativity; expression is evaluated to 7
B. Equal precedence and right associativity; expression is evaluated to 9
C. Precedence of is higher than that of +, and both operators are left associative; expression is evaluated to 7
D. Precedence of + is higher than that of , and both operators are left associative; expression is evaluated to 9

gate2005

compiler-design

parsing

Selected Answer

Adding Nandan Jha

answer....

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

301 of 1876

A
-- Kathleen Bankson ( 40113 points)

11 votes

Follow the link...I tried explaining both the questions...srry for the bad handwriting though...
http://gateoverflow.in/?qa=blob&qa_blobid=15270491569523623302

-- Nandan Jha ( 59 points)

3 votes

yes i provided the link to the image..bt frm nw on i will directly provide the image
-- Nandan Jha ( 59 points)

1 votes

2.97 Parsing: GATE2005_60 top

gateoverflow.in/1383

Consider the grammar:


S (S) a
Let the number of states in SLR (1), LR(1) and LALR(1) parsers for the grammar be n1 , n2 and n3 respectively. The following
relationship holds good:

A. n1 < n2 < n3
B. n1 = n3 < n2
C. n1 = n2 = n3
D. n1 n3 n2

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

302 of 1876


gate2005

compiler-design

parsing

normal

Selected Answer

ans b)
Both in SLR(1) and LALR(1), states are the LR(0) items while in LR(1) the states are LR(1) set of items. Number of LR(0)
items can never be greater than number of LR(1) items. So, n1 = n3 n2 , B choice. If we construct the states for the
grammar we can replace with < .
-- Aditi Dan ( 5103 points)

3 votes

2.98 Parsing: GATE2005_14 top

gateoverflow.in/1350

The grammar A AA (A) is not suitable for predictive-parsing because the grammar is:

A. ambiguous
B. left-recursive
C. right-recursive
D. an operator-grammar

gate2005

compiler-design

parsing

grammar

easy

Selected Answer

both A and B can be answers but A is a better answer. Because we have standard procedure for removing left-recursion
but ambiguity is not easy to remove. - checking if a given CFG is ambiguous is a undecidable problem.
2 votes

-- Vikrant Singh ( 10051 points)

Any Grammar which is Left Recursive will cause any Predictive Parser to fall into an infinite loop. No matter if it is
ambiguous or not, it won't be parsable. This is more stronger than saying it is ambiguous so fails.
Hence, answer = option B
3 votes

-- Amar Vashishth ( 17735 points)

answer - B
2 votes

2.99 Parsing: GATE2007_18 top


Which one of the following is a top-down parser?

A. Recursive descent parser.
B. Operator precedence parser.

Copyright GATE Overflow. All rights reserved.

-- ankitrokdeonsns ( 7941 points)

gateoverflow.in/1216

GATE Overflow

April 2016

303 of 1876

C. An LR(k) parser.
D. An LALR(k) parser.

gate2007

compiler-design

parsing

normal

answer - A
-- ankitrokdeonsns ( 7941 points)

2 votes

2.100 Parsing: GATE2012-52 top

gateoverflow.in/2181

For the grammar below, a partial LL(1) parsing table is also presented along with the grammar. Entries that need to be filled
are indicated as E1, E2, and E3. is the empty string, $ indicates end of input, and, separates alternate right hand sides
of productions.
S aAbB bAaB
AS
BS

E1

E2

AS

AS

error

BS

BS

E3

The FIRST and FOLLOW sets for the non-terminals A and B are
(A)
FIRST(A) = {a, b, } = FIRST(B)
FOLLOW(A) = {a, b}
FOLLOW(B) = {a, b, $}

(B)
FIRST(A) = {a, b, $}
FIRST(B) = {a, b, }
FOLLOW(A) = {a, b}
FOLLOW(B) = {$}

(C)
FIRST(A) = {a, b, } = FIRST(B)
FOLLOW(A) = {a, b}
FOLLOW(B) =

(D)
FIRST(A) = {a, b} = FIRST(B)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

304 of 1876

FOLLOW(A) = {a, b}
FOLLOW(B) = {a, b}

gate2012

compiler-design

parsing

normal

Selected Answer

First(S) = First(A) = First(B) = {a, b, }


Follow(A) = {a, b}
Follow(B) = Follow(S) = {a, b, $}
So, the answer to question 52 is option A.

-- Pooja ( 22745 points)

3 votes

Q 52 : ans is A.
first we can easly find.
follow of A = {a,b}, all symbols appeared after A in RHS
follow of B = {a,b,$}, as B is at the end in RHS, follow(B) = follow (S) and S is also at the end in RHS so follow(S) =
follow(A) = {a,b} and S is start symbol, so its follow contains $ also.
hence, follow(B) = {a,b,$}
Q 53.
ans is C.
-- jayendra ( 5797 points)

4 votes

2.101 Parsing: GATE2008_55 top

gateoverflow.in/478

An LALR(1) parser for a grammar G can have shift-reduce (S-R) conflicts if and only if

A. The SLR(1) parser for G has S-R conflicts
B. The LR(1) parser for G has S-R conflicts
C. The LR(0) parser for G has S-R conflicts
D. The LALR(1) parser for G has reduce-reduce conflicts

gate2008

compiler-design

parsing

normal

Selected Answer

Answer is B.
3 votes

2.102 Parsing: GATE2008_11 top

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

gateoverflow.in/409

GATE Overflow

April 2016

305 of 1876

Which of the following describes a handle (as applicable to LR-parsing) appropriately?



A. It is the position in a sentential form where the next shift or reduce operation will occur
B. It is non-terminal whose production will be used for reduction in the next step
C. It is a production that may be used for reduction in a future step along with a position in the sentential form where the
next shift or reduce operation will occur
D. It is the production p that will be used for reduction in the next step along with a position in the sentential form where
the right hand side of the production may be found

gate2008

compiler-design

parsing

normal

Selected Answer

A sentential form is the start symbol S of a grammar or any string in (V

T)* that can be derived from S.

Consider the linear grammar


({S, B}, {a, b}, S, {S

aS, S

B, B

bB, B

}).

A derivation using this grammar might look like this:


S

aS

aB

abB

abbB

abb

Each of {S, aS, aB, abB, abbB, abb} is a sentential form.


Because this grammar is linear, each sentential form has at most one variable. Hence there is never any choice about which variable to
expand next.
Here, in option D the sentential forms are same but generated differently coz we are using here Bottom Up production.
Handle:
for example the grammar is:
E E+n
E En
En
then say to derive string n + n n:

these are three different handles shown in 3 different colors = {n, E + n, E n}


that's what option D says
9 votes

-- Amar Vashishth ( 17735 points)

Answer is (D)
Handle is a substring of sentential form from which the start symbol can be reached using reduction at each step.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

306 of 1876
-- Keith Kr ( 5467 points)

6 votes

2.103 Parsing: GATE2014-1_34 top

gateoverflow.in/1807

A canonical set of items is given below


S L. > R
Q R.
On input symbol < the set has
(A) a shift-reduce conflict and a reduce-reduce conflict.
(B) a shift-reduce conflict but not a reduce-reduce conflict.
(C) a reduce-reduce conflict but not a shift-reduce conflict.
(D) neither a shift-reduce nor a reduce-reduce conflict.

gate2014-1

compiler-design

parsing

normal

Selected Answer

Ans : The given input symbol no where in the given grammar so with given symbol we have neither a shift-reduce nor a
reduce-reduce conflict. So, correct answer is (D.) ...
-- Jayesh Malaviya ( 1075 points)

10 votes

2.104 Parsing: GATE 2016-1-45 top

gateoverflow.in/39697

The attribute of three arithmetic operators in some programming language are given below.
OPERATOR
+
*

PRECEDENCE
high

ASSOCIATIVITY
Left

Medium
Low

Right
Left

ARITY
Binary
Binary
Binary


The value of the expression 2 5 + 1 7 3 in this language is ________.

gate2016-1

compiler-design

parsing

normal

numerical-answers

Selected Answer

2 - 5 + 1 - 7 * 3 will be evaluated according to the precedence and associativity as given in the question as follows:
((2 - ((5 + 1) - 7)) * 3) => ((2 - (-1))*3) => 9
19 votes

-- Monanshi Jain ( 5787 points)

2.105 Parsing: GATE1992_02,xiii top

gateoverflow.in/570

Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
For a context free grammar, FOLLOW(A) is the set of terminals that can appear immediately to the right of non-terminal A in
some "sentential" form. We define two sets LFOLLOW(A) and RFOLLOW(A) by replacing the word "sentential" by "left

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

307 of 1876

sentential" and "right most sentential" respectively in the definition of FOLLOW (A).
(a). FOLLOW(A) and LFOLLOW(A) may be different.
(b). FOLLOW(A) and RFOLLOW(A) are always the same.
(c). All the three sets are identical.
(d). All the three sets are different.
gate1992

parsing

compiler-design

normal

Selected Answer

Ans - a,b, LFollow may be different but RFollow and Follow will be same
Consider a Grammar -
S -> AB
A -> a
B -> b
Now only string derivable is { ab }.
Let's find Follow(A) in all cases :
i) Follow(A) - set of terminals that can appear immediately to the right of non-terminal A in some "sentential " form
S -> AB -> Ab -> ab
Here, we notice only 'b' can appear to the right of A.
Follow(A) = { b }
ii) LFollow(A) - set of terminals that can appear immediately to the right of non-terminal A in some "left sentential" form
S -> AB -> aB -> ab
Here, we notice no terminal can appear to the right of A.
LFollow(A) = {}
iii) RFollow(A) - set of terminals that can appear immediately to the right of non-terminal A in some "right
most sentential" form
S -> AB -> Ab -> ab
Here, we notice only 'b' can appear to the right of A.
RFollow(A) = { b }
-- Himanshu Agarwal ( 8861 points)

4 votes

2.106 Postfix: GATE1998_19b top

gateoverflow.in/15708

Compute the post fix equivalent of the following expression 3 log(x + 1) 2

Copyright GATE Overflow. All rights reserved.

GATE Overflow
gate1998

April 2016

compiler-design

308 of 1876

postfix

Selected Answer

3x1 + log a2/


-- Happy Mittal ( 9253 points)

8 votes

2.107 Programming In C: GATE2005_61 top

gateoverflow.in/4066

Consider line number 3 of the following C-program.


int main() {
/*Line 1 */
int I, N;
/*Line 2 */
fro (I=0, I<N, I++); /*Line 3 */
}

Identify the compilers response about this line while creating the object-module:

A. No compilation error
B. Only a lexical error
C. Only syntactic errors
D. Both lexical and syntactic errors

gate2005

compiler-design

programming-in-c

normal

Selected Answer

C language allows only certain words in it- these are called tokens. If we input any invalid tokens it causes lexical error.
eg:
44a44
causes lexical error as in C as an alphabet cannot come in between digits.
Syntactic error is caused by bad combination of tokens. For example, we cannot have a constant on the left hand side of
an assignment statement, a for loop must have two expressions inside () separated by semi colon etc.
In the given question, line 3 won't cause lexical error or syntactic error. The statement will be treated as a function call
with three arguments. Function definition being absent will cause link time error, but the question asks only for compile
time errors. So, (a) must be the answer.
PS: Implicit function declaration was removed from C99 standard on wards. As per current standard we should not use a
function without declaration. Still, we cannot guarantee "compilation error"- just expect compiler warnings in C. In C++
this should produce compilation (semantic) error.
http://stackoverflow.com/questions/15570553/lexical-and-semantic-errors-in-c
17 votes

-- Arjun Suresh ( 124085 points)

2.108 Recursion: GATE2014-3_18 top


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.

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/2052

GATE Overflow

April 2016

309 of 1876

(A) 1 and 2 only


(B) 2 and 3 only
(C) 3 and 4 only
(D) 1 and 3 only

gate2014-3

compiler-design

recursion

normal

Selected Answer

It will be D.
option 2 is wrong because it is not necessary to have automatic garbage collection to implement recursion.
option 4 is wrong because it says that both are required to implement recursion, which is wrong. Either of them will
suffice.
-- Gate Keeda ( 16619 points)

7 votes

2.109 Register Allocation: GATE2010_37 top

gateoverflow.in/2338

The program below uses six temporary variables a, b, c, d, e, f.


a = 1
b = 10
c = 20
d = a + b
e = c + d
f = c + e
b = c + e
e = b + f
d = 5 + e
return d + f

Assuming that all operations take their operands from registers, what is the minimum number of registers needed to execute this program without spilling?


(A) 2
(B) 3
(C) 4
(D) 6


gate2010

compiler-design

target-code-generation

register-allocation

normal

Selected Answer

After making the interference graph it can be colored with 3 different colors. Therefore minimum number of color needed
to execute the program without spilling would be 3 (B).
6 votes

3 registers.
here,
d = a + b
e = c + (a+b)
f = c + (c+ (a+b))
b = c + (c+ (a+b) = f
e = b + (c+(c+(a+b)))
d = 5 + (b+(c+(c+(a+b))))
return d + f

first evaluate b using two registers and then store its value in f because f and b are equal.

Copyright GATE Overflow. All rights reserved.

-- suraj ( 3299 points)

GATE Overflow

April 2016

310 of 1876

now evaluate d with two registers. then return d+f


hence 3 registers.
-- jayendra ( 5797 points)

1 votes

2.110 Register Allocation: GATE1997_4.9 top

gateoverflow.in/2250

The expression (a b) c op
where op is one of +, * and (exponentiation) can be evaluated on a CPU with single register without storing the value
of (a * b) if
A. op is + or *
B. op is or *
C. op is or +
D. not possible to evaluate without storing
gate1997

compiler-design

target-code-generation

register-allocation

normal

A)

has higer precedence than {*,+,-,/}


So, if op = implies, we need to evaluate the right hand side of first and then do the lhs part, which would definately require us
but if its a '+' or '*' , we dont need to store the values evaluated, and on the go can do the operation directly on one register.


-- confused_luck ( 205 points)

0 votes

2.111 Register Allocation: GATE2011_36 top

gateoverflow.in/2138

Consider evaluating the following expression tree on a machine with load-store architecture in which memory can be
accessed only through load and store instructions. The variables a, b, c, d, and e are initially stored in memory. The binary
operators used in this expression tree can be evaluated by the machine only when operands are in registers. The instructions
produce result only in a register. If no intermediate results can be stored in memory, what is the minimum number of
registers needed to evaluate this expression?

(A) 2
(B) 9
(C) 5
(D) 3

gate2011

compiler-design

register-allocation

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

311 of 1876

R1<- -c, R2<- -d, R2<- -R1+R2, R1<- -e, R2<- -R1-R2
To calculate the rest of the expression we must load a and b into the registers but we need the content of R2 later. So we
must use another register. R1<- -a, R3<- -b, R1<- -R1-R3, R1<- -R1+R2
Ans D
-- Keith Kr ( 5467 points)

4 votes

answer - D
using dependency graph coloring algorithm
-- ankitrokdeonsns ( 7941 points)

2 votes

2.112 Runtime Environments: GATE1998_1.28 top

gateoverflow.in/1665

A linker reads four modules whose lengths are 200, 800, 600 and 500 words, respectively. If they are loaded in that order, what
are the relocation constants?
A. 0, 200, 500, 600
B. 0, 200, 1000, 1600
C. 200, 500, 600, 800
D. 200, 700, 1300, 2100

gate1998

compiler-design

runtime-environments

normal

Selected Answer

answer - B
first module loaded starting at address 0. Size is 200. hence it will occup first 200 address last address being 199. Second
module will be present from 200 and so on.
-- ankitrokdeonsns ( 7941 points)

5 votes

2.113 Runtime Environments: GATE1995_1.14 top

gateoverflow.in/2601

A linker is given object modules for a set of programs that were compiled separately. What information need to be included
in an object module?
A. Object code
B. Relocation bits
C. Names and locations of all external symbols defined in the object module
D. Absolute addresses of internal symbols

gate1995

compiler-design

runtime-environments

normal

Selected Answer

(c) is the answer. For linker to link external symbols (for example in C, to link an extern variable in one module to a global
variable in another module), it must know the location of all external symbols. In C external symbols includes all global
variables and function names.
(a) is trivially there is an object module. (b) must be there if we need to have relocation capability.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

312 of 1876

(d) is no way needed.


-- Arjun Suresh ( 124085 points)

8 votes

2.114 Runtime Environments: GATE1998_1.25 top

gateoverflow.in/1662

In a resident OS computer, which of the following systems must reside in the main memory under all situations?
A. Assembler
B. Linker
C. Loader
D. Compiler

gate1998

compiler-design

runtime-environments

normal

answer - C
-- ankitrokdeonsns ( 7941 points)

2 votes

2.115 Runtime Environments: GATE2001_1.17 top

gateoverflow.in/710

The process of assigning load addresses to the various parts of the program and adjusting the code and the date in the
program to reflect the assigned addresses is called
A. Assembly
B. parsing
C. Relocation
D. Symbol resolution
gate2001

compiler-design

runtime-environments

easy

Selected Answer

answer - C
-- ankitrokdeonsns ( 7941 points)

5 votes

2.116 Runtime Environments: GATE1993_7.7 top

gateoverflow.in/2295

A part of the system software which under all circumstances must reside in the main memory is:
a. text editor
b. assembler
c. linker
d. loader
e. none of the above

gate1993

compiler-design

runtime-environments

easy

Selected Answer

Answer: D
The loader is a program that loads the object program from the secondary memory into the main memory for execution of

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

313 of 1876

the program. The loader resides in main memory.


-- Rajarshi Sarkar ( 27781 points)

4 votes

2.117 Static Single Assignment: GATE 2016-1-19 top

gateoverflow.in/39675

Consider the following code segment.


x
y
x
y
y

=
=
=
=
=

u
x
y
t
x

*
+
*

t;
v;
w;
z;
y;

The minimum number of total variables required to convert the above code segment to static single assignment form is
__________.

gate2016-1

compiler-design

static-single-assignment

normal

numerical-answers

Selected Answer

I am getting 10. Static single assignment means temporary reg will be assigned only once.
6 votes

-- Shikhar Vashishth ( 3439 points)

I got 5.
-- Divya74 ( 109 points)

6 votes

ans. is 10
here every variable can be assigned with a value only once.
t1 = t2 - t3
t4 = t1 * t5
t6 = t4 + t7
t8 = t2 - t9
t10 = t6 - t8
-- Vaibhav Singh ( 421 points)

3 votes

I got 6. Plz comment


2 votes

-- Debasmita Bhoumik ( 213 points)

Static single assignment means assignment to register can be done one time only.
so, draw the GRAPH and count number of nodes which will give the number of register required.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

314 of 1876



-- Nishank Garg ( 21 points)

1 votes

2.118 Syntax Directed Translation: GATE 2016-1-46 top

gateoverflow.in/39700

Consider the following Syntax Directed Translation Scheme (SDTS), with non-terminals {S, A} and terminals {a, b}.
S aA
S a

{print 1}
{print 2}

A Sb

{print 3}

Using the above SDTS , the output printed by a bottom-up parser, for the input aab is:
A. 1 3 2
B. 2 2 3
C. 2 3 1
D. syntax error

gate2016-1

compiler-design

syntax-directed-translation

normal

Selected Answer

aab could be derived as follows by the bottom up parser:


S->aA prints 1
A->aSb prints 3
A->aab prints 2
Now since bottom up parser will work in reverse of right most derivation, so it will print in bottom up fashion i.e., 231
which is option C.
Note that this could also be visualized easily by drawing the derivation tree.

-- Monanshi Jain ( 5787 points)

14 votes

2.119 Syntax Directed Translation: GATE1994_23 top


Suppose we have a computer with single register and only three instructions given below:
LOAD addren

STORE addren

; load register
; from addren
; store register
; at addren

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/2519

GATE Overflow

April 2016

ADD addren


315 of 1876

; add register to
; contents of addren
; and place the result
; in the register


Consider the following grammar:
A id:= E

E E+TT

T (E) id


Write a syntax directed translation to generate code using this grammar for the computer described above.

gate1994

compiler-design

grammar

syntax-directed-translation

normal

2.120 Syntax Directed Translation: GATE1996_20 top

gateoverflow.in/2772

Consider the syntax-directed translation schema (SDTS) shown below:


E
E
E
E

E + E {print +}
E E {print .}
id {print id.name}
(E)

An LR-parser executes the actions associated with the productions immediately after a reduction by the corresponding
production. Draw the parse tree and write the translation for the sentence.
(a + b) (c + d), using SDTS given above.

gate1996

compiler-design

syntax-directed-translation

normal

ab+cd+. its a basic SDT, used to find the postfix expression.


5 votes

ab+cd+.

Copyright GATE Overflow. All rights reserved.

-- abhishek1317 ( 259 points)

GATE Overflow

April 2016

316 of 1876

-- jayendra ( 5797 points)

4 votes

2.121 Syntax Directed Translation: GATE1995_2.10 top

gateoverflow.in/2622

A shift reduce parser carries out the actions specified within braces immediately after reducing with the corresponding rule of
grammar
S xxW{print"1"}
S y{print"2"}
W Sz{print"3"}
What is the translation of xxxxyzz using the syntax directed translation scheme described by the above rules?
A. 23131
B. 11233
C. 11231
D. 33211

gate1995

compiler-design

grammar

syntax-directed-translation

normal

Selected Answer

A.
Making a tree and performing post order traversal will yield answer as A.
S-->x x W (Pf'1')
W-->S z (Pf'3')
S-->x x W (Pf'1')
W-->S z (Pf'3')
S-->y (Pf'2').
-- Gate Keeda ( 16619 points)

11 votes

2.122 Syntax Directed Translation: GATE2003_18 top


In a bottom-up evaluation of a syntax directed definition, inherited attributes can

A. always be evaluated
B. be evaluated only if the definition is L-attributed
C. be evaluated only if the definition has synthesized attributes
D. never be evaluated


gate2003

compiler-design

syntax-directed-translation

Ans:C
lets see how ,consider following SDD:
A->BC B.i =A.i
B->b B.s=b.val

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/908

GATE Overflow

April 2016

317 of 1876

C->c C.s=c.val
if u draw parse tree
A
B C
b c
now ur traversing bottom up
first you 'll evaluate B.s then you want to evaluate B.i but as we can see as i is an inherited attribute and it is dependent
on A.i , but we have'nt evaluated A.i yet coz we are doing a bottom up traversal and we havent seen A yet . so it cannot
be evaluated due to Inherited attribute i.

now if A=BC A.s=B.s+C.s
B->b B.s=b.val
C->c C.s=c.val
see that
A
B C
b c
you 'll traverse bottom up ,first eval B.s=b then C.s=c
then when you are at A ,you have already evaluated all the attributes on which A.s is dependent..so Only in this case
where SDD has Synthesized attributes ,then only Bottom up Evaluation can be used.
for Inherited attributes we will need a depth first evaluation.
2 votes

-- Anurag Semwal ( 4775 points)

Ans D
Why ?
A) inherited attributes can have cyclic dependencis. Due to which we can not be sure whether they can be evaluated in
First Place.
So A is wrong.
B) This is wrong because even defination is is L-attributed, we need to go top down, left to right. We can not do standard
bottom up Traversal.
example :T' -> *FT1' | T1'.inh = T'.inh * F.val -> This move is allowed in L attributed, which can not be computed using bottom up
traversal. We need to go from left to right, top down. So B is out of question.
reference :- https://en.wikipedia.org/wiki/L-attributed_grammar
L-attributed grammars are a special type of attribute grammars. They allow the attributes to be evaluated in one
depth-first left-to-right traversal of the abstract syntax tree. As a result, attribute evaluation in L-attributed grammars can
be incorporated conveniently in top-down parsing.
A syntax-directed definition is L-attributed if each inherited attribute of Xj on the right side of
A X1 X2 Xn
depends only on
1.the attributes of the symbols X1, X2, , Xj-1
2.the inherited attributes of A // This is why B is false.

C) This is wrong because it says " definition has synthesized attributes". So along with Synthesized attributes, I can even

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

318 of 1876

have cycles. Which makes this wrong..


So answer is One and only D. Never !
-- Akash ( 26265 points)

1 votes

2.123 Syntax Directed Translation: GATE2000_19 top

gateoverflow.in/690

Consider the syntax directed translation scheme (SDTS) given in the following. Assume attribute evaluation with bottom-up parsing, i.e.,
attributes are evaluated immediately after a reduction.
E E1 * T {E.val = E1 .val * T.val}
E T {E.val = T.val}
T F - T1 {T.val = F.val - T1 .val}
T F {T.val = F.val}
F 2 {F.val = 2}
F 4 {F.val = 4}

a. Using this SDTS, construct a parse tree for the expression 4 - 2 - 4 * 2 and also compute its E.val.
b. It is required to compute the total number of reductions performed to parse a given input. Using synthesized attributes only, modify the
SDTS given, without changing the grammar, to find E.red, the number of reductions performed while reducing an input to E.

gate2000

compiler-design

syntax-directed-translation

normal

Selected Answer

A. Given Expression is 4 - 2 - 4 * 2 , which can be rewritten as ((4 - (2 - 4))* 2) which is equal to 12.
-- Aditya Gaurav ( 1831 points)

4 votes

2.124 Syntax Directed Translation: GATE1997_23 top

gateoverflow.in/2283

The language L, defined by the following grammar, allows use of real or integer data in expressions and assignment
statements.

gate1997

compiler-design

syntax-directed-translation

normal

2.125 Syntax Directed Translation: GATE1998_23 top


Let the attribute val give the value of a binary number generated by S in the following grammar:
S L. L L

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/1738

GATE Overflow

April 2016

319 of 1876

L LB B
B01
For example, an input 101.101 gives S. val = 5.625
Construct a syntax directed translation scheme using only synthesized attributes, to determine S. val.
gate1998

compiler-design

syntax-directed-translation

normal

Selected Answer

S-- > L.L { S.dv = L 1.dv + L 2.dv/2L2.nb }


| L { S.dv = L.dv }
L-- > LB { L.dv = 2 * L 1.dv + B.dv
L.nb = L 1.nb + B.nb }}
| B { L.dv = B.dv
L.nb = B.nb }
B-- > 0 { B.dv = 0
B.nb = 1 }
| 1 { B.dv = 1
B.nb = 1 }
here dv = decimal value
nb = number of bits.


-- Gate Keeda ( 16619 points)

3 votes

2.126 Target Code Generation: GATE2003_59 top

gateoverflow.in/947

Consider the syntax directed definition shown below.


S id := E
E E1 + E2

{gen(id.place = E.place;);}

gen(t = E1 .place + E2 place;);


E id

E.place = t;}
{E.place = id.place;}

{t = newtemp();

Here, gen is a function that generates the output code, and newtemp is a function that returns the name of a new temporary
variable on every call. Assume that ti's are the temporary variable names generated by newtemp. For the statement X : = Y
+ Z, the 3-address code sequence generated by this definition is
A. X = Y + Z
B. t1 = Y + Z; X = t1
C. t1 = Y; t2 = t1 + Z; X = t2
D. t1 = Y; t2 = Z; t3 = t1 + t2 ; X = t3


gate2003

compiler-design

target-code-generation

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

320 of 1876

answer - B
-- ankitrokdeonsns ( 7941 points)

6 votes

x=y+z
three address code

operand op1 op2 result
+ y z t1
= t1 x
t1=y+z
x=t1
so ans is b
-- Pooja ( 22745 points)

1 votes

2.127 Target Code Generation: GATE2004_10 top

gateoverflow.in/4069

Consider the grammar rule E E1 E2 for arithmetic expressions. The code generated is targeted to a CPU having a single user register.
The subtraction operation requires the first operand to be in the register. If E1 and E2 do not have any common sub expression, in order to get
the shortest possible code
(A) E1 should be evaluated first
(B) E2 should be evaluated first
(C) Evaluation of E1 and E2 should necessarily be interleaved
(D) Order of evaluation of E1 and E2 is of no consequence

gate2004

compiler-design

target-code-generation

normal

Selected Answer

E2 should be evaluated first


After evaluating E2 rst and then E1, we will have E1 in the register and thus we can simply do SUB operation with E2 which will be in
memory (as we have only a single register). If we do E1 rst and then E2, we must move E2 to memory and E1 back to register before doing
SUB, which will increase the code size.
-- Arjun Suresh ( 124085 points)

11 votes

2.128 GATE2009_17 top

gateoverflow.in/1309

Match all items in Group 1 with the correct options from those given in Group 2.
Group 1

Group 2

P. Regular Expression
Q. Pushdown automata
R. Dataflow analysis

1. Syntax analysis
2. Code generation
3. Lexical analysis

S. Register allocation

4.

Copyright GATE Overflow. All rights reserved.

Code optimization

GATE Overflow

April 2016

321 of 1876

A. P-4, Q-1, R-2, S-3


B. P-3, Q-1, R-4, S-2
C. P-3, Q-4, R-1, S-2
D. P-2, Q-1, R-4, S-3

gate2009

compiler-design

easy

Selected Answer

Regular expressions are used in lexical analysis.


Pushdown automata is related to context free grammar which is related to syntax analysis.
Dataflow analysis is done in code optimization.
Register allocation is done in code generation.
Ans B
-- Keith Kr ( 5467 points)

5 votes

2.129 GATE2014-3_11 top

gateoverflow.in/2045

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

gate2014-3

compiler-design

numerical-answers

normal

Selected Answer

P(X) = x5 + 4x3 + 6x + 5
=x(x4 + 4x2 + 6) +5
=x( x ( x3 + 4x) + 6) + 5
=x( x ( x (x2 + 4)) + 6) + 5
=x( x ( x (x(x) + 4)) + 6) + 5
mul = pair of brackets 4
add = num of signs 3
total 7
8 votes

Copyright GATE Overflow. All rights reserved.

-- jayendra ( 5797 points)

GATE Overflow

April 2016

322 of 1876

In the above 8 steps of evaluation, the total number of arithmetic operations required are 7 [4
Multiplications, 3 Additions]
So answer is 7 arithmetic operations.
-- Gate Keeda ( 16619 points)

5 votes

2.130 GATE1991_03,ix top

gateoverflow.in/519

Choose the correct alternatives (more than one may be correct ) and write the corresponding letters only
A link editor is a program that:
(a). matches the parameters of the macro-definition with locations of the parameters of the macro call
(b). matches external names of one program with their location in other programs
(c). matches the parameters of subroutine definition with the location of parameters of subroutine call.
(d). acts as a link between text editor and the user
(e). acts as a link between compiler and the user program
gate1991

compiler-design

normal

Selected Answer

Link editor or (linker ) performs


1. external symbol resolution
2. relocation.

ANS: B

Matches external names of one program with their location in other programs
1 votes

2.131 GATE1997_1.7 top


Which of the following is essential for converting an infix expression to the postfix form efficiently?
a. An operator stack

Copyright GATE Overflow. All rights reserved.

-- pramod ( 2071 points)

gateoverflow.in/2223

GATE Overflow

April 2016

323 of 1876

b. An operand stack
c. An operand stack and an operator stack
d. A parse tree
gate1997

compiler-design

normal

Selected Answer

A.
we use operator stack (only operators are pushed as +, *, (, ), / ) for converting infix to postfix. And we use operand
stack( operands such as 5,4,17 etc) for postfix evaluation.
-- Gate Keeda ( 16619 points)

10 votes

2.132 GATE2014-2_18 top

gateoverflow.in/1975

Which one of the following is NOT performed during compilation?

(A) Dynamic memory allocation


(B) Type checking

(C) Symbol table management


(D) Inline expansion

gate2014-2

compiler-design

easy

Selected Answer

Dynamic means- at runtime. Dynamic memory allocation happens during the execution time and hence (A) is the answer.
-- Arjun Suresh ( 124085 points)

6 votes

2.133 GATE2014-2_39 top

gateoverflow.in/1999

Consider the expression tree shown. Each leaf represents a numerical value, which can either be 0 or 1. Over all possible choices of the values at the leaves, the
maximum possible value of the expression represented by the tree is ___.

gate2014-2

compiler-design

normal

Selected Answer

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

324 of 1876

ans is 6
at left leafs
+ -----> (1,1)=2 intermediate + -------> 2-(-1)=3
- -------->(0,1)=-1
at right leafs
- minus ------->(1,0)=1 intermediate + ------> 1+2=3
+ ------------->(1,1)=2

at root + -------> 3+3=6
-- GANNA ( 149 points)

4 votes

2.134 GATE 2016-2-19 top

gateoverflow.in/39548

Match the following:


(P) Lexical analysis (i) Leftmost derivation
(Q) Top down parsing (ii) Type checking
(R) Semantic analysis (iii) Regular expressions
(S) Runtime environment (iv) Activation records
A. P
B. P
C. P
D. P

i, Q ii, R iv, S iii


iii, Q i, R ii, S iv
ii, Q iii, R i, S iv
iv, Q i, R ii, S iii



gate2016-2

compiler-design

easy

Selected Answer

Option B.
Lexical Analysis phase uses regular expressions.
LMD is involved in top down parsing.
Type checking is done in semantic analysis phase.
Activation records are related to Run Time Environments
8 votes

-- Sharathkumar Anbu ( 657 points)

2.135 GATE1994_18 top

gateoverflow.in/2514

State whether the following statements are True or False with reasons for your answer
a. A subroutine cannot always be used to replace a macro in an assembly language program.
b. A symbol declared as external in an assembly language program is assigned an address outside the program by the
assembler itself.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

gate1994

April 2016

compiler-design

325 of 1876

normal

A) This is true. We can not replace macro entirely using subroutine. Ex -> Macro constant used for renaming.
B) This is false. This is job of Linker.
-- Akash ( 26265 points)

1 votes

2.136 GATE1996_1.17 top

gateoverflow.in/2721

The pass numbers for each of the following activities


i. object code generation
ii. literals added to literal table
iii. listing printed
iv. address resolution of local symbols that occur in a two pass assembler
respectively are

A. 1, 2, 1, 2
B. 2, 1, 2, 1
C. 2, 1, 1, 2
D. 1, 2, 2, 2

gate1996

compiler-design

normal

Ans should be (B)


the functions performed in pass 1 and pass 2 in 2 pass assembler are
Pass 1
1. Assign addresses to all statements in the program.
2. Save the values assigned to all labels for use in pass 2
3. Perform some processing of assembler directives.
Pass 2
1. Assemble instructions.
2. Generate data values defined by BYTE, WORD etc.
3. Perform processing of assembler directives not done during pass 1.
4. Write the program and the assembling listing
2 votes

i think ans should be B.


literals added to literal table is done in lexical analysis phase, so possible in 1 pass.
and a is back end activity so can not in 1 pass.
d is back end activity but it is in 2 pass assembler. so only 1 pass required.
hence B

Copyright GATE Overflow. All rights reserved.

-- sonam vyas ( 6439 points)

GATE Overflow

April 2016

326 of 1876
-- jayendra ( 5797 points)

2 votes

2.137 GATE2015-2_14 top

gateoverflow.in/8084

In the context of abstract-syntax-tree (AST) and control-flow-graph (CFG), which one of the following is TRUE?

A. In both AST and CFG, let node N2 be the successor of node N1 . In the input program, the code corresponding to N2 is
present after the code cprresponding to N1
B. For any input program, neither AST nor CFG will contain a cycle
C. The maximum number of successors of a node in an AST and a CFG depends on the input program
D. Each node in AST and CFG corresponds to at most one statement in the input program
gate2015-2

compiler-design

easy

Selected Answer

Option (C) is Correct


(A) is false , In CFG , code of N2 may be present before N1 when there is a loop or Goto.
(B) is false , CFG contains cycle when input program has loop.
(C) is true ,successors in AST and CFG depend on Input program.
(D) is false, In CFG a single node may belong to a block of statements.

-- Himanshu Agarwal ( 8861 points)

3 votes

answer is c, but i'm not so sure


-- naresh1845 ( 1135 points)

2 votes

2.138 GATE1994_17 top

gateoverflow.in/2513

State whether the following statements are True or False with reasons for your answer:
a. Coroutine is just another name for a subroutine.
b. A two pass assembler uses its machine opcode table in the first pass of assembly.

gate1994

compiler-design

normal

a) False
b) True
1 votes

2.139 GATEFORUM Section Test 1 (que no. 14th ) top

Copyright GATE Overflow. All rights reserved.

-- Neha Sisodiya ( 51 points)

gateoverflow.in/36739

GATE Overflow

April 2016

2.140 GATE2004_9 top

327 of 1876

gateoverflow.in/1006

Consider a program P that consists of two source modules M1 and M2 contained in two different files. If M1 contains a
reference to a function defined in M2 the reference will be resolved at

A. Edit time
B. Compile time
C. Link time
D. Load time

gate2004

compiler-design

easy

Selected Answer

answer - C. Each module is compiled separately and then linked together to make the executable. The below commands
shows how to do this for two modules c1.c and c2.c using gcc.
gcc -c c1.c -o c1.o
gcc -c c2.c -o c2.o
gcc c1.o c2.o -o C.exe


-- ankitrokdeonsns ( 7941 points)

5 votes

2.141 GATE2015-2_19 top


Match the following:
P. Lexical analysis

1. Graph coloring

Q. Parsing

2. DFA minimization

R. Register allocation

3. Post-order traversal

S. Express evaluation

4. Production tree


A. P-2, Q-3, R-1, S-4
B. P-2, Q-1, R-4, S-3
C. P-2, Q-4, R-1, S-3
D. P-2, Q-3, R-4, S-1

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/8098

GATE Overflow

April 2016

gate2015-2

compiler-design

328 of 1876

normal

Selected Answer

Answer: C
-- Rajarshi Sarkar ( 27781 points)

9 votes

2.142 GATE1997_1.8 top

gateoverflow.in/2224

A language L allows declaration of arrays whose sizes are not known during compilation. It is required to make efficient use
of memory. Which one of the following is true?
a. A compiler using static memory allocation can be written for L
b. A compiler cannot be written for L; an interpreter must be used
c. A compiler using dynamic memory allocation can be written for L
d. None of the above
gate1997

compiler-design

easy

Selected Answer

C.
Using dynamic memory allocation, memory will be allocated to array at runtime.
7 votes

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

GATE Overflow

April 2016

329 of 1876

CO & Architecture top

3.1 Addressing Modes: GATE2006-IT_39 top

gateoverflow.in/3578

Which of the following statements about relative addressing mode is FALSE?



A)
B)
C)
D)

It enables reduced instruction size


It allows indexing of array elements with same instruction
It enables easy relocation of data
It enables faster address calculations than absolute addressing

gate2006-it

co&architecture

addressing-modes

normal

Selected Answer

(D) is false. Relative addressing cannot be faster than absolute addressing as absolute address must be calculated from
relative address. With specialized hardware unit, this can perform equally as good as absolute addressing but not faster.
(A) is true as instead of absolute address we can use a much smaller relative address in instructions which results in
smaller instruction size.
(B) By using the base address of array we can index array elements using relative addressing.
(C) is true as we only need to change the base address in case of relocation- instructions remain the same.
-- Arjun Suresh ( 124085 points)

13 votes

3.2 Addressing Modes: GATE2006-IT_40 top

gateoverflow.in/3581

The memory locations 1000, 1001 and 1020 have data values 18, 1 and 16 respectively before the following program is
executed.
MOVI
Rs, 1
; Move immediate
LOAD Rd, 1000(Rs) ; Load from memory
ADDI
Rd, 1000
; Add immediate
STOREI 0(Rd), 20
; Store immediate
Which of the statements below is TRUE after the program is executed ?

A)
B)
C)
D)
gate2006-it

Memory location 1000 has value 20


Memory location 1020 has value 20
Memory location 1021 has value 20
Memory location 1001 has value 20

co&architecture

addressing-modes

normal

Selected Answer

D) Memory location 1001 has value 20.

Rs<-1
Rd<-1
Rd<-1001
store in address 1001 <- 20
10 votes

3.3 Addressing Modes: GATE1999_2.23 top


Copyright GATE Overflow. All rights reserved.

-- Abhinav Rana ( 489 points)

gateoverflow.in/1500

GATE Overflow

April 2016

330 of 1876

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

gate1999

co&architecture

addressing-modes

normal

Selected Answer

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.
-- Arjun Suresh ( 124085 points)

7 votes

pointer require indirect addressing mode.Array and record need index addressing modes.
int foo(int a) {
int b = 1 + a;
int c = bar(b);
return c;
}
int bar(int x) {
//do something
}
When

bar
is done executing, it stores its return value in a register which

foo
knows to check for the return value.
So register addressing mode is required.
Hence the answer is A,B,C,D

-- debdas ( 79 points)

1 votes

3.4 Addressing Modes: GATE2001_2.9 top


Which is the most appropriate match for the items in the first column with the items in the second column
X. Indirect Addressing
Y. Indexed addressing

I. Array implementation
II. Writing relocatable code

Z. Base Register Addressing III. Passing array as parameter

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/727

GATE Overflow

April 2016

331 of 1876


(A) (X, III) (Y, I) (Z, II)
(B) (X, II) (Y, III) (Z, I)
(C) (X, III) (Y, II) (Z, I)
(D) (X, I) (Y, III) (Z, II)

gate2001

co&architecture

addressing-modes

normal

Selected Answer

(A) is the answer.


Array implementation can use Indexed addressing
While passing array as parameter we can make use of a pointer (as in C) and hence can use Indirect addressing
Base Register addressing can be used to write relocatable code by changing the content of Base Register.
-- Arjun Suresh ( 124085 points)

10 votes

3.5 Addressing Modes: GATE1996_1.16 top

gateoverflow.in/2720

Relative mode of addressing is most relevant to writing


A. coroutines
B. position independent code
C. shareable code
D. interrupt handlers

gate1996

co&architecture

addressing-modes

easy

Selected Answer

Answer: B
Relative mode addressing is most relevant to writing a position-independent code.
Ref: http://en.wikipedia.org/wiki/Addressing_mode#PC-relative
4 votes

3.6 Addressing Modes: GATE1993_10 top

-- Rajarshi Sarkar ( 27781 points)

gateoverflow.in/2307

The instruction format of a CPU is:


OP CODE MODE RegR
_____one memory word___

Mode and RegR together specify the operand. RegR specifies a CPU register and Mode specifies an addressing mode. In
particular, Mode = 2 specifies that the register RegR contains the address of the operand, after fetching the operand, the
contents of R RegR are incremented by 1'.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

332 of 1876

An instruction at memory location 2000 specifies Mode = 2 and the RegR refers to program counter (PC).
a. What is the address of the operand?
b. Assuming that is a non-jump instruction, what are the contents of PC after the execution of this instruction?
gate1993

co&architecture

addressing-modes

normal

Selected Answer

a) Address of the operand = content of PC = 2001 as PC holds the address of the next instruction to be executed and
instruction size is 1 word as given in the diagram.
b) After execution PC will be automatically incremented by 1 and also one extra increment will be done by operand fetch.
So, PC = 2003. If we assume operand fetch is not done, it should be 2002.
-- Arjun Suresh ( 124085 points)

4 votes

3.7 Addressing Modes: GATE2011_21 top

gateoverflow.in/2123

Consider a hypothetical processor with an instruction of type LW R1 , 20(R2) , which during execution reads a 32-bit word from memory and stores it in a 32-bit
register R1. The eective address of the memory location is obtained by the addition of a constant 20 and the contents of register R2. Which of the following best
reflects the addressing mode implemented by this instruction for the operand in memory?
(A) Immediate addressing
(B) Register addressing
(C) Register Indirect Scaled Addressing
(D) Base Indexed Addressing

gate2011

co&architecture

addressing-modes

easy

Selected Answer

Answer: D
Base Index Addressing, as the content of register R2 will serve as the index and 20 will be the Base address.
-- Rajarshi Sarkar ( 27781 points)

5 votes

option d
-- anirban4 ( 27 points)

1 votes

3.8 Addressing Modes: GATE2002_1.24 top


In the absolute addressing mode

A. the operand is inside the instruction
B. the address of the operand in inside the instruction
C. the register containing the address of the operand is specified inside the instruction
D. the location of the operand is implicit
gate2002

co&architecture

addressing-modes

Copyright GATE Overflow. All rights reserved.

easy

gateoverflow.in/829

GATE Overflow

April 2016

333 of 1876

Selected Answer

(b) is the answer. Absolute addressing mode means address of operand is given in the instruction.
(a) operand is inside the instruction -> immediate addressing
(c) -> register addressing
(d) -> implicit addressing
-- gatecse ( 9515 points)

10 votes

3.9 Addressing Modes: GATE1998_1.19 top

gateoverflow.in/1656

Which of the following addressing modes permits relocation without any change whatsoever in the code?
A. Indirect addressing
B. Indexed addressing
C. Base register addressing
D. PC relative addressing

gate1998

co&architecture

addressing-modes

easy

PC relative addressing is the best option. For Base register addressing, we have to change the address in the base register
while in PC relative there is absolutely no change in code needed.
-- Arjun Suresh ( 124085 points)

0 votes

3.10 Addressing Modes: GATE2005_66 top

gateoverflow.in/1389

Match each of the high level language statements given on the left hand side with the most natural addressing mode from
those listed on the right hand side.
(1) A[I] = B[J]
(2) while (*A++);
(3) int temp = *x

(a) Indirect addressing


(b) Indexed addressing
(C) Auto increment

A. (1, c), (2, b) (3, a)


B. (1, c), (2, c) (3, b)
C. (1, b), (2, c) (3, a)
D. (1, a), (2, b) (3, c)


gate2005

co&architecture

addressing-modes

easy

Selected Answer

(c) is the answer.


A[i] = B[j]; Indexed addressing
while(*A++); Auto increment
temp = *x; Indirect addressing
6 votes

3.11 Addressing Modes: GATE2005_65 top

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/1388

GATE Overflow

April 2016

334 of 1876

Consider a three word machine instruction


ADD A[R0], @B
The first operand (destination) A[R0] uses indexed addressing mode with R0 as the index register. The second operand
(source) @B uses indirect addressing mode. A and B are memory addresses residing at the second and third words,
respectively. The first word of the instruction specifies the opcode, the index register designation and the source and
destination addressing modes. During execution of ADD instruction, the two operands are added and stored in the
destination (first operand).
The number of memory cycles needed during the execution cycle of the instruction is:

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

gate2005

co&architecture

addressing-modes

normal

Selected Answer

1 memory read - get first operand from memory address A+R0 (A is given as part of instruction)
1 memory read - get address of second operand (since second uses indirect addressing)
1 memory read - to get second operand from the address given by the previous memory read
1 memory write - to store to first operand (which is the destination)
So, totally 4 memory cycles once the instruction is fetched.
The second and third words of the instruction are loaded as part of the Instruction fetch and not during the execute stage:
Ref: http://www.cs.iit.edu/~cs561/cs350/fetch/fetch.html
-- Arjun Suresh ( 124085 points)

16 votes

3.12 Addressing Modes: GATE2008_33 top

gateoverflow.in/444

Which of the following is/are true of the auto-increment addressing mode?


I. It is useful in creating self-relocating code
II. If it is included in an Instruction Set Architecture, then an additional ALU is required for effective address calculation
III. The amount of increment depends on the size of the data item accessed

A. I only
B. II only
C. III only
D. II and III only

gate2008

addressing-modes

co&architecture

normal

Selected Answer

In auto increment addressing mode, the base address is incremented after operand fetch. This is useful in fetching
elements from an array. But this has no effect in self-relocating code (where code can be loaded to any address) as this
works on the basis of an initial base address.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

335 of 1876

An additional ALU is desirable for better execution especially with pipelining, but never a necessity.
Amount of increment depends on the size of the data item accessed as there is no need to fetch a part of a data.
So, answer must be C only.
-- Arjun Suresh ( 124085 points)

9 votes

Correct answer (C)


Auto increment mode is used for incrementing and depends on size of data.
-- Keith Kr ( 5467 points)

3 votes

3.13 Addressing Modes: GATE2004_20 top

gateoverflow.in/1017

Which of the following addressing modes are suitable for program relocation at run time?
I. Absolute addressing
II. Based addressing
III. Relative addressing
IV. Indirect addressing

A. (I) and (IV)
B. (I) and (II)
C. (II) and (III)
D. (I), (II) and (IV)


gate2004

co&architecture

addressing-modes

easy

Selected Answer

Answer: C
A displacement type addressing should be preferred. So, I is not the answer.
Indirect Addressing leads to extra memory reference which is not preferable at run time. So, IV is not the answer.
-- Rajarshi Sarkar ( 27781 points)

4 votes

It should be a displacement type of addressing mode so option c.


-- anshu ( 2155 points)

2 votes

3.14 Cache: GATE2016-2-32 top

gateoverflow.in/39622

The width of the physical address on a machine is 40 bits. The width of the tag field in a 512 KB 8-way set associative cache is
________ bits.
gate2016-2

computer-organization

Selected Answer

Copyright GATE Overflow. All rights reserved.

cache

normal

numerical-answers

GATE Overflow

April 2016

336 of 1876

Physical Address = 40
=> Tag + Set + Block Offset = 40
=> T + S + B = 40 ----------- (1)
We have , Cache Size = number of sets * blocks per set * Block size
=> 512 KB = number of sets * 8 * Block size
=> number of sets * Block size = 512/8 KB = 64 KB
=> S + B = 16 ---------(2)

from (1) & (2)


T = 24 bits (Ans)
-- Himanshu Agarwal ( 8861 points)

9 votes

In question block size has not been given,so we can assume block size 2 x Byte.
Number of Blocks:- 512 X 210 2 x =219-x
Number of sets:- 2 19-x 8 =216-x
So number of bits for sets=16-x
Let number of bits for Tag=T
And we have already assumed block size 2 x Byte,therefore number of bits for block size is x
And finally, T + (16-x) + x = 40
T+16 = 40
T = 24
-- ajit ( 1369 points)

1 votes

24 bits
-- Ashish Deshmukh ( 1229 points)

1 votes

3.15 Cache Memory: GATE2014-2_9 top

gateoverflow.in/1963

A 4-way set-associative cache memory unit with a capacity of 16 KB is built using a block size of 8 words. The word length is
32 bits. The size of the physical address space is 4 GB. The number of bits for the TAG field is ____
gate2014-2

co&architecture

cache-memory

numerical-answers

normal

Selected Answer

Number of sets = cache size / sizeof a set


Size of a set = blocksize * no. of blocks in a set
= 8 words * 4 (4-way set-associative)
= 8*4*4 (since a word is 32 bits = 4 bytes)
= 128 bytes.
So, number of sets = 16 KB / (128 B) = 128

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

337 of 1876

Now, we can divide the physical address space equally between these 128 sets. So, the number of bytes each set can
access
= 4 GB / 128
= 32 MB
= 32/4 = 8 M words = 1 M blocks. (220 blocks)
So, we need 20 tag bits to identify these 220 blocks.
-- Arjun Suresh ( 124085 points)

10 votes

3.16 Cache Memory: GATE2014-3_44 top

gateoverflow.in/2078

The memory access time is 1 nanosecond for a read operation with a hit in cache, 5 nanoseconds for a read operation with a miss in cache, 2 nanoseconds for a
write operation with a hit in cache and 10 nanoseconds for a write operation with a miss in cache. Execution of a sequence of instructions involves 100 instruction
fetch operations, 60 memory operand read operations and 40 memory operand write operations. The cache hit-ratio is 0.9. The average memory access time (in
nanoseconds) in executing the sequence of instructions is ______.

gate2014-3

co&architecture

cache-memory

numerical-answers

normal

Selected Answer

Fetch is also a memory read operation.


160 (0.91 +0.15 ) +40(0.92 +0.110)
200

Avg access time =

160 1.4+402.8

200

336

= 200 = 1.68
-- aravind90 ( 599 points)

9 votes

3.17 Cache Memory: GATE2011_43 top

gateoverflow.in/2145

An 8KB direct-mapped write-back cache is organized as multiple blocks, each size of 32-bytes. The processor generates 32bit addresses. The cache controller contains the tag information for each cache block comprising of the following.
1 valid bit
1 modified bit
As many bits as the minimum needed to identify the memory block mapped in the cache.
What is the total size of memory needed at the cache controller to store meta-data (tags) for the cache?
(A) 4864 bits
(B) 6144 bits
(C) 6656 bits
(D) 5376 bits
gate2011

co&architecture

cache-memory

normal

Selected Answer

Number of cache blocks = cache size / size of a block


=8 KB/32 B
=256
So, we need 8 bits for indexing the 256 blocks of the cache. And since a block is 32 bytes we need 5 WORD bits to
address each byte. So, out of the remaining 19 bits (32 - 8 - 5) should be tag bits.
So, a tag entry size = 19 + 1(valid bit) + 1(modified bit) = 21 bits.
Total size of metadata = 21 * Number of cache blocks
= 21 * 256
= 5376 bits

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

338 of 1876
-- Arjun Suresh ( 124085 points)

5 votes

3.18 Cache Memory: GATE2007_10 top

gateoverflow.in/1208

Consider a 4-way set associative cache consisting of 128 lines with a line size of 64 words. The CPU generates a 20-bit
address of a word in main memory. The number of bits in the TAG, LINE and WORD fields are respectively:
A. 9, 6, 5
B. 7, 7, 6
C. 7, 5, 8
D. 9, 5, 6

gate2007

co&architecture

cache-memory

normal

Selected Answer

Number of sets = cache size/(size of a block * No. of blocks in a set)


= 128 * 64 / (64 * 4) (4 way set associative means 4 blocks in a set)
= 32.
So, number of index (LINE) bits = 5 and number of WORD bits = 6 size cache block (line) size is 64. So, number of TAG
bits = 20 - 6 - 5 = 9.
Answer is (D) choice
-- Arjun Suresh ( 124085 points)

3 votes

3.19 Cache Memory: GATE2007-80 top

gateoverflow.in/1273

Consider a machine with a byte addressable main memory of 2 16 bytes. Assume that a direct mapped data cache consisting
of 32 lines of 64 bytes each is used in the system. A 50 x 50 two-dimensional array of bytes is stored in the main memory
starting from memory location 1100H. Assume that the data cache is initially empty. The complete array is accessed twice.
Assume that the contents of the data cache do not change in between the two accesses.
How many data misses will occur in total?
A. 48
B. 50
C. 56
D. 59
gate2007

co&architecture

cache-memory

normal

Selected Answer

bits used to represent the address = log2 216 = 16


each cache line size = 64 bytes; means offset requires 6 bits
total number of lines in cache = 32; means line# requires 5 bits
so, tag bits = 16 6 5 = 5
we have a 2D array each of its element is of size = 1 Byte;
total size of this array = 50 50 1Byte = 2500Bytes
2500B

so, total number of lines it will require to get contain in cache = 64B = 39.0625 40

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

339 of 1876

starting address of array = 1100H = 00010 00100 000000


the group of bits in middle represents Cache Line number  array starts from cache line number 4,
we require 40 cache lines to hold all array elements, but we have only 32 cache lines
Lets group/partition our 2500 array elements in those 40 array lines, we call this first array line as A0 which will have 64 of
its elements. this line(group of 64 elements) of array will be mapped to cache line number 4 as found by analysis of
starting address of array above.
This all means that among those 40 array lines some array lines will be mapped to same cache line, coz there are just 32
cache lines but 40 of array lines.
this is how mapping is :
0

A28

A29

A30

A31

A0

A32

A1

A33

A2

A34

A3

A35

A4

A36

A5

A37

10

A6

A38

11

A7

A39

12

A8

30

A26

31

A27

so, if we access complete array twice we get = 32 + 8 + 8 + 8 = 56 miss


coz only 8 lines from cache line number 4 to 11 are miss operation, rest are Hits(not counted) or Compulsory misses(first
32).
Hence, Q.80 answer = option C

18 votes

-- Amar Vashishth ( 17735 points)

216 = 64 KB main memory is mapped to 32 lines of 64 bytes. So, number of offset bits = 6 (to identify a byte in a line) and
number of indexing bits = 5 (to identify the line).
Size of array = 50* 50 = 2500 B. If array is stored in row-major order (first row, second-row..), and if elements are also
accessed in row-major order (or stored and accessed in column-major order), for the first 64 accesses, there will be only 1
cache miss, and for 2500 accesses, there will be 2500/64 = 40 cache misses during the first iteration.
We have 5 index bits and 6 offset bits. So, for 2 11 (5 + 6 = 11) continuous memory addresses there wont be any cache
conflicts as the least significant bits are offset bits followed by index bits.
So, number of array elements that can be accessed without cache conflict = 2048 (as element size is a byte). The next
452 elements conflict with the first 452 elements. This means 452/64 = 8 cache blocks are replaced. (We used ceil, as
even if one element from a new block is accessed, the whole block must be fetched).
So, during second iteration we incur misses for the first 8 cache blocks as well as for the last 8 cache blocks. So, total
data cache misses across 2 iterations = 40 + 8 + 8 = 56.

7 votes

-- Arjun Suresh ( 124085 points)

80-c ,because a miss is related to cache line.Initially all lines are empty so 32.Then 2500(5050,size of array)2048(3264,size of cache)=452.this requires 7.0625 cachelines so another 8 misses then 2nd time 8 and 8 =16 .net =
56.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

340 of 1876

81-c , everytime this first 8 line 0-7 are being replaced and a total of 3 times they've been replaced.
-- anshu ( 2155 points)

1 votes

3.20 Cache Memory: GATE2014-2_43 top

gateoverflow.in/2009

In designing a computer's cache system, the cache block (or cache line) size is an important parameter. Which one of the
following statements is correct in this context?
(A) A smaller block size implies better spatial locality
(B) A smaller block size implies a smaller cache tag and hence lower cache tag overhead
(C) A smaller block size implies a larger cache tag and hence lower cache hit time
(D) A smaller block size incurs a lower cache miss penalty
gate2014-2

co&architecture

cache-memory

normal

Selected Answer

(A) A smaller block size means during a memory access only a smaller part of near by addresses are brought to cachemeaning spatial locality is reduced.
(B) A smaller block size means more number of blocks (assuming cache size constant)and hence we need more cache tag
bits to identify the correct block. So, cache tag becomes bigger.
(C) A smaller block size implying larger cache tag is true, but this can't lower cache hit time in any way.
(D) A smaller block size incurs a lower cache miss penalty. This is because during a cache miss, an entire cache block is
fetched from next lower level of memory. So, a smaller block size means only a smaller amount of data needs to be
fetched and hence reduces the miss penalty (Cache block size can go til the size of data bus to the next level of memory,
and beyond this only increasing the cache block size increases the cache miss penalty).
-- Arjun Suresh ( 124085 points)

8 votes

D option makes perfect sense as there is no relation between tagbits and size of block/lines in caching
-- Siddharth Singh Taragi ( 21 points)

1 votes

3.21 Cache Memory: GATE2009_29 top

gateoverflow.in/1315

Consider a 4-way set associative cache (initially empty) with total 16 cache blocks. The main memory consists of 256 blocks
and the request for memory blocks are in the following order:
0, 255, 1, 4, 3, 8, 133, 159, 216, 129, 63, 8, 48, 32, 73, 92, 155.
Which one of the following memory block will NOT be in cache if LRU replacement policy is used?
A. 3
B. 8
C. 129
D. 216
gate2009

co&architecture

cache-memory

normal

Selected Answer

16 blocks and sets with 4 blocks each means there are 4 sets. So, the lower 2 bits are used for getting a set. And 4 way
associative means in a set only the last 4 cache accesses can be stored.
0, 255, 1, 4, 3, 8, 133, 159, 216, 129, 63, 8, 48, 32, 73, 92, 155

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

341 of 1876

Mod 4 gives
0, 3, 1, 0, 3, 0, 1, 3, 0, 1, 3, 0, 0, 0, 1, 0, 3
Now for each of 0..3, the last 4 accesses will be in cache. So, {92, 32, 48, 8}, {155, 63, 459, 3}, {73, 129, 133, 1} and
{} will be in cache. So, the missing element from choice is 216.
-- Arjun Suresh ( 124085 points)

9 votes

3.22 Cache Memory: GATE1999_1.22 top

gateoverflow.in/1475

The main memory of a computer has 2 cm blocks while the cache has 2c blocks. If the cache uses the set associative
mapping scheme with 2 blocks per set, then block k of the main memory maps to the set
A. (k mod m) of the cache
B. (k mod c) of the cache
C. (k mod 2c) of the cache
D. (k mod 2 cm) of the cache

gate1999

co&architecture

cache-memory

normal

Selected Answer

Number of cache blocks = 2c


Number of sets in cache = 2c/2 = c since each set has 2 blocks. Now, a block of main memory gets mapped to a set
(associativity of 2 just means there are space for 2 memory blocks in a cache set), and we have 2cm blocks being mapped
to c sets. So, in each set 2m different main memory blocks can come and block k of main memory will be mapped to k
mod c.
-- Arjun Suresh ( 124085 points)

5 votes

3.23 Cache Memory: GATE2005_67 top

gateoverflow.in/1390

Consider a direct mapped cache of size 32 KB with block size 32 bytes. The CPU generates 32 bit addresses. The number of
bits needed for cache indexing and the number of tag bits are respectively,
A. 10, 17
B. 10, 22
C. 15, 17
D. 5, 17

gate2005

co&architecture

cache-memory

easy

Selected Answer

Number of blocks = cache size/block size = 32KB/32 = 1024 bytes. So, indexing requires 10 bits. Number of OFFSET bits
required to access 32 bit block = 5. So, number of TAG bits = 32 - 10 - 5 = 17. So, answer is (A).
5 votes

3.24 Cache Memory: GATE2013_20 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/1442

In a k-way set associative cache, the cache is divided into v sets, each of which consists of k lines. The lines of a set are
placed in sequence one after another. The lines in set s are sequenced before the lines in set (s + 1). The main memory blocks
are numbered 0 onwards. The main memory block numbered j must be mapped to any one of the cache lines from

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

342 of 1876

(A) (j mod v) k to (j mod v) k + (k 1)


(B) (j mod v) to (j mod v) + (k 1)
(C) (j mod k) to (j mod k) + (v 1)
(D) (j mod k) v to (j mod k) v + (v 1)
gate2013

co&architecture

cache-memory

normal

Selected Answer

Number of sets in cache = v. The question gives a sequencing for the cache lines. For set 0, the cache lines are numbered
0, 1, .., k-1. Now for set 1, the cache lines are numbered k, k+1,... k+k-1 and so on. So, main memory block j will be
mapped to set (j mod v), which will be any one of the cache lines from (j mod v) * k to (j mod v) * k + (k-1).
(Associativity plays no role in mapping- k-way associativity means there are k spaces for a block and hence reduces the
chances of replacement.)
-- Arjun Suresh ( 124085 points)

11 votes

3.25 Cache Memory: GATE2012-54 top

gateoverflow.in/2192

A computer has a 256-KByte, 4-way set associative, write back data cache with block size of 32 Bytes. The processor sends 32
bit addresses to the cache controller. Each cache tag directory entry contains, in addition to address tag, 2 valid bits, 1
modified bit and 1 replacement bit.
The number of bits in the tag field of an address is
A. 11
B. 14
C. 16
D. 27
gate2012

co&architecture

cache-memory

normal

Selected Answer

Total cache size = 256 KB


Cache block size = 32 Bytes
So, number of cache entries = 256 K / 32 = 8 K
Number of sets in cache = 8 K/4 = 2 K as cache is 4-way associative.
So, log(2048) = 11 bits are needed for accessing a set. Inside a set we need to identify the cache entry.
-- Arjun Suresh ( 124085 points)

7 votes

3.26 Cache Memory: GATE1998_18 top


For a set-associative Cache organization, the parameters are as follows:

Copyright GATE Overflow. All rights reserved.

tc

Cache access time

tm

Main memory access time

l
b
k*b

number of sets
block size
set size

gateoverflow.in/1732

GATE Overflow

April 2016

343 of 1876

Calculate the hit ratio for a loop executed 100 times where the size of the loop is n*b, and n = k*m is a non-zero integer and
1 < m 1.
Give the value of the hit ratio for l = 1.
gate1998

co&architecture

cache-memory

descriptive

Selected Answer

Size of the loop = n b = k m b


Size of a set = k b
Here, size of the loop is smaller than size of a set as m 1. Now, however be the mapping (whether all be mapped to the
same set or not), we are guaranteed that the entire loop is in cache without any replacement.
For the first iteration:
No. of accesses = n b
No. of misses = n
For, the remaining 99 iterations:
No. of accesses = n b
No. of misses = 0
So, total no. of accesses = 100nb
Total no. of hits = Total no. of accesses Total no. of misses
= 100nb n
100nb n

So, hit ratio = 100nb = 1 100b


1

The hit ratio is independent if l, so for l = 1 also we have hit ratio = 1


2 votes

3.27 Cache Memory: GATE2006-80 top

100b

-- Arjun Suresh ( 124085 points)

gateoverflow.in/1854

A CPU has a 32 KB direct mapped cache with 128 byte-block size. Suppose A is two dimensional array of size 512 512 with
elements that occupy 8-bytes each. Consider the following two C code segments, P1 and P2.
P1:
for (i=0; i<512; i++)
{
for (j=0; j<512; j++)
{
x +=A[i] [j];
}
}

P2:
for (i=0; i<512; i++)
{
for (j=0; j<512; j++)
{
x +=A[j] [i];
}
}

P1 and P2 are executed independently with the same initial state, namely, the array A is not in the cache and i, j, x are in
registers. Let the number of cache misses experienced by P1 be M1 and that for P2 be M 2.
The value of M 1 is:
A. 0
B. 2048
C. 16384

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

344 of 1876

D. 262144
gate2006

co&architecture

cache-memory

normal

Selected Answer

Code being C implies array layout is row-major.


http://en.wikipedia.org/wiki/Row-major_order
When A[0][0] is fetched, 128 consecutive bytes are moved to cache. So, for the next 128/8 -1= 15 memory references
there won't be a cache miss. For the next iteration of i loop also the same thing happens as there is no temporal locality in
the code. So, number of cache misses for P1
512

= 16 512
= 32 512
= 214 = 16384

-- Arjun Suresh ( 124085 points)

8 votes

215B
Number of Cache Lines = 128B
= 256
128B
In 1 Cache Line = 8B = 16 elements
total elements in array
P1 = elements in a cache line
512 512
=

16

= 214
= 16384
It is so because for P1 for every line there is a miss, and once a miss is processed we get 16 elements in memory. So another miss happens
after 16 elements.
Hence, answer = option C
-- Amar Vashishth ( 17735 points)

3 votes

3.28 Cache Memory: GATE2006-74 top

gateoverflow.in/1851

Consider two cache organizations. First one is 32 kb 2-way set associative with 32 byte block size, the second is of same size
but direct mapped. The size of an address is 32 bits in both cases . A 2-to-1 multiplexer has latency of 0.6ns while a k bit
k

comparator has latency of 10 ns. The hit latency of the set associative organization is h1 while that of direct mapped is h2 .
The value of h1 is:
A. 2.4 ns
B. 2.3 ns
C. 1.8 ns
D. 1.7 ns
gate2006

co&architecture

cache-memory

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

345 of 1876

Selected Answer

Cache size is 32 KB and cache block size is 32 B. So,


cache size

number of sets = no. of blocks in a set block size


32KB

= 2 32B = 512
So, number of index bits needed = 9 ( since 2 9 = 512). Number of offset bits = 5 (since 2 5 = 32 B is the block size and
assuming byte addressing). So, number of tag bits = 32 - 9 - 5 = 18 (as memory address is of 32 bits).
So, time for comparing the data = Time to compare the data + Time to select the block in set = 0.6 + 18/10 ns = 2.4 ns.
(Two comparisons of tag bits need to be done for each block in a set, but they can be carried out in parallel and the
succeeding one multiplexed as the output)
7 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

346 of 1876

gives a better insight.


-- Amar Vashishth ( 17735 points)

5 votes

3.29 Cache Memory: GATE2014-1_44 top

gateoverflow.in/1922

An access sequence of cache block addresses is of length N and contains n unique block addresses. The number of unique
block addresses between two consecutive accesses to the same block address is bounded above by k. What is the miss ratio
if the access sequence is passed through a cache of associativity A k exercising least-recently-used replacement policy?
(A) n/N
(B) 1/N
(C) 1/A
(D) k/n

gate2014-1

co&architecture

cache-memory

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

347 of 1876

There are N accesses to cache.


Out of these n are unique block addresses.
Now, we need to find the number of misses. (min. n misses are guaranteed whatever be the access sequence due to n
unique block addresses)
We are given that between two consecutive accesses to the same block, there can be only k unique block addresses. So,
for a block to get replaced we can assume that all the next k block addresses goes to the same set (given cache is setassociative) which will be the worst case scenario (they may also go to a different set but then there is lesser chance of a
replacement). Now, if associativity size is >= k, and if we use LRU (Least Recently Used) replacement policy, we can
guarantee that these k accesses won't throw out our previously accessed cache entry (for that we need at least k
accesses). So, this means we are at the best-cache scenario for cache replacement -- out of N accesses we miss only n
(which are unique and can not be helped from getting missed and there is no block replacement in cache). So, miss ratio is
n/N.
PS: In question it is given "bounded above by k", which should mean k unique block accesses as k is an integer, but to
ensure no replacement this must be 'k-1'. Guess, a mistake in question.
-- Arjun Suresh ( 124085 points)

18 votes

3.30 Cache Memory: GATE1995_1.6 top

gateoverflow.in/2593

The principle of locality justifies the use of


(a) Interrupts
(b) DMA
(c) Polling
(d) Cache Memory
gate1995

co&architecture

cache-memory

easy

Selected Answer

It is D.
Locality of reference is actually the frequent accessing of any storage location or some value. We can say in simple
language that whatever things are used more frequently, they are stored in the locality of reference. So we have cache
memory for the purpose.
-- Gate Keeda ( 16619 points)

7 votes

3.31 Cache Memory: GATE2012-55 top

gateoverflow.in/43311

A computer has a 256-KByte, 4-way set associative, write back data cache with block size of 32 Bytes. The processor sends 32
bit addresses to the cache controller. Each cache tag directory entry contains, in addition to address tag, 2 valid bits, 1
modified bit and 1 replacement bit.
The size of the cache tag directory is
A. 160 Kbits
B. 136 Kbits
C. 40 Kbits
D. 32 Kbits

normal

gate2012

co&architecture

cache-memory

No of Line or block=256KB/32B
=2^13
No of sets=2^13/4=2^11

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

348 of 1876

tag controller maintains=16+4 =20 bits


So tag directory size=20*2^13
=160Kbits
-- Manojk ( 3327 points)

1 votes

3.32 Cache Memory: GATE2015-3_14 top

gateoverflow.in/8410

Consider a machine with a byte addressable main memory of 220 bytes, block size of 16 bytes and a direct mapped cache
having 212 cache lines. Let the addresses of two consecutive bytes in main memory be (E201F)16 and (E2020)16. What are the
tag and cache line addresses ( in hex) for main memory address (E201F)16?

A. E, 201
B. F, 201
C. E, E20
D. 2, 01F
gate2015-3

co&architecture

cache-memory

normal

Selected Answer

Block size of 16 bytes means we need 4 offset bits. (The lowest 4 digits of memory address are offset bits)
Number of sets in cache (cache lines) = 2 12 so the next lower 12 bits are used for set indexing.
The top 4 bits (out of 20) are tag bits.
So, Answer A.
-- Arjun Suresh ( 124085 points)

9 votes

3.33 Cache Memory: GATE2015-2_24 top

gateoverflow.in/8119

Assume that for a certain processor, a read request takes 50 nanoseconds on a cache miss and 5 nanoseconds on a cache
hit. Suppose while running a program, it was observed that 80% of the processor's read requests result in a cache hit. The
average read access time in nanoseconds is _____.
gate2015-2

co&architecture

cache-memory

easy

Selected Answer

Ans 14 ns = 0.8(5) + 0.2(50)


8 votes

Copyright GATE Overflow. All rights reserved.

-- Vikrant Singh ( 10051 points)

GATE Overflow

April 2016

349 of 1876

3.34 Cache Memory: GATE2005-IT_61 top

gateoverflow.in/3822

Consider a 2-way set associative cache memory with 4 sets and total 8 cache blocks (0-7) and a main memory with 128
blocks (0-127). What memory blocks will be present in the cache after the following sequence of memory block references if
LRU policy is used for cache block replacement. Assuming that initially the cache did not have any memory block from the
current job?
0 5 3 9 7 0 16 55

A)
B)
C)
D)

0 3 5 7 16 55
0 3 5 7 9 16 55
0 5 7 9 16 55
3 5 7 9 16 55



gate2005-it

co&architecture

cache-memory

normal

Selected Answer

128 main memory blocks are mapped to 4 sets in cache. So, each set maps 32 blocks each. And in each set there is place
for two blocks (2-way set).
Now, we have 4 sets meaning 2 index bits. Also, 32 blocks going to one set means 5 tag bits.
Now, these 7 bits identify a memory block and tag bits are placed before index bits. (otherwise adjacent memory
references- spatial locality- will hamper cache performance)
So, based on the two index bits (lower 2 bits) blocks will be going to sets as follows:
Set Number

Block Numbers

0
1

0,16
5, 9

2
3


3, 7, 55


Since, each set has only 2 places, 3 will be throw out as its the least recently used block. So, final content of cache will be
0 5 7 9 16 55
(C) choice.

12 votes

3.35 Cache Memory: GATE2010-49 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/43329

A computer system has an L1 cache, an L2 cache, and a main memory unit connected as shown below. The block size in L1
cache is 4 words. The block size in L2 cache is 16 words. The memory access times are 2 nanoseconds, 20 nanoseconds and
200 nanoseconds for L1 cache, L2 cache and the main memory unit respectively.

When there is a miss in both L1 cache and L2 cache, first a block is transferred from main memory to L2 cache, and then a
block is transferred from L2 cache to L1 cache. What is the total time taken for these transfers?

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

350 of 1876

A. 222 nanoseconds
B. 888 nanoseconds
C. 902 nanoseconds
D. 968 nanoseconds
gate2010

co&architecture

cache-memory

normal

The transfer time should be 4*200 + 20 = 820 ns. But this is not in option. So, I assume the following is what is meant by
the question.
L2 block size being 16 words and data width between memory and L2 being 4 words, we require 4 memory accesses(for
read) and 4 L2 accesses (for store). Now, we need to send the requested block to L1 which would require one more L2
access (for read) and one L1 access (for store). So, total time
= 4 * (200 + 20) + (20 + 2)
= 880 + 22
= 902 ns
-- Arjun Suresh ( 124085 points)

0 votes

3.36 Cache Memory: GATE2008-72 top

gateoverflow.in/43490

Consider a machine with a 2-way set associative data cache of size 64 Kbytes and block size 16 bytes. The cache is managed
using 32 bit virtual addresses and the page size is 4 Kbytes. A program to be run on this machine begins as follows:
double ARR[1024][1024];
int i, j;
/*Initialize array ARR to 0.0 */
for(i = 0; i < 1024; i++)
for(j = 0; j < 1024; j++)
ARR[i][j] = 0.0;

The size of double is 8 bytes. Array ARR is located in memory starting at the beginning of virtual page 0xFF000 and stored in
row major order. The cache is initially empty and no pre-fetching is done. The only data memory references made by the
program are those to array ARR.
Which of the following array elements have the same cache index as ARR[0][0]?
A. ARR[0][4]
B. ARR[4][0]
C. ARR[0][5]
D. ARR[5][0]
gate2008

co&architecture

cache-memory

normal

3.37 Cache Memory: GATE2006-75 top

gateoverflow.in/43565

Consider two cache organizations. First one is 32 kb 2-way set associative with 32 byte block size, the second is of same size
but direct mapped. The size of an address is 32 bits in both cases . A 2-to-1 multiplexer has latency of 0.6ns while a k bit
k

comparator has latency of


The value of h2 is:

10

ns. The hit latency of the set associative organization is h1 while that of direct mapped is h2 .

A. 2.4 ns
B. 2.3 ns
C. 1.8 ns
D. 1.7 ns

gate2006

co&architecture

cache-memory

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

351 of 1876

cache size

number of sets =

no. of blocks in a set block size

32KB

1 32B

= 1024

So, number of index bits = 10, and number of tag bits = 32 - 10 - 5 = 17. So, h2
= 17/10 = 1.7 ns
-- Arjun Suresh ( 124085 points)

0 votes

3.38 Cache Memory: GATE2006-81 top

gateoverflow.in/43517

A CPU has a 32 KB direct mapped cache with 128 byte-block size. Suppose A is two dimensional array of size 512 512 with
elements that occupy 8-bytes each. Consider the following two C code segments, P1 and P2.
P1:
for (i=0; i<512; i++)
{
for (j=0; j<512; j++)
{
x +=A[i] [j];
}
}

P2:
for (i=0; i<512; i++)
{
for (j=0; j<512; j++)
{
x +=A[j] [i];
}
}

P1 and P2 are executed independently with the same initial state, namely, the array A is not in the cache and i, j, x are in
registers. Let the number of cache misses experienced by P1 be M1 and that for P2 be M2.
M1

The value of the ratio

M2

A. 0
1

B.

16
1

C. 8
D. 16

co&architecture

cache-memory

normal

Selected Answer

Copyright GATE Overflow. All rights reserved.

gate2006

GATE Overflow

April 2016

352 of 1876

215B
Number of Cache Lines = 128B
= 256
128B
In 1 Cache Line = 8B = 16 elements
total elements in array
elements in a cache line
P1 =
512 512
16

= 214
= 16384
P2 = 512 512
= 218
P1
P2

16384
512 512

= 21418
= 2 4
1
16
=
It is so because for P1 for every line there is a miss, and once a miss is processed we get 16 elements in memory. So another miss happens
after 16 elements.
for P2 for every element there is a miss coz storage is row major order(by default) and we are accessing column wise.
Hence,
answer = option B

1 votes

-- Amar Vashishth ( 17735 points)

No. of elements/block = 128/8=16


one row contains 512 elements
No. of blocks/row= 512/16 = 32
No. of cache lines = 32KB/128B= 256
FOR M1
Now to access one row 32 miss operations will be occurred
to access whole array it requires = 512 * 32 (miss operations)
= 16384
FOR M2
Now to access one column 512 miss operations will occur(as it is column major)
to access whole array it requires = 512 * 512 (miss operations)
so M1/M2=1/16
ANSWER IS (B)
1 votes

3.39 Cache Memory: GATE2007-81 top

Copyright GATE Overflow. All rights reserved.

-- Tauhin Gangwar ( 509 points)

gateoverflow.in/43511

GATE Overflow

April 2016

353 of 1876

Consider a machine with a byte addressable main memory of 216 bytes. Assume that a direct mapped data cache consisting
of 32 lines of 64 bytes each is used in the system. A 50 x 50 two-dimensional array of bytes is stored in the main memory
starting from memory location 1100H. Assume that the data cache is initially empty. The complete array is accessed twice.
Assume that the contents of the data cache do not change in between the two accesses.
Which of the following lines of the data cache will be replaced by new blocks in accessing the array for the second time?
A. line 4 to line 11
B. line 4 to line 12
C. line 0 to line 7
D. line 0 to line 8
gate2007

co&architecture

cache-memory

normal

Answer is lines 4 to 11 as we start from


1100 H = (0001 0001 0000 0000) b excluding lower 6 bits for offset, we get 0001 0001 00 bits for cache block which is the
4th block.
-- Arjun Suresh ( 124085 points)

0 votes

3.40 Cache Memory: GATE2008-73 top

gateoverflow.in/43491

Consider a machine with a 2-way set associative data cache of size 64 Kbytes and block size 16 bytes. The cache is managed
using 32 bit virtual addresses and the page size is 4 Kbytes. A program to be run on this machine begins as follows:
double ARR[1024][1024];
int i, j;
/*Initialize array ARR to 0.0 */
for(i = 0; i < 1024; i++)
for(j = 0; j < 1024; j++)
ARR[i][j] = 0.0;

The size of double is 8 bytes. Array ARR is located in memory starting at the beginning of virtual page 0xFF000 and stored in
row major order. The cache is initially empty and no pre-fetching is done. The only data memory references made by the
program are those to array ARR.
The cache hit ratio for this initialization loop is
A. 0%
B. 25%
C. 50%
D. 75%

gate2008

co&architecture

cache-memory

normal

3.41 Cache Memory: GATE2004-IT_48 top

gateoverflow.in/3691

Consider a fully associative cache with 8 cache blocks (numbered 0-7) and the following sequence of memory block
requests:
4, 3, 25, 8, 19, 6, 25, 8, 16, 35, 45, 22, 8, 3, 16, 25, 7
If LRU replacement policy is used, which cache block will have memory block 7?

A)
B)
C)
D)
gate2004-it

4
5
6
7

co&architecture

cache-memory

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

354 of 1876

Selected Answer

When 45 comes, the cache contents are


4 3 25 8 19 6 16 35
LRU array (first element being least recently used)
[4 3 19 6 25 8 16 35]
So, 45 replaces 4
45 3 25 8 19 6 16 35 [3 19 6 25 8 16 35 45]
Similarly 22 replaces 3 to give
45 22 25 8 19 6 16 35 [19 6 25 8 16 35 45 22]
8 hits in cache
45 22 25 8 19 6 16 35 [19 6 25 16 35 45 22 8]
3 replaces 19
45 22 25 8 3 6 16 35 [6 25 16 35 45 22 8 3]
16 and 25 hits in cache
45 22 25 8 3 6 16 35 [6 35 45 22 8 16 25 3]
Finally 7 replaces 6, which is in block 5.
So, answer is (B)
-- Arjun Suresh ( 124085 points)

4 votes

3.42 Cache Memory: GATE2004-IT_12 top

gateoverflow.in/3653

Consider a system with 2 level cache. Access times of Level 1 cache, Level 2 cache and main memory are 1 ns, 10 ns, and
500 ns, respectively. The hit rates of Level 1 and Level 2 caches are 0.8 and 0.9, respectively. What is the average access
time of the system ignoring the search time within the cache?

A)
13.0 ns
B)
12.8 ns
C)
12.6 ns
D)
12.4 ns
gate2004-it

co&architecture

cache-memory

normal

Selected Answer

option C
t1 * h1 + (1- h1) h2 t2 + (1-h1) (1-h2) tm
tm- main memory access time
-- rajsh3kar ( 851 points)

6 votes

3.43 Cache Memory: GATE1996_26 top


A computer system has a three level memory hierarchy, with access time and hit ratios as shown below:
Level 1 (Cache memory)

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/2778

GATE Overflow

April 2016

355 of 1876

Access time = 50 nsec/byte


Size
8 M byte
16 M byte

Hit Ratio
0.80
0.90

64 M byte

0.95


Level 2 (main memory)
Access time = 200 nsec/byte
Size
4M byte

Hit ratio
0.98

16 M byte
64 M byte

0.99
0.995


Level 3
Size
260 Mbyte

Hit ratio
1.0


A. What should be the minimum sizes of level 1 and 2 memories to achieve an average access time of less than 100 nsec
B. What is the average access time achieved using the chosen sizes of level 1 and level 2 memories?

gate1996

co&architecture

cache-memory

normal

The equation for access time can be written as follows(assuming a,b are the hit ratios of level1 and level2 respectively).
T = T1 + (1 a)T2 + (1 a) (1 b)T3
Here T<=100, T1 = 50ns ,T2 = 200ns and T3 = 5000ns. On substituting the a, b for the first case we get

T = 95ns for a = 0.8 and b = 0.995. i.e., L1 = 8M and L2 = 64M.


T = 75ns for a = 0.9 and b = 0.99. i.e., L1 = 16M and L2 = 4M
b.
1. L1 = 8M, a = 0.8, L2 = 4M, b = 0.98. So,
T = 50 + 0.2 200 + 0.2 0.02 5000 = 50 + 40 + 20 = 110ns
2. L1 = 16M, a = 0.9, L2 = 16M, b = 0.99. So,
T = 50 + 0.1 200 + 0.1 0.01 5000 = 50 + 20 + 5 = 75ns
3. L1 = 64M, a = 0.95, L2 = 64M, b = 0.995. So,
T = 50 + 0.05 200 + 0.05 0.005 5000 = 50 + 10 + 1.25 = 61.25ns

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

356 of 1876


-- kireeti ( 883 points)

1 votes

3.44 Cache Memory: GATE1995_2.25 top

gateoverflow.in/2638

A computer system has a 4 K word cache organized in block-set-associative manner with 4 blocks per set, 64 words per
block. The number of bits in the SET and WORD fields of the main memory address format is:

(A) 15, 40
(B) 6, 4
(C) 7, 2
(D) 4, 6
gate1995

co&architecture

cache-memory

normal

Selected Answer

Number of sets = 4K /(64*4) = 16. So, we need 4 bits to identify a set => SET = 4 bits.
64 words per block means WORD is 6 bits.
So, (D)
-- Arjun Suresh ( 124085 points)

5 votes

3.45 Cache Memory: GATE2004_65 top

gateoverflow.in/1059

Consider a small two-way set-associative cache memory, consisting of four blocks. For choosing the block to be replaced,
use the least recently used (LRU) scheme. The number of cache misses for the following sequence of block addresses is
8, 12, 0, 12, 8
A. 2
B. 3
C. 4
D. 5


gate2004

co&architecture

cache-memory

normal

Selected Answer

We have 4 blocks and 2 blocks in a set


=> there are 2 sets. So blocks will go
to sets as follows:
Set Number

Block Number

0, 8, 12

since the lowest bit of block address is used for indexing into the set.
So, 8, 12 and 0 first miss in cache with 0 replacing 8 (there are two slots in each set due to 2-way set) and then 12 hits in
cache and 8 again misses. So totally 4 misses.
3 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

357 of 1876

3.46 Cache Memory: GATE2010-48 top

gateoverflow.in/2352

A computer system has an L1 cache, an L2 cache, and a main memory unit connected as shown below. The block size in L1 cache is 4
words. The block size in L2 cache is 16 words. The memory access times are 2 nanoseconds, 20 nanoseconds and 200 nanoseconds for L1
cache, L2 cache and the main memory unit respectively.

Q.48 When there is a miss in L1 cache and a hit in L2 cache, a block is transferred from L2 cache to L1 cache. What is the time taken for this
transfer?

(A) 2 nanoseconds
(B) 20 nanoseconds
(C) 22 nanoseconds
(D) 88 nanoseconds

gate2010

co&architecture

cache-memory

normal

Selected Answer

Ideally the answer should be 20 ns as it is the time to transfer a block from L2 to L1 and this time only is asked in
question. But there is confusion regarding access time of L2 as this means the time to read data from L2 till CPU but here
we need the time till L1 only. So, I assume the following is what is meant by the question.
A block is transferred from L2 to L1. And L1 block size being 4 words (since L1 is requesting we need to consider L1 block
size and not L2 block size) and data width being 4 bytes, it requires one L2 access (for read) and one L1 access (for
store). So, time = 20+2 = 22 ns.
-- Arjun Suresh ( 124085 points)

19 votes

3.47 Cache Memory: GATE2008-IT_80 top

gateoverflow.in/3403

Consider a computer with a 4-ways set-associative mapped cache of the following characteristics: a total of 1 MB of main
memory, a word size of 1 byte, a block size of 128 words and a cache size of 8 KB.
The number of bits in the TAG, SET and WORD fields, respectively are:

A.
B.
C.
D.
gate2008-it

7, 6, 7
8, 5, 7
8, 6, 6
9, 4, 7

co&architecture

cache-memory

normal

Selected Answer

Number of cache blocks = 8KB/(128*1) = 64



Number of sets in cache = Number of cache blocks/ 4 (4-way set)
= 64 / 4 = 16
So, number of SET bits required = 4 (as 24 = 16, and with 4 bits we can get 16 possible outputs)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

358 of 1876

We can now straight away choose (D) as answer but for confirmation can proceed further.
Since, only physical memory information is given we can assume cache is physically tagged (which is anyway the common
case even in case of virtual memory). So, we can divide the physical memory into 16 regions so that, each set maps into
only its assigned region. So, size of a region a set can address = 1MB/16 = 2 16 Bytes = 2 16 /128 = 2 9 cache blocks (as
cache block size is 128 words = 128 bytes). So, when an access comes to an cache entry, it must be able to
determine which out of the 2 9 possible physical block it is. In short it needs 9 bits for TAG.
Now, cache block size is 128 words and so to identify a word we need 7 bits for WORD.


-- Arjun Suresh ( 124085 points)

6 votes

3.48 Cache Memory: GATE2008-IT_81 top

gateoverflow.in/3405

Consider a computer with a 4-ways set-associative mapped cache of the following characteristics: a total of 1 MB of main
memory, a word size of 1 byte, a block size of 128 words and a cache size of 8 KB.
While accessing the memory location 0C795H by the CPU, the contents of the TAG field of the corresponding cache line is

A.
B.
C.
D.
gate2008-it

000011000
110001111
00011000
110010101

co&architecture

cache-memory

normal

Selected Answer

As shown in http://gateoverflow.in/3403/gate2008-it_80 we have 16 sets in cache and correspondingly 16 regions in


physical memory to which each set is mapped. Now, WORD bit size is 7 as we need 7 bits to address 128 possible words
in a cache block. So, the lowest 7 bits of 0C795H will be used for this giving us the remaining bits as
0000 1100 0111 1
Of these bits, the lower 4 are used for addressing the 16 possible sets, giving us the tag bits: 0000 1100 0 in (A) choice.
-- Arjun Suresh ( 124085 points)

7 votes

20 bit physical address will be divided into


9-tag, 4-set 7-word
so answer will be A
-- Monisha ( 127 points)

3 votes

3.49 Cache Memory: GATE2006-IT_43 top

gateoverflow.in/3586

A computer system has a level-1 instruction cache (1-cache), a level-1 data cache (D-cache) and a level-2 cache (L2-cache)
with the following specifications:

Block

Capacity Mapping Method
size
I-cache 4K words Direct mapping
2-way
set
D-cache 4K words
mapping
L2cache

Copyright GATE Overflow. All rights reserved.

64K
words

4-way
mapping

set

4 Words
associative
associative

4 Words
16 Words

GATE Overflow

April 2016

359 of 1876



The length of the physical address of a word in the main memory is 30 bits. The capacity of the tag memory in the I-cache,
D-cache and L2-cache is, respectively,

A)
B)
C)
D)

1 K x 18-bit, 1 K x 19-bit, 4 K x 16-bit


1 K x 16-bit, 1 K x 19-bit, 4 K x 18-bit
1 K x 16-bit, 512 x 18-bit, 1 K x 16-bit
1 K x 18-bit, 512 x 18-bit, 1 K x 18-bit

gate2006-it

co&architecture

cache-memory

normal

Selected Answer

1. I-cache
Number of blocks in cache = 4K/4 = 2 10 blocks
Bits to represent blocks = 10
Number of words in a block = 4 = 2 2 words
Bits to represent words = 2
tag bits = 30 - (10+2) = 18
Each block will have it's own tag bits. So total tag bits = 1K x 18 bits.
2. D-cache
Number of blocks in cache = 4K/4 = 2 10 blocks
Number of sets in cache = 2 10 /2 = 29 sets
Bits to represent sets = 9
Number of words in a block = 4 = 2 2 words
Bits to represent words = 2
tag bits = 30 - (+2) = 19
Each block will have it's own tag bits. So total tag bits = 1K x 19 bits.
3. L2 cache
Number of blocks in cache = 64K/16 = 2 12 blocks
Number of sets in cache = 2 12 /4 = 28 sets
Bits to represent sets = 8
Number of words in cache = 16 = 2 4 words
Bits to represent words = 4
tag bits = 30 - (8+4) = 18
Each block will have it's own tag bits. So total tag bits = 2 12 x 18 bits = 4K x 18 bits
Option A.
-- Viral Kapoor ( 1777 points)

5 votes

3.50 Cache Memory: GATE2006-IT_42 top

gateoverflow.in/3585

A cache line is 64 bytes. The main memory has latency 32ns and bandwidth 1G.Bytes/s. The time required to fetch the entire
cache line from the main memory is

A)
B)
C)
D)
gate2006-it

32 ns
64 ns
96 ns
128 ns

co&architecture

cache-memory

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

360 of 1876

Selected Answer

ans : c
for 1 sec it is 10^9 bytes
so for 64 bytes?
it is 64 * 1 /10^9 so it is 64 ns but mm latency is 32 so total time required to place cache line is
64+32 = 96 ns
-- rajsh3kar ( 851 points)

8 votes

3.51 Cache Memory: GATE2007-IT_37 top

gateoverflow.in/3470

Consider a Direct Mapped Cache with 8 cache blocks (numbered 0-7). If the memory block requests are in the following
order
3, 5, 2, 8, 0, 63, 9,16, 20, 17, 25, 18, 30, 24, 2, 63, 5, 82,17, 24.
Which of the following memory blocks will not be in the cache at the end of the sequence ?

A)
B)
C)
D)
gate2007-it

3
18
20
30

co&architecture

cache-memory

normal

Selected Answer

ans is B
cache location (memory block) = block req mod number of cache blocks. Since each block has only one location
(associativity is 1) the last mod 8 request will be in cache (no need of any replacement policy as mapping is direct).
3, 5, 2, 8, 0, 63, 9, 16, 20, 17, 25, 18, 30, 24, 2, 63, 5, 82, 17, 24
Block 0- 8, 0, 16, 24. At end contains 24.
1- 9, 17, 25, 63, 17.
2- 2, 18, 2, 82.
3- 3.
4- 20.
5- 5, 5.
6- 30.
7- 63 63.
So, memory block 18 is not in cache while 3, 20 and 30 are in cache.
-- rajsh3kar ( 851 points)

4 votes

3.52 Cache Memory: GATE1993_11 top

gateoverflow.in/2308

In the three-level memory hierarchy shown in the following table, pi denotes the probability that an access request will refer
to Mi.

Copyright GATE Overflow. All rights reserved.

Hierarchy
Level

Access
Time

Probability of
access

Page Transfer
Time

(Mi)

(ti)

(pi)

(Ti)

GATE Overflow

April 2016
M1
Hierarchy
Level
M2
(M
M3i)

Access
10 6
Time
10 5
(ti)
10 4

361 of 1876

Probability of
0.99000
access

Page Transfer
0.001 sec
Time

0.00998
(pi)

0.1 sec
(Ti)

0.00002

--


If a miss occurs at level Mi, a page transfer occurs from Mi +1 to Mi and the average time required for such a page swap is Ti.
Calculate the average time tA required for a processor to read one word from this memory system.
gate1993

co&architecture

cache-memory

normal

0.99000(10-6) + (1-0.99000)[(0.00998)(10 -6 +10-5 + 0.001) + (1-0.00998){(0.00002)*(10 -6 + 10-5 + 10-4 + 0.1)}] =


1.1*10-6 s.
-- Rajarshi Sarkar ( 27781 points)

1 votes

3.53 Cache Memory: GATE2014-2_44 top

gateoverflow.in/2010

If the associativity of a processor cache is doubled while keeping the capacity and block size unchanged, which one of the
following is guaranteed to be NOT affected?
(A) Width of tag comparator
(B) Width of set index decoder
(C) Width of way selection multiplexor
(D) Width of processor to main memory data bus
gate2014-2

co&architecture

cache-memory

normal

Selected Answer

If associativity is doubled, keeping the capacity and block size constant, then the number of sets gets halved. So, width of
set index decoder can surely decrease - (B) is false.
Width of way-selection muntiplexer must be increased as we have to double the ways to choose from- (C) is false
As the number of sets gets decreased, the number of possible cache block entries that a set maps to gets increased. So,
we need more tag bits to identify the correct entry. So, (A) is also false.
(D) is the correct answer- main memory data bus has nothing to do with cache associativity- this can be answered without
even looking at other options.
7 votes

3.54 Cache Memory: GATE2001_9 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/750

A CPU has 32-bit memory address and a 256 KB cache memory. The cache is organized as a 4-way set associative cache
with cache block size of 16 bytes.
A. What is the number of sets in the cache?
B. What is the size (in bits) of the tag field per cache block?
C. What is the number and size of comparators required for tag matching?
D. How many address bits are required to find the byte offset within a cache block?
E. What is the total amount of extra memory (in bytes) required for the tag bits?

Copyright GATE Overflow. All rights reserved.

GATE Overflow
gate2001

April 2016

co&architecture

cache-memory

362 of 1876

normal

Selected Answer

What is the number of sets in the cache?


Number of sets = Cache memory/(set associativity * cache block size)
= 256KB/(4*16 B)
= 4096

What is the size (in bits) of the tag field per cache block?
Memory address size = 32-bit
Number of bits required to identify a particular set = 12 (Number of sets = 4096)
Number of bits required to identify a paticular location in cache line = 4 (cache block size = 16)
size of tag field = 32 -12 -4 = 16-bit

What is the number and size of comparators required for tag matching?
We use 4-way set associate cache. So, we need 4 comparators each of size 16 bits
http://ecee.colorado.edu/~ecen2120/Manual/caches/cache.html

How many address bits are required to find the byte offset within a cache block?
Cache block size is 16 byte. so 4 bits are required to find the byte offset within a cache block.

What is the total amount of extra memory (in bytes) required for the tag bits?
size of tag = 16 bits
Number of sets = 4096
Set associativity = 4
Extramemory required to store the tag bits = 16 * 4096 * 4 bits = 2 15 bytes
10 votes

-- suraj ( 3299 points)

A. To find the number of sets we need to determine the number of rows. To do that we need to determine the number of
blocks. We are given that this is a 4-way set associative cache, hence each set has four blocks.
It holds:
#Blocks = Capacity / BlockSize = 2 18 / 24 = 2 14. There are 2 14 blocks.
#Sets = #Blocks / #ways = 2 14 / 22 = 2 12. There are 2 12 sets.

1 votes

3.55 Cache Memory: GATE2002_10 top

-- Shyam Singh ( 1357 points)

gateoverflow.in/863

In a C program, an array is declared as float A[2048]. Each array element is 4 Bytes in size, and the starting address of the
array is 0x00000000. This program is run on a computer that has a direct mapped data cache of size 8 Kbytes, with block

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

363 of 1876

(line) size of 16 Bytes.


a. Which elements of the array conflict with element A[0] in the data cache? Justify your answer briefly.
b. If the program accesses the elements of this array one by one in reverse order i.e., starting with the last element and
ending with the first element, how many data cache misses would occur? Justify your answer briefly. Assume that the
data cache is initially empty and that no other data or instruction accesses are to be considered.

gate2002

co&architecture

cache-memory

normal

Selected Answer

(a)
Data cache size = 8KB.
Block line size = 16B.
Since each array element occupies 4B, four consecutive array elements occupy a block line (elements are aligned as
starting address is 0)
Number of cache blocks = 8KB/16B = 512. Number of cache blocks needed for the array = 2048/4 = 512. So, all the
array elements has its own cache block and there is no collision.
We can also explain this with respect to array address. Starting address is 0x00000000 = 0b0000..0 (32 0's). Ending
address is 0x00001FFF = 0b0000..0111111111111 (4*2048 = 8192 location).
Here, the last 4 bits are used as OFFSET bits and the next 9 bits are used as SET bits. So, since the ending address is not
extending beyond these 9 bits, all cache accesses are to diff sets.
(b) If the last element is accessed first, its cache block is fetched. (which should contain the previous 3 elements of the
array also since each cache block hold 4 elements of array and 2048 is and exact multiple of 4). Thus, for every 4
accesses, we will have a cache miss => for 2048 accesses we will have 512 cache misses. (This would be same even if we
access array in forward order).
-- Arjun Suresh ( 124085 points)

8 votes

3.56 Cache Memory: GATE1992-5,a top

gateoverflow.in/584

The access times of the main memory and the Cache memory, in a computer system, are 500 n sec and 50 n sec,
respectively. It is estimated that 80% of the main memory request are for read the rest for write. The hit ratio for the read
access only is 0.9 and a write-through policy (where both main and cache memories are updated simultaneously) is used.
Determine the average time of the main memory.
gate1992

co&architecture

cache-memory

normal

Selected Answer

Average memory access time = Time spend for read + Time spend for write
= Read time when cache hit + Read time when cache miss
+Write time when cache hit + Write time when cache miss
= 0.8 0.9 50 + 0.8 0.1 (500+50) (assuming hierarchical read from memory and cache as only simultaneous write is
mentioned in question)
+ 0.2 0.9 500 + 0.2 0.1 500 (simultaneous write mentioned in question)
= 36 + 44 + 90 + 10 = 180 ns
http://www.howardhuang.us/teaching/cs232/24-Cache-writes-and-examples.pdf
3 votes

3.57 Cache Memory: GATE2008-71 top


Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/494

GATE Overflow

April 2016

364 of 1876

Consider a machine with a 2-way set associative data cache of size 64 Kbytes and block size 16 bytes. The cache is managed
using 32 bit virtual addresses and the page size is 4 Kbytes. A program to be run on this machine begins as follows:
double ARR[1024][1024];
int i, j;
/*Initialize array ARR to 0.0 */
for(i = 0; i < 1024; i++)
for(j = 0; j < 1024; j++)
ARR[i][j] = 0.0;

The size of double is 8 bytes. Array ARR is located in memory starting at the beginning of virtual page 0xFF000 and stored in
row major order. The cache is initially empty and no pre-fetching is done. The only data memory references made by the
program are those to array ARR.
The total size of the tags in the cache directory is
A. 32 Kbits
B. 34 Kbits
C. 64 Kbits
D. 68 Kbits
gate2008

co&architecture

cache-memory

normal

Selected Answer

Number of sets = cache size/ size of a set


= 64 KB / (16 B * 2) (two blocks per set)
= 2 K = 211
So, we need 11 bits for set indexing.
Number of WORD bits required = 4 as a cache block consists of 16 bytes and we need 4 bits to address each of them.
So, number of tag bits = 32 - 11 - 4 = 17
Total size of the tag = 17 * Number of cache blocks
= 17 * 211 * 2 (since each set has 2 blocks)
= 68 KB
We use the top 17 bits for tag and the next 11 bits for indexing and next 4 for offset. So, for two addresses to have the
same cache index, their 11 address bits after the 4 offset bits from right must be same.
ARR[0][0] is located at virtual address 0x FF000 000. (FF000 is page address and 000 is page offset). So, index bits are
00000000000
Address of ARR[0][4] = 0xFF000 + 4 * sizeof (double) = 0xFF000 000 + 4*8 = 0xFF000 020 (32 = 20 in hex) (index bits
differ)
Address of ARR[4][0] = 0xFF000 + 4 * 1024 * sizeof (double) [since we use row major storage] = 0xFF000 000 +
4096*8 = 0xFF000 000 + 0x8000 = 0xFF008 000 ( index bits matches that of ARR [0][0] as both read 000 0000 0000)

Address of ARR[0][5] = 0xFF000 + 5 * sizeof (double) = 0xFF000 000+ 5*8 = 0xFF000 028 (40 = 28 in hex) (index bits
differ)
Address of ARR[5][0] = 0xFF000 + 5 * 1024 * sizeof (double) [since we use row major storage] = 0xFF000 000 +
5120*8 = 0xFF000 000 + 0xA000 = 0xFF00A 000 (index bits differ)
So, only ARR[4][0] and ARR[0][0] have the same cache index.
The inner loop is iterating from 0 to 1023, so consecutive memory locations are accessed in sequence. Since cache block
size is only 16 bytes and our element being double is of size 8 bytes, during a memory access only the next element gets
filled in the cache. i.e.; every alternative memory access is a cache miss giving a hit ratio of 50%. (If loops i and j are
reversed, all accesses will be misses and hit ratio will become 0).

17 votes

3.58 Cache Memory: GATE2008_35 top

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/446

GATE Overflow

April 2016

365 of 1876

For inclusion to hold between two cache levels L1 and L2 in a multi-level cache hierarchy, which of the following are
necessary?
I. L1 must be write-through cache
II. L2 must be a write-through cache
III. The associativity of L2 must be greater than that of L1
IV. The L2 cache must be at least as large as the L1 cache

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

gate2008

co&architecture

cache-memory

normal

Selected Answer

1st is not correct as data need not to be exactly same at the same point of time and so write back policy can be used in
this.
2nd is not needed when talking only about L1 and L2.
For 3rd, associativity can be equal.
So only 4th statement is Necessarily true - A choice.
-- Shaun Patel ( 5445 points)

5 votes

Cache levels differs only because their access times are different. If L1 is made write through then it implies that on every
write operation it will take the same time that L2 cache takes to write. so this will erase the difference between L1 and L2
and to use them at different levels will be implied as meaningless. So, statement I cannot be true always.
statement II asks that L2 is always write through, this is not true for every case we can have a Write Back cache in many
cases. So, this is also false.
statement III talks nothing meaningful. as assoc. has nothing to do here.
statement IV : for Inclusion property to hold it is required that L1 is a subset of L2 cache.
Hence, answer = option A
-- Amar Vashishth ( 17735 points)

2 votes

3.59 Computer Organization: GATE 2016-2-33 top

gateoverflow.in/39580

32

Consider a 3 GHz (gigahertz) processor with a three stage pipeline and stage latencies 1 , 2 and 3 such that 1 = 4 = 23 . If
the longest pipeline stage is split into two pipeline stages of equal latency , the new frequency is __________ GHz, ignoring
delays in the pipeline registers.

gate2016-2

computer-organization

Copyright GATE Overflow. All rights reserved.

pipeline

normal

numerical-answers

GATE Overflow

April 2016

366 of 1876

Selected Answer

Answer is 4 GHz.
Given 3 stage pipeline , with 3 GHz processor.
Given , e 1 = 3 e 2 / 4 = 2 e 3
Put e1 = 6x
we get, e2 = 8x , e 3 = 3x

Now largest stage time is 8x.


So, frequency is

1
8x

=> 8x = 3 GHz
1

=> x = 24 GHz ---------(1)


Now, we divide e 2 into two stages of 4x & 4x.
New processor has 4 stages 6x , 4x, 4x, 3x.
Now largest stage time is 6x.
So, new frequency is
1
6x

24

= 6 = 4 GHz (Ans)

------- from (1)


4 votes

-- Himanshu Agarwal ( 8861 points)

ANS.4
2 votes

-- ajit ( 1369 points)

t1=a , t2=b , t3=c


a=3b/4=2c
a=3b/4 , 3b/4=2c
a:b = 3:4 , b:c = 8:3
make b same for both..multiply 3:4 with 2
we will get a=6x , b=8x , c=3x
1/8x=3Ghz say p1
8x stage is divided into 2 stages with same latency..4x and 4x
new pipeline having 6x,4x,4x,3x
1/6x=Y say p2
By solving P1 and P2 ans should be ...4Ghz
1 votes

3.60 Computer Organization: GATE 2016-2-50 top


Copyright GATE Overflow. All rights reserved.

-- Gabbar ( 469 points)

gateoverflow.in/39592

GATE Overflow

April 2016

367 of 1876

A file system uses an in-memory cache to cache disk blocks. The miss rate of the cache is shown in the figure. The latency
to read a block from the cache is 1 ms and to read a block from the disk is 10 ms. Assume that the cost of checking whether
a block exists in the cache is negligible. Available cache sizes are in multiples of 10 MB.

The smallest cache size required to ensure an average read latency of less than 6 ms is _________ MB.



gate2016-2

computer-organization

Selected Answer

Ans =>30 MB
How ?

Copyright GATE Overflow. All rights reserved.

cache-memory

normal

numerical-answers

GATE Overflow

April 2016

368 of 1876

-- Akash ( 26265 points)

8 votes

30 MB
-- Ashish Deshmukh ( 1229 points)

3 votes

Tavg=H(1ms) + (1-H)(10ms)
6ms=H(1ms) + (1-H)(10ms)
if u solved u will get H=4/9
but in graph they have given miss rate(%)
so miss rate approx 55% if u increase miss rate it is not possibe to get 6ms
so ans should be 30MB since if u achieve ur goal with 55% miss rate definately possible with 40% miss rate
-- Gabbar ( 469 points)

1 votes

3.61 Computer Organization: GATE 2016-1-09 top

gateoverflow.in/39632

A processor can support a maximum memory of 4GB, where the memory is word-addressable (a word consists of two bytes).
The size of address bus of the processor is at least _________bits.
gate2016-1

computer-organization

Copyright GATE Overflow. All rights reserved.

easy

numerical-answers

GATE Overflow

April 2016

369 of 1876

Selected Answer

Size of Memory = No of words (Addresses) No of bits per word


232B = No of words (Addresses) 2B
No of words (Addresses) = 231
Number of Address lines = 31
-- Praveen Saini ( 34297 points)

12 votes

Max memory = 4 GB = 2 32 Bytes since 1 word=2B.. total number of words=2 32 /2=231 .. so to address these words we
need minimum 31 bit address bus
-- Abhilash Panicker ( 6507 points)

7 votes

3.62 Computer Organization: GATE2005_69 top

gateoverflow.in/1392

A device with data transfer rate 10 KB/sec is connected to a CPU. Data is transferred byte-wise. Let the interrupt overhead
be 4sec. The byte transfer time between the device interface register and CPU or memory is negligible. What is the
minimum performance gain of operating the device under interrupt mode over operating it under program-controlled mode?

A. 15
B. 25
C. 35
D. 45

gate2005

computer-organization

Selected Answer

In Programmed I/O, the CPU issues a command and waits for I/O operations to complete.
So here, CPU will wait for 1sec to transfer 10KB of data.
overhead in programmed I/O = 1 sec
In Interrupt mode , data is transferred word by word (here word size is 1 byte as mentioned in question "Data is
transferred byte-wise").
So to transfer 1 byte of data overhead is 4 10 6 sec
Thus to transfer 10 KB of data overhead is= 4 10 6 104 sec
1

6
4
2
Performance gain = 4 10 10 = 4x10 = 25

Thus, (b) is correct answer.


8 votes

3.63 Data Dependencies: GATE2015-3_47 top

-- ashwini anand ( 289 points)

gateoverflow.in/8556

Consider the following code sequence having five instructions from I1 to I5 . Each of these instructions has the following
format.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

370 of 1876

OP Ri, Rj, Rk
Where operation OP is performed on contents of registers Rj and Rk and the result is stored in register Ri.
I1 : ADD R1, R2, R3
I2 : MUL R7, R1, R3
I3 : SUB R4, R1, R5
I4 : ADD R3, R2, R4
I5 : MUL R7, R8, R9
Consider the following three statements.
S1: There is an anti-dependence between instructions I2 and I5
S2: There is an anti-dependence between instructions I2 and I4
S3: Within an instruction pipeline an anti-dependence always creates one or more stalls
Which one of the above statements is/are correct?

A. Only S1 is true
B. Only S2 is true
C. Only S1 and S3 are true
D. Only S2 and S3 are true
gate2015-3

co&architecture

pipeline

data-dependencies

normal

Selected Answer

Answer should be B.
Anti-dependence can be overcome in pipeline using register renaming. So, "always" in S3 makes it false. Also, if I2 is
completed before I4 (execution stage of MUL), then also there won't be any stall.
-- ppm ( 549 points)

10 votes

3.64 Data Dependencies: GATE2007-IT_39 top

gateoverflow.in/3472

Data forwarding techniques can be used to speed up the operation in presence of data dependencies. Consider the following
replacements of LHS with RHS.
R1 Loc, Loc
R1 R2, R1
(i)

R2
Loc
R1 Loc, Loc
(ii)

R1 R2
R2
R1 Loc, R2
(iii)

R1 Loc
Loc
R1 Loc, R2
(iv)

R1 Loc
Loc
In which of the following options, will the result of executing the RHS be the same as executing the LHS irrespective of the
instructions that follow ?

A)
B)
C)
D)
gate2007-it

(i) and (iii)


(i) and (iv)
(ii) and (iii)
(ii) and (iv)

data-dependencies

(iii) and (iv) are the same!! and both are wrong because R2 is writing last, not R1..

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

371 of 1876

(i) is true...
(ii) false, because R2 get the correct data, but location has not got updated..

No option.. (bonus marks :D)
-- Vicky Bajoria ( 3147 points)

1 votes

3.65 Data Path: GATE2001_2.13 top

gateoverflow.in/731

Consider the following data path of a simple non-pipelined CPU. The registers A, B, A 1, A 2, MDR, the bus and the ALU are 8bit wide. SP and MAR are 16-bit registers. The MUX is of size 8 (2:1) and the DEMUX is of size 8 (1:2). Each memory
operation takes 2 CPU clock cycles and uses MAR (Memory Address Register) and MDR (Memory Date Register). SP can be
decremented locally.

The CPU instruction "push r" where, r = A or B has the specification


M[SP] r
SP SP - 1
How many CPU clock cycles are required to execute the "push r" instruction?

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

gate2001

co&architecture

data-path

answer = option B
3 cycles are required

Copyright GATE Overflow. All rights reserved.

machine-instructions

normal

GATE Overflow

April 2016

1 votes

3.66 Data Path: GATE2005-80 top

372 of 1876

-- Amar Vashishth ( 17735 points)

gateoverflow.in/43568

The ALU, the bus and all the registers in the data path are of identical size. All operations including incrementation of the PC
and the GPRs are to be carried out in the ALU. Two clock cycles are needed for memory read operation the first one for
loading address in the MAR and the next one for loading data from the memory bus into the MDR.

The instruction "call Rn, sub is a two word instruction. Assuming that PC is incremented during the fetch cycle of the first
word of the instruction, its register transfer interpretation is
Rn <= PC + 1;

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

373 of 1876

PC <= M[PC];
The minimum number of CPU clock cycles needed during the execution cycle of this instruction is:
A. 2
B. 3
C. 4
D. 5
co&architecture

normal

gate2005

data-path

machine-instructions

Rn <= Pc+1
Pc<= M[Pc]
The sequence of instruction take place


I Cycle : PC out , Sin , MAR in (MAR can be loaded with PCout
II Cycle: S out , ALUincrement , R n in
III Cycle: MDRout , PC in (MDRout can be performed once MARin has been performed) therefore 3 cycle required


-- Umang Raman ( 10379 points)

0 votes

3.67 Data Path: GATE2005-79 top

gateoverflow.in/1402

Consider the following data path of a CPU.


The ALU, the bus and all the registers in the data path are of identical size. All operations including incrementation of the PC
and the GPRs are to be carried out in the ALU. Two clock cycles are needed for memory read operation the first one for
loading address in the MAR and the next one for loading data from the memory bus into the MDR.
The instruction add R0, R1 has the register transfer interpretation R0 <= R0 + R1. The minimum number of clock cycles
needed for execution cycle of this instruction is:
A. 2
B. 3
C. 4
D. 5
gate2005

co&architecture

machine-instructions

data-path

normal

S <- R0 ...... 1cycle ( Since the buses are of same size as the
T <- R1 ...... 2nd cycle
R0 <- R0 + R1 ..... 3rd cycle
therefore we need 3 cycles.
5 votes

Copyright GATE Overflow. All rights reserved.

-- Riya Roy ( 4769 points)

GATE Overflow

April 2016

374 of 1876

R0 <= R0 +R1
The sequence of instruction take place
I Cycle : R1 out , Sin
II Cycle: Ro out , Tin
III Cycle: Sout , Tout , ALU , R in therefore 3 cycle required

-- Umang Raman ( 10379 points)

2 votes

3.68 Data Path: GATE 2016-2-30 top

gateoverflow.in/39627

Suppose the functions F and G can be computed in 5 and 3 nanoseconds by functional units U F and U G, respectively. Given
two instances of U F and two instances of U G, it is required to implement the computation F(G(Xi)) for 1 i 10. Ignoring all
other delays, the minimum time required to complete this computation is ____________ nanoseconds.
gate2016-2

co&architecture

data-path

normal

numerical-answers

Selected Answer

The same concept is used in pipelining. Bottleneck here is U F as it takes 5 ns while U G takes 3ns only. We have to do 10
such calculations and we have 2 instances of U F and U G respectively. So, U F can be done in 50/2 = 25 nano seconds. For the
start U F needs to wait for U G output for 3 ns and rest all are pipelined and hence no more wait. So, answer is
3 + 25 = 28ns.
13 votes

-- Arjun Suresh ( 124085 points)

This is pipeline concept


two unit says we have to pipelines with same functionality.we can start both of them at same time.
Lets distribute i's values 1 to 5 for pipeline1...6 to 10 for pipeline2...
T1=(3+5)+(4*5)=28=T2
T1=Time required for pipeline1
T2=Time required for pipeline2
Parallel running so answer should be 28.
1 votes

3.69 Dma: GATE2011_28 top

-- Gabbar ( 469 points)

gateoverflow.in/2130

On a non-pipelined sequential processor, a program segment, which is the part of the interrupt service routine, is given to
transfer 500 bytes from an I/O device to memory.

LOOP:

Initialize the address register


Initialize the count to 500
Load a byte from device
Store in memory at address given by address register
Increment the address register
Decrement the count
If count !=0 go to LOOP

Assume that each statement in this program is equivalent to a machine instruction which takes one clock cycle to execute if

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

375 of 1876

it is a non-load/store instruction. The load-store instructions take two clock cycles to execute.
The designer of the system also has an alternate approach of using the DMA controller to implement the same transfer. The
DMA controller requires 20 clock cycles for initialization and other overheads. Each DMA transfer cycle takes two clock cycles
to transfer one byte of data from the device to the memory.
What is the approximate speed up when the DMA controller based design is used in a place of the interrupt driven program
based input-output?
(A) 3.4
(B) 4.4
(C) 5.1
(D) 6.7

gate2011

co&architecture

dma

normal

Selected Answer

STATEMENT
Initialize the address register
Initialize the count to 500
LOOP: Load a byte from device
Store in memory at address given by address register
Increment the address register
Decrement the count
If count != 0 go to LOOP

CLOCK CYCLE(S) NEEDED


1
1
2
2
1
1
1

Interrrupt driven transfer time = 1+1+500(2+2+1+1+1) = 3502


DMA based transfer time = 20+500*2 = 1020
Speedup = 3502/1020 = 3.4

-- Manu Thakur ( 5261 points)

12 votes

3.70 Dma: GATE 2016-1-31 top

gateoverflow.in/39698

The size of the data count register of a DMA controller is 16bits. The processor needs to transfer a file of 29,154 kilobytes
from disk to main memory. The memory is byte addressable. The minimum number of times the DMA controller needs to get
the control of the system bus from the processor to transfer the file from the disk to main memory is _________-.

gate2016-1

co&architecture

dma

normal

numerical-answers

Selected Answer

Data count register gives the number of words the DMA can transfer in a single cycle..
Here it is 16 bits.. so max 216 words can be transferred in one cycle.. since memory is byte addressable..
1 word = 1 byte
so 216 bytes in 1 cycle..
Now for the given file..
File size =29154KB=29154 * 210 B
in 1 cylce => DMA transfers 216 B
i.e
1 B transfered by DMA=> 1/216 cycles.
Now for full file of size 29154 KB, minimum number of cylces = (29154 * 2 10 B) / 216 = 455.53
but number of cylces is asked so 455.53 => 456..

4 votes

Copyright GATE Overflow. All rights reserved.

-- Abhilash Panicker ( 6507 points)

GATE Overflow

April 2016

376 of 1876

minimum 456
-- Shreyans Dhankhar ( 2265 points)

4 votes

3.71 Hardwired Controller: GATE1991-07a top

gateoverflow.in/533

It is required to design a hardwired controller to handle the fetch cycle of a single address CPU with a 16 bit instructionlength. The effective address of an indexed instruction should be derived in the fetch cycle itself. Assume that the lower
order 8 bits of an instruction constitute the operand field.
Give the register transfer sequence for realizing the above instruction fetch cycle.
gate1991

co&architecture

control-unit

hardwired-controller

normal

3.72 Hardwired Controller: GATE1991-07b top

gateoverflow.in/43606

It is required to design a hardwired controller to handle the fetch cycle of a single address CPU with a 16 bit instructionlength. The effective address of an indexed instruction should be derived in the fetch cycle itself. Assume that the lower
order 8 bits of an instruction constitute the operand field.
Draw the logic schematic of the hardwired controller including the data path.
gate1991

co&architecture

control-unit

hardwired-controller

normal

3.73 Instruction Format: GATE1992_01,vi top

gateoverflow.in/551

In an 11-bit computer instruction format, the size of address field is 4-bits. The computer uses expanding OP code technique
and has 5 two-address instructions and 32 one-address instructions. The number of zero-address instructions it can support
is ________

gate1992

co&architecture

machine-instructions

instruction-format

normal

Selected Answer

No. of possible instruction encoding = 211 = 2048


No. of encoding taken by two-address instructions = 5 24 24 = 1280
No. of encoding taken by one-address instructions = 32 24 = 512
So, no. of possible zero-address instructions = 2048 (1280 + 512) = 256
-- Arjun Suresh ( 124085 points)

9 votes

3.74 Instruction Format: GATE 2016-2-31 top

gateoverflow.in/39601

Consider a processor with 64 registers and an instruction set of size twelve. Each instruction has five distinct fields, namely,
opcode, two source register identifiers, one destination register identifier, and twelve-bit immediate value. Each instruction
must be stored in memory in a byte-aligned fashion. If a program has 100 instructions, the amount of memory (in bytes)
consumed by the program text is _________.
gate2016-2

instruction-format

machine-instructions

Selected Answer

Answer => 500 bytes


How =>

Copyright GATE Overflow. All rights reserved.

computer-organization

normal

numerical-answers

GATE Overflow

April 2016

377 of 1876

-- Akash ( 26265 points)

7 votes

Each instruction needs 34 bits. Question is asking for byte alignment, so, every instruction will need 40 bits (5 bytes).
So, total 5B x 100 = 500 Bytes will be needed.
-- Ashish Deshmukh ( 1229 points)

3 votes

3.75 Instruction Format: GATE2014-1_9 top

gateoverflow.in/1767

A machine has a 32-bit architecture, with 1-word long instructions. It has 64 registers, each of which is 32 bits long. It needs to support 45 instructions, which
have an immediate operand in addition to two register operands. Assuming that the immediate operand is an unsigned integer, the maximum value of the
immediate operand is ____________

gate2014-1

co&architecture

machine-instructions

instruction-format

numerical-answers

normal

Selected Answer

64 registers means 6 bits for a register operand. So, 2 register operand requires 12 bits. Now, 45 instructions require
another 6 bits for opcode. So, totally 18 bits. So, we have 32 - 18 = 14 bits left for the immediate operand. So, the max
value will be 214 - 1 = 16383 (as the operand is unsigned we don't need a sign bit and with 14 bits we can represent from
0 to 2 14 -1)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

378 of 1876
-- Arjun Suresh ( 124085 points)

11 votes

3.76 Instruction Format: GATE1994_3.2 top

gateoverflow.in/2479

State True or False with one line explanation


Expanding opcode instruction formats are commonly employed in RISC. (Reduced Instruction Set Computers) machines.
gate1994

co&architecture

machine-instructions

instruction-format

normal

Selected Answer

FALSE
This expanding opcode scheme makes the decoding more complex. Instead of simply looking at a bit pattern and deciding
which instruction it is, we need to decode the instruction something like this:
if (leftmost four bits != 1111 ) {
Execute appropriate three-address instruction}
else if (leftmost seven bits != 1111 111 ) {
Execute appropriate two-address instruction}
else if (leftmost twelve bits != 1111 1111 1111 ) {
Execute appropriate one-address instruction }
else {
Execute appropriate zero-address instruction
}

At each stage, one spare code is used to indicate that we should now look at more bits. This is another example of the
types of trade-offs hardware designers continually face: Here, we trade opcode space for operand space.
Ref: http://www.fatih.edu.tr/~emanetn/courses/spring2006/ceng252/ceng252_lecture3.pdf
Being more complex and RISC not needing more instructions expanding opcode is not a common RISC technique. But this
is there in many RISC machines.
-- Arjun Suresh ( 124085 points)

0 votes

3.77 Interrupts: GATE2007-73 top


Consider the following program segment. Here R1, R2 and R3 are the general purpose registers.

Instruction

Operation

MOV R1, (3000) R1 m[3000]

Instruction
size (no. of
words)
2

LOOP: MOV R2, (R3)

R2 M[R3]

ADD R2, R1

R2 R1 + R2

MOV (R3), R2

M[R3] R2

INC R3

R3 R3 +1

DEC R1

R1 R1 - 1

BNZ LOOP

Branch on not zero

HALT

Stop

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/43516

GATE Overflow

April 2016

379 of 1876

Assume that the content of memory location 3000 is 10 and the content of the register R3 is 2000. The content of each of
the memory locations from 2000 to 2010 is 100. The program is loaded from the memory location 1000. All the numbers are
in decimal.
Assume that the memory is byte addressable and the word size is 32 bits. If an interrupt occurs during the execution of the
instruction INC R3, what return address will be pushed on to the stack?
A. 1005
B. 1020
C. 1024
D. 1040
gate2007

co&architecture

machine-instructions

interrupts

normal

Selected Answer

An interrupt is checked for after the execution of the current instruction and the contents of PC (address of next
instruction to be executed) is pushed on to stack. Here, address of INC, R3 = 1000 + (2 + 1 + 1 + 1) 32/8 = 1020 and next
instruction address = 1020 + 4 = 1024 which is pushed on to stack.
Ref: http://www.ece.utep.edu/courses/web3376/Notes_files/ee3376-interrupts_stack.pdf
-- Vicky Bajoria ( 3147 points)

1 votes

3.78 Interrupts: GATE2007-72 top

gateoverflow.in/43515

Consider the following program segment. Here R1, R2 and R3 are the general purpose registers.
Instruction
size (no. of
words)

Instruction

Operation

MOV R1, (3000) R1 m[3000]

LOOP: MOV R2, (R3)

R2 M[R3]

ADD R2, R1

R2 R1 + R2

MOV (R3), R2

M[R3] R2

INC R3

R3 R3 +1

DEC R1

R1 R1 - 1

BNZ LOOP

Branch on not zero

HALT

Stop

Assume that the content of memory location 3000 is 10 and the content of the register R3 is 2000. The content of each of
the memory locations from 2000 to 2010 is 100. The program is loaded from the memory location 1000. All the numbers are
in decimal.
Assume that the memory is word addressable. After the execution of this program, the content of memory location 2010 is:
A. 100
B. 101
C. 102
D. 110
gate2007

co&architecture

machine-instructions

Copyright GATE Overflow. All rights reserved.

interrupts

normal

GATE Overflow

April 2016

380 of 1876

Selected Answer

The loop is executed 10 times and it modifies the contents from memory location 2000-2009. Memory location 2010 is
untouched - contains 100 as before.
-- Vicky Bajoria ( 3147 points)

1 votes

3.79 Interrupts: GATE1998_1.20 top

gateoverflow.in/1657

Which of the following is true?


A. Unless enabled, a CPU will not be able to process interrupts.
B. Loop instructions cannot be interrupted till they complete.
C. A processor checks for interrupts before executing a new instruction.
D. Only level triggered interrupts are possible on microprocessors.

gate1998

co&architecture

interrupts

normal

Ans is A.
Options B and D is obviously false.
A processor checks for the interrupt before FETCHING an instruction, So Option C is also false.
-- Hardi Shah ( 107 points)

2 votes

3.80 Interrupts: GATE1995_1.3 top

gateoverflow.in/2590

In a vectored interrupt
A. The branch address is assigned to a fixed location in memory
B. The interrupting source supplies the branch information to the processor through an interrupt vector
C. The branch address is obtained from a register in the processor
D. None of the above

gate1995

co&architecture

interrupts

normal

Selected Answer

Answer: B
A vectored interrupt is a processing technique in which the interrupting device directs the processor to the appropriate
interrupt service routine. This is in contrast to a polled interrupt system, in which a single interrupt service routine must
determine the source of the interrupt by checking all potential interrupt sources, a slow and relatively laborious process.
2 votes

-- Rajarshi Sarkar ( 27781 points)

ans is B
1 votes

Copyright GATE Overflow. All rights reserved.

-- jayendra ( 5797 points)

GATE Overflow

April 2016

3.81 Interrupts: GATE2007-71 top

381 of 1876

gateoverflow.in/1269

Consider the following program segment. Here R1, R2 and R3 are the general purpose registers.

Instruction

Operation


LOOP:





MOV R1, (3000)


MOV R2, (R3)
ADD R2, R1
MOV (R3), R2
INC R3
DEC R1
BNZ LOOP
HALT

R1 m[3000]
R2 M[R3]
R2 R1 + R2
M[R3] R2
R3 R3 +1
R1 R1 - 1
Branch on not zero
Stop

Instruction
size (no. of
words)
2
1
1
1
1
1
2
1

Assume that the content of memory location 3000 is 10 and the content of the register R3 is 2000. The content of each of
the memory locations from 2000 to 2010 is 100. The program is loaded from the memory location 1000. All the numbers are
in decimal.
Assume that the memory is word addressable. The number of memory references for accessing the data in executing the
program completely is
A. 10
B. 11
C. 20
D. 21

gate2007

co&architecture

machine-instructions

interrupts

normal

Selected Answer

Loop is executed 10 times and there are two memory reference in the loop (each MOV is loading 1 word, so 1 memory
reference for each MOV inside the loop). So number of memory reference inside loop is 2 (MOV) * 10 ( times iteration) *
1 ( 1 word access/ MOV) = 20 memory accesses.
-- Vicky Bajoria ( 3147 points)

4 votes

3.82 Interrupts: GATE2002_1.9 top

gateoverflow.in/813

A device employing INTR line for device interrupt puts the CALL instruction on the data bus while

A. INTA is active
B. HOLD is active
C. READY is inactive
D. None of the above
gate2002

co&architecture

interrupts

normal

INTR is a signal which if enabled then microprocessor has interrupt enabled it receives high INR signal & activates INTA
signal, so another request cant be accepted till CPU is busy in servicing interrupt. Hence (A) is correct option.
1 votes

3.83 Interrupts: GATE2009_8 top


A CPU generally handles an interrupt by executing an interrupt service routine

A. As soon as an interrupt is raised.

Copyright GATE Overflow. All rights reserved.

-- Tejas Jaiswal ( 461 points)

gateoverflow.in/1300

GATE Overflow

April 2016

382 of 1876

B. By checking the interrupt register at the end of fetch cycle.


C. By checking the interrupt register after finishing the execution of the current instruction.
D. By checking the interrupt register at fixed time intervals.

gate2009

co&architecture

interrupts

normal

Selected Answer

It will be C.
After finishing the execution of each instruction the CPU reads the interrupt pins to recognize the interrupts.
INTR = 1 = Interrupt is present.(Service the Interrupt)
= 0 = Interrupt is not present.(Goto next Instruction fetch from user program)
-- Gate Keeda ( 16619 points)

3 votes

3.84 Interrupts: GATE1992-05,b top

gateoverflow.in/31576

Three devices A, B and C are corrected to the bus of a computer, input/output transfers for all three devices use interrupt
control. Three interrupt request lines INTR1, INTR2 and INTR3 are available with priority of INTR1 > priority of INTR2 >
priority of INTR3. Draw a schematic of the priority logic, using an interrupt mask register, in which Priority of A > Priority of
B > Priority of C.

gate1992

co&architecture

interrupts

normal

3.85 Io Handling: GATE1996_25 top

gateoverflow.in/2777

A hard disk is connected to a 50 MHz processor through a DMA controller. Assume that the initial set-up of a DMA transfer
takes 1000 clock cycles for the processor, and assume that the handling of the interrupt at DMA completion requires 500
clock cycles for the processor. The hard disk has a transfer rate of 2000 Kbytes/sec and average block transferred is 4 K
bytes. What fraction of the processor time is consumed by the disk, if the disk is actively transferring 100% of the time?

gate1996

computer-organization

io-handling

dma

normal

30 us for initialisation and termination and 2 ms for data transfer


Cpu time is consumed only for initialisation and termination
% of cpu time consumed =30us/(30us+2ms)*100=1.5%

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

383 of 1876

-- Pooja ( 22745 points)

4 votes

3.86 Io Handling: GATE2008_64 top

gateoverflow.in/487

Which of the following statements about synchronous and asynchronous I/O is NOT true?

A. An ISR is invoked on completion of I/O in synchronous I/O but not in asynchronous I/O
B. In both synchronous and asynchronous I/O, an ISR (Interrupt Service Routine) is invoked after completion of the I/O
C. A process making a synchronous I/O call waits until I/O is complete, but a process making an asynchronous I/O call
does not wait for completion of the I/O
D. In the case of synchronous I/O, the process waiting for the completion of I/O is woken up by the ISR that is invoked
after the completion of I/O

gate2008

operating-system

io-handling

normal

Selected Answer

Answer is (B).
In synchronous I/O process performing I/O operation will be placed in blocked state till the I/O operation is completed. An
ISR will be invoked after the completion of I/O operation and it will place process from block state to ready state.
In asynchronous I/O, Handler function will be registered while performing the I/O operation. The process will not be placed
in the block state and process continues to execute the remaining instructions. when the I/O operation completed signal
mechanism is used to notify the process that data is available.
-- gate_asp ( 483 points)

5 votes

3.87 Io Handling: GATE1996_1.24 top

gateoverflow.in/2728

For the daisy chain scheme of connecting I/O devices, which of the following statements is true?
A. It gives non-uniform priority to various devices
B. It gives uniform priority to all devices
C. It is only useful for connecting slow devices to a processor device
D. It requires a separate interrupt pin on the processor for each device

gate1996

co&architecture

io-handling

normal

Selected Answer

daisy chaining approach tell the processor i which order the interrupt should be handled by providing priority to the
devices .
In daisy chaining method all the devices are connected in serial. The device with the highest priority is placed in the first position, followed by lower
priority devices . interrupt pin is common to all
so answer is a
6 votes

3.88 Io Organization: GATE2005 top


Copyright GATE Overflow. All rights reserved.

-- Ravi Singh ( 7303 points)

gateoverflow.in/33006

GATE Overflow

April 2016

384 of 1876

Consider a disk drive with the following specifications:


16 surfaces, 512 tracks/surface, 512 sectors/track, 1 KB/sector, rotation speed 3000 rpm. The disk is operated in cycle
stealing mode whereby whenever one 4 byte word is ready it is sent to memory; similarly, for writing, the disk interface
reads a 4 byte word from the memory in each DMA cycle. Memory cycle time is 40 nsec. The maximum percentage of time
that the CPU gets blocked during DMA operation is____________
co&architecture

io-organization

dma

3.89 Machine Instructions: GATE2004-63 top

gateoverflow.in/1058

Consider the following program segment for a hypothetical CPU having three user registers R1, R2 and R3.
Instruction

Operation

MOV R1, 5000


MOV R2(R1)
ADD R2, R3
MOV 6000, R2

R1 Memory[5000]
R2 Memory[(R1)]
R2 R2 + R3
Memory[6000] R2

Instruction
(in words)
2
1
1
2

HALT

Machine halts

Size

Consider that the memory is byte addressable with size 32 bits, and the program has been loaded starting from memory
location 1000 (decimal). If an interrupt occurs while the CPU has been halted after executing the HALT instruction, the return
address (in decimal) saved in the stack will be

A. 1007
B. 1020
C. 1024
D. 1028
gate2004

co&architecture

machine-instructions

normal

Selected Answer

63. Word size is 32 bits (4 bytes). Interrupt occurs after execution of HALT instruction NOT during, So address of next
instruction will be saved on to the stack which is 1028. (We have 5 instructions starting from address 1000, each of size
2, 1, 1, 2, 1 totaling 7 words = 28 bytes).
After HALT instruction CPU enters a HALT state and if an interrupt happens the return address will be that of the
instruction after the HALT. Ref http://x86.renejeschke.de/html/file_module_x86_id_134.html
option D
7 votes

-- Vikrant Singh ( 10051 points)

3.90 Machine Instructions: GATE1994_12 top

gateoverflow.in/2508


a. Assume that a CPU has only two registers R1 and R2 and that only the following instruction is available
XOR Ri, Rj; {Rj Ri Rj, for i, j = 1, 2}
Using this XOR instruction, find an instruction sequence in order to exchange the contents of the registers R1 and R2
b. The line p of the circuit shown in figure has stuck at 1 fault. Determine an input test to detect the fault.

Copyright GATE Overflow. All rights reserved.

GATE Overflow
gate1994

April 2016

co&architecture

machine-instructions

385 of 1876

normal

Selected Answer

(a)
R2  R1 R2
R1  R2 R1
R2  R1 R2
(b) A=1, B=1, C=1 should give output as 1 but as p is struck at 1 fault the output comes out to be 0.
-- Rajarshi Sarkar ( 27781 points)

3 votes

3.91 Machine Instructions: GATE 2016-2-10 top

gateoverflow.in/39547

A processor has 40 distinct instruction and 24 general purpose registers. A 32-bit instruction word has an opcode, two
registers operands and an immediate operand. The number of bits available for the immediate operand field is_______.
gate2016-2

machine-instructions

computer-organization

easy

numerical-answers

Selected Answer

Instruction Opcode Size => log 2 40 => 6


Register operand size = log 224 =>5
Total bits available => 32
Bits required for opcode + two register operands => 6 + 2 * 5 => 16
Bits available for immediate operand => 32 - 16 = 16 !
-- Akash ( 26265 points)

5 votes

16 bits
-- ajit ( 1369 points)

3 votes

3.92 Machine Instructions: GATE2008-IT_38 top

gateoverflow.in/3348

Assume that EA = (X)+ is the effective address equal to the contents of location X, with X incremented by one word length
after the effective address is calculated; EA = (X) is the effective address equal to the contents of location X, with X
decremented by one word length before the effective address is calculated; EA = (X) is the effective address equal to the
contents of location X, with X decremented by one word length after the effective address is calculated. The format of the
instruction is (opcode, source, destination), which means (destination source op destination). Using X as a stack pointer,
which of the following instructions can pop the top two elements from the stack, perform the addition operation and push
the result back to the stack.

A)
B)
C)
D)
gate2008-it

ADD (X), (X)


ADD (X), (X)
ADD (X), (X)+
ADD (X), (X)

co&architecture

machine-instructions

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

386 of 1876

I think it should be A as 998<-1000+998.(i am writing only memory locations for sake of brevity).lets say sp is 1000 initially then after it calculates the EA of source(which is 1000 as it
decrements after the EA) the destination becomes 998 and that is where we want to store the result as stack is decrementing...in case of C and D it becomes 998<-998+998

-- Shaun Patel ( 5445 points)

5 votes

Answer is A :- We can also write this statement like that


for option
X = ( X - -) + X
----------------------------> execution.
X = top + X ( decrement the pointer )
X = top + top -1
(top-1) = top + ( top -1)
-- Arpit Dhuriya ( 1791 points)

1 votes

3.93 Machine Instructions: GATE2008_34 top

gateoverflow.in/445

Which of the following must be true for the RFE (Return From Exception) instruction on a general purpose processor?
I. It must be a trap instruction
II. It must be a privileged instruction
III. An exception cannot be allowed to occur during execution of an RFE instruction

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

gate2008

co&architecture

machine-instructions

normal

RFE (Return From Exception) is a privileged trap instruction that is executed when exception occurs, so an exception is not allowed to
execute. (D) is the correct option.
Ref: http://www.cs.rochester.edu/courses/252/spring2014/notes/08_exceptions
-- Vikrant Singh ( 10051 points)

3 votes

I am sure about the 2nd but have slight confusion about the first one. All the privileged instructions cause trap instructions
when executing under user mode, but I think when executing under kernel mode they do not cause any trap(as they
meant to run there) and hence Return from exception is not a trap...so should be only B
-- Shaun Patel ( 5445 points)

1 votes

3.94 Machine Instructions: GATE2007-IT_41 top

gateoverflow.in/3476

Following table indicates the latencies of operations between the instruction producing the result and instruction using the
result.
Instruction
the result

Copyright GATE Overflow. All rights reserved.

producing Instruction using the


Latency
result

ALU Operation
ALU Operation

ALU operation
Store

2
2

Load

ALU Operation

GATE Overflow

April 2016
Load
Instruction
the result

387 of 1876

Store
0
producing Instruction using the
Latency
result

Consider the following code segment.


Load R1, Loc 1; Load R1 from memory location Loc1
Load R2, Loc 2; Load R2 from memory location Loc 2
Add R1, R2, R1; Add R1 and R2 and save result in R1
Dec R2; Decrement R2
Dec R1; Decrement R1
Mpy R1, R2, R3; Multiply R1 and R2 and save result in R3
Store R3, Loc 3; Store R3 in memory location Loc 3

What is the number of cycles needed to execute the above code segment assuming each instruction takes one cycle to
execute ?
A)
B)
C)
D)
gate2007-it

7
10
13
14

co&architecture

machine-instructions

normal

Selected Answer

Answer is (C)
Here each instruction takes 1 cycle but apart from that we have to consider latencies b/w instruction: If there are two ALU operations by I1 and
I2 such that I2 uses the value produced by I1 in some register then I2 will be executed ONLY after waiting TWO more cycles after I1 has executed
because latency b/w two ALU operations is 2
See here:
Clock 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Inst. I1 I2 - I3 I4 - I5 - - I6 - - I7


I3 is ALU operation which uses result of LOAD in I2 , so latency is of 1 cycle.
I5 is ALU operation using result of ALU in I3 therefore has to wait for 2 cycles after I3
I6 is ALU and uses result of ALU in I5 ,therefore waits 2 cycles


-- Sandeep_Uniyal ( 5063 points)

6 votes

3.95 Machine Instructions: GATE2003-49 top

gateoverflow.in/43577

Consider the following assembly language program for a hypothetical processor A, B, and C are 8 bit registers. The meanings
of various instructions are shown as comments.
MOV B, #0

;B 0

MOV C, #8

;C 8

Z: CMP C, #0

; compare C with 0

JZ X

; jump to X if zero flag is set

SUB C, #1

;C C 1

RRC A, #1

; right rotate A through carry by one bit. Thus:

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

; If the initial values of A and the carry flag are a7 . . a0 and

; c0 respectively, their values after the execution of this

; instruction will be c0 a7 . . a1 and a0 respectively.

JC Y

; jump to Y if carry flag is set

JMP Z

; jump to Z

Y: ADD B, #1

;B B + 1

JMP Z

; jump to Z

X:

388 of 1876


Which of the following instructions when inserted at location X will ensure that the value of the register A after program
execution is as same as its initial value?
A. RRC A, #1
B. NOP ; no operation
C. LRC A, #1; left rotate A through carry flag by one bit
D. ADD A, #1
gate2003

co&architecture

machine-instructions

normal

Selected Answer

49. A. RRC a, #1. As the 8 bit register is rotated via carry 8 times.
a7a6a5a4a3a2a1a0
c0a7a6a5a4a3a2a1, now a0 is the new carry. So, after next rotation,
a0c0a7a6a5a4a3a2
So, after 8 rotations,
a6a5a4a3a2a1a0c0 and carry is a7.
Now, one more rotation will restore the original value of A0.
-- Arjun Suresh ( 124085 points)

0 votes

3.96 Machine Instructions: GATE1999_17 top

gateoverflow.in/1516

Consider the following program fragment in the assembly language of a certain hypothetical processor. The processor has
three general purpose registers R1, R2 and R3. The meanings of the instructions are shown by comments (starting with ;)
after the instructions.
X:

CMP
JZ
MOV
SHR
SHL
CMP
JZ
INC
Y: SHR
JMP
Z:...

R1,
Z;
R2,
R1;
R1;
R2,
Y;
R3;
R1;
X;

0; Compare R1 and 0, set flags appropriately in status register


Jump if zero to target Z
R1; Copy contents of R1 to R2
Shift right R1 by 1 bit
Shift left R1 by 1 bit
R1; Compare R2 and R1 and set flag in status register
Jump if zero to target Y
Increment R3 by 1;
Shift right R1 by 1 bit
Jump to target X

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

389 of 1876

a. Initially R1, R2 and R3 contain the values 5, 0 and 0 respectively, what are the final values of R1 and R3 when control
reaches Z?
b. In general, if R1, R2 and R3 initially contain the values n, 0, and 0 respectively. What is the final value of R3 when
control reaches Z?

gate1999

co&architecture

machine-instructions

normal

Selected Answer

SHR R1 (Lower bit is lost and upper bit becomes 0 and all other bits shift right by 1)
SHL R1 (Upper bit is lost and lower bit becomes 0 and all other bits shift left by 1)
These two operations change the value of R1 if its lower bit is 1. So, the given program checks the lowest bit of R1 in each
iteration and if its 1 then only increment R3 and loop terminates when R1 becomes 0. Thus at end, R3 will have the count
of the number of bits set to 1 in R1.
a. R1 = 0, R3 = 2 as 101 has two 1's
b. R3 = #1 in R1.
-- Arjun Suresh ( 124085 points)

4 votes

3.97 Machine Instructions: GATE2006_09 top

gateoverflow.in/888

A CPU has 24-bit instructions. A program starts at address 300 (in decimal). Which one of the following is a legal program
counter (all values in decimal)?
(A) 400
(B) 500
(C) 600
(D) 700
gate2006

co&architecture

machine-instructions

easy

Selected Answer

Option c. 24 bit = 3 bytes instructions. So PC will have multiples of 3 in it.


-- anshu ( 2155 points)

3 votes

3.98 Machine Instructions: GATE2007_54 top


In a simplified computer the instructions are:
OP Rj, Ri

OP m, Ri

MOV m, Ri
MOV Ri, m

-Performs Rj OP Ri and stores the


result in register Rj.
-Performs val OP Ri and stores the
result in register Ri. val
denotes the content of the memory
location m.
-Moves the content of memory
location m to register Ri
-Moves the content of register Ri to
memory location m

The computer has only two registers, and OP is either ADD or SUB. Consider the following basic block:
t1 = a + b
t2 = c + d

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/1252

GATE Overflow

April 2016

390 of 1876

t3 = e t2
t4 = t1 t3
Assume that all operands are initially in memory. The final value of the computation should be in memory. What is the
minimum number of MOV instructions in the code generated for this basic block?

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


gate2007

co&architecture

machine-instructions

normal

Selected Answer

MOV a, R1
ADD b, R 1
MOV c, R2
ADD d, R 2
SUB e, R 2
SUB R 1, R 2
MOV R2, m
Total no. of MOV Instruction = 3

-- Gate Keeda ( 16619 points)

5 votes

3.99 Machine Instructions: GATE2003-48 top

gateoverflow.in/938

Consider the following assembly language program for a hypothetical processor A, B, and C are 8 bit registers. The meanings
of various instructions are shown as comments.
MOV B, #0
MOV C, #8
Z: CMP C, #0
JZ X
SUB C, #1
RRC A, #1

;B 0
;C 8
; compare C with 0
; jump to X if zero flag is set
;C C 1
; right rotate A through carry by one bit. Thus:
; If the initial values of A and the carry flag are a7 . . a0 and

; c0 respectively, their values after the execution of this

; instruction will be c0 a7 . . a1 and a0 respectively.

JC Y
JMP Z
Y: ADD B, #1
JMP Z
X:

; jump to Y if carry flag is set


; jump to Z
;B B + 1
; jump to Z


If the initial value of register A is A0 the value of register B after the program execution will be

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

391 of 1876

A. the number of 0 bits in A0


B. the number of 1 bits in A0
C. A0
D. 8
gate2003

co&architecture

machine-instructions

normal

Selected Answer

B. The code is counting the number of 1 bits in A0. When a 1 is moved to carry, B is incremented.
-- Arjun Suresh ( 124085 points)

7 votes

3.100 Machine Instructions: GATE2004-IT_46 top

gateoverflow.in/3689

If we use internal data forwarding to speed up the performance of a CPU (R1, R2 and R3 are registers and M[100] is a
memory reference), then the sequence of operations
R1 M[100]
M[100] R2
M[100] R3
can be replaced by

R1 R3
R2 M[100]
M[100] R2
R1 R2
R1 R3
R1 M[100]
R2 R3
R1 R2
R1 R3
R1 M[100]

A)
B)
C)
D)

gate2004-it

co&architecture

machine-instructions

easy

Selected Answer

Data forwarding means if CPU writes to a memory location and subsequently reads from the same memory location, the
second instruction can fetch the value directly from the register used to do the write than waiting for the memory. So,
this increases the performance.
Here, choices A, B and C doesn't really make any sense as the data was in R1 and it must be moved to R2, R3 and
M[100]. So, (D) is the answer.
4 votes

3.101 Machine Instructions: GATE2015-2_42 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/8215

Consider a processor with byte-addressable memory. Assume that all registers, including program counter (PC) and Program
Status Word (PSW), are size of two bytes. A stack in the main memory is implemented from memory location (0100)16 and it
grows upward. The stack pointer (SP) points to the top element of the stack. The current value of SP is (016E)16. The CALL
instruction is of two words, the first word is the op-code and the second word is the starting address of the subroutine (one
word = 2 bytes). The CALL instruction is implemented as follows:
Store the current value of PC in the stack
Store the value of PSW register in the stack
Load the statring address of the subroutine in PC
The content of PC just before the fetch of a CALL instruction is (5FA0)16. After execution of the CALL instruction, the value of

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

392 of 1876

the stack pointer is



A. (016A)16
B. (016C)16
C. (0170)16
D. (0172)16
gate2015-2

co&architecture

machine-instructions

easy

Selected Answer

first we have to consider here memory is byte-addressable


The CALL instruction is implemented as follows:


Store the current value of PC in the stack
pc is 2 byte it means when we store pc in stack it will increase by 2
so current value of SP is (016E)16 +2

Store the value of PSW register in the stack


psw is 2 byte it means when we store psw in stack it will increase by 2
so current value of SP is (016E)16 +2+2 =(0172)16

-- Anoop Sonkar ( 4167 points)

11 votes

3.102 Machine Instructions: GATE2004-64 top


Consider the following program segment for a hypothetical CPU having three user registers R1, R2 and R3.

Instruction

Operation

Instruction
(in words)

MOV R1, 5000

R1 Memory[5000]

MOV R2(R1)

R2 Memory[(R1)]

ADD R2, R3

R2 R2 + R3

MOV 6000, R2

Memory[6000] R2

HALT

Machine halts

Size

Let the clock cycles required for various operations be as follows:


Register to/from memory transfer

: 3 clock cycles

ADD with both operands in register : 1 clock cycle


Instruction fetch and decode

Copyright GATE Overflow. All rights reserved.

: 2 clock cycles per word

gateoverflow.in/43570

GATE Overflow

April 2016

393 of 1876

The total number of clock cycles required to execute the program is


A. 29
B. 24
C. 23
D. 20

gate2004

co&architecture

machine-instructions

normal

Selected Answer

64. B. 24 cycles
Instruction Size Fetch and Decode + Execute
mov
2
2*2 + 3 = 7
mov

2*1 + 3 = 5

add
mov

1
2

2*1 + 1 = 3
2*2 + 3 = 7

halt

2*1 + 0 = 2

Total 24 cycles


-- Vikrant Singh ( 10051 points)

1 votes

3.103 Memory Interfacing: Gate 2016 syllabus C.O. memory interface

gateoverflow.in/35673

top

Memory Interface topic has been removed. Can someone tell me what kind question will not be asked.
or what not to do in this section?
co&architecture

memory-interfacing

3.104 Memory Interfacing: GATE2006_41 top

gateoverflow.in/1817

A CPU has a cache with block size 64 bytes. The main memory has k banks, each bank being c bytes wide. Consecutive c
byte chunks are mapped on consecutive banks with wrap-around. All the k banks can be accessed in parallel, but two
accesses to the same bank must be serialized. A cache block access may involve multiple iterations of parallel bank accesses
depending on the amount of data obtained by accessing all the k banks in parallel. Each iteration requires decoding the bank
k

numbers to be accessed in parallel and this takes 2 ns.The latency of one bank access is 80 ns. If c = 2 and k = 24, the latency
of retrieving a cache block starting at address zero from main memory is:
(A) 92 ns
(B) 104 ns
(C) 172 ns
(D) 184 ns


gate2006

co&architecture

cache-memory

Copyright GATE Overflow. All rights reserved.

memory-interfacing

normal

GATE Overflow

April 2016

394 of 1876

Selected Answer

Cache block = 64 bytes.


Each bank in memory is 2 bytes and there are 24 such banks. So, in 1 iteration we can get 2*24 = 48 bytes and getting
64 bytes requires 2 iterations.
So, latency = k/2 + 80 + k/2 + 80 (since in each iteration we need to select the banks and the bank decoding time (k/2)
is independent of the number of banks we are going to access)
= 12 + 80 + 12 + 80 = 184 ns
But total memory capacity here is 2*24 = 48 bytes. What is the need of cache management and decoding mechanism?
-- Arjun Suresh ( 124085 points)

10 votes

3.105 Microprogramming: GATE2006-IT_41 top

gateoverflow.in/3584

The data path shown in the figure computes the number of 1s in the 32-bit input word corresponding to an unsigned even
integer stored in the shift register.
The unsigned counter, initially zero, is incremented if the most significant bit of the shift register is 1.

The microprogram for the control is shown in the table below with missing control words for microinstructions I 1, I 2, ..... I n.
Microinstruction reset_counter shift_left load_output
BEGIN

I1

:
In

END

The counter width (k) , the number of missing microinstructions (n), and the control word for microinstructions I 1, I 2, ..... I n
are, respectively,

A)
B)
C)
D)
gate2006-it

32, 5, 010
5, 32, 010
5, 31, 011
5, 31, 010

co&architecture

microprogramming

normal

As there can be maximum 32 ones in number so 5 bit counter is sufficient no of micro instructions required would be 32
we have to load output at end so control word would be 0 1 0 for all micro instructions so ans is b
3 votes

Copyright GATE Overflow. All rights reserved.

-- Pooja ( 22745 points)

GATE Overflow

April 2016

395 of 1876

For 32 instructions counter require 5 bits and we require 31 shift left operation.
and the instruction word would be 011 because for load_output=1 the counter value would be stored into the output.
so option (c).
-- Suvojit Mondal ( 423 points)

1 votes

3.106 Microprogramming: GATE1996_2.25 top

gateoverflow.in/2754

A micro program control unit is required to generate a total of 25 control signals. Assume that during any microinstruction,
at most two control signals are active. Minimum number of bits required in the control word to generate the required control
signals will be
A. 2
B. 2.5
C. 10
D. 12
gate1996

co&architecture

microprogramming

normal

Selected Answer

To generate 25 different control signals 5 bits are required....at any time atmost 2 signals are active..so control word
length=5+5=10 bits
-- aravind90 ( 599 points)

2 votes

3.107 Microprogramming: GATE2002_2.7 top

gateoverflow.in/837

Horizontal microprogramming

A. does not require use of signal decoders
B. results in larger sized microinstructions than vertical microprogramming
C. uses one bit for each control signal
D. all of the above

gate2002

co&architecture

microprogramming

Selected Answer

option (d). All statements are true.


Ref: http://www.cs.virginia.edu/~cs333/notes/microprogramming.pdf
8 votes

3.108 Microprogramming: GATE2005-IT_49 top

-- Suvojit Mondal ( 423 points)

gateoverflow.in/3810

An instruction set of a processor has 125 signals which can be divided into 5 groups of mutually exclusive signals as follows:
Group 1 : 20 signals, Group 2 : 70 signals, Group 3 : 2 signals, Group 4 : 10 signals, Group 5 : 23 signals.

How many bits of the control words can be saved by using vertical microprogramming over horizontal microprogramming?

A)
0
B)
103
C)
22

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

D)

396 of 1876

55

gate2005-it

co&architecture

microprogramming

normal

Selected Answer

In horizontal microprogramming we need 1 bit for every control word, therefore total bits in
Horizontal Microprogramming=20+70+2+10+23=125
Now lets consider vertical microprogramming, In vertical microprogramming we use Decoder (n to 2 n ) and output lines
are equal to number of control words . A input is given according to what control word we have to select.
Now in this question these 5 groups contains mutually exclusive signals, i.e, they can be activated one at a time for a
given group, we can safely use decoder.
group 1=  log 220=5 (Number of input bits for decoder, given output is number of control word in given group)
group 2=  log 270 =7
group 3=  log 22  =1
group 4=  log 210 =4
group 5= og 223 =5
Total bits required in vertical microprogramming= 5+7+1+4+5=22
So number of control words saved= 125-22=103 hence (B) is answer
-- Prateeksha Keshari ( 1619 points)

9 votes

3.109 Microprogramming: GATE1999_2.19 top

gateoverflow.in/1497

Arrange the following configuration for CPU in decreasing order of operating speeds:
Hard wired control, Vertical microprogramming, Horizontal microprogramming.

A. Hard wired control, Vertical microprogramming, Horizontal microprogramming.
B. Hard wired control, Horizontal microprogramming, Vertical microprogramming.
C. Horizontal microprogramming, Vertical microprogramming, Hard wired control.
D. Vertical microprogramming, Horizontal microprogramming, Hard wired control.

gate1999

co&architecture

microprogramming

normal

Answer: B
2 votes

3.110 Microprogramming: GATE1997_5.3 top


A micro instruction is to be designed to specify
a. none or one of the three micro operations of one kind and
b. none or upto six micro operations of another kind
The minimum number of bits in the micro-instruction is

Copyright GATE Overflow. All rights reserved.

-- Rajarshi Sarkar ( 27781 points)

gateoverflow.in/2254

GATE Overflow

April 2016

397 of 1876

A. 9
B. 5
C. 8
D. None of the above
gate1997

co&architecture

microprogramming

normal

Selected Answer

Answer: C
The first condition (None or any one out of 3 operations) gives 4 variations to consider. This uses 2 bits.
The second condition (Any combination of 6 other operations) gives 64 variations to consider. This uses 6 bits.
In total 8 bits.
-- Rajarshi Sarkar ( 27781 points)

3 votes

3.111 Microprogramming: GATE2013_28 top

gateoverflow.in/1539

Consider the following sequence of micro-operations.



MBR PC

MAR X

PC Y

Memory MBR

Which one of the following is a possible operation performed by this sequence?


(A) Instruction fetch
(B) Operand fetch
(C) Conditional branch
(D) Initiation of interrupt service
gate2013

co&architecture

microprogramming

normal

Selected Answer

Here PC value is being stored in memory. which is done when either CALL RETURN involved or there is Interrupt. As, we
will have to come back to execute current instruction.
so, option (A), (B) are clearly incorrect
option (C) is incorrect coz conditional branch does not require to save PC contents.

option (D) is correct as it matches the generic Interrupt Cycle :

6 votes

-- Himanshu Agarwal ( 8861 points)

- whenever the word fetch is used instruction register was associated as there is no instruction reg. so (A) is not our answer.
- operand fetch says you have to get operand from the memory and place it into the memory data register so source should
be the memory and destination should be memory data register so there no such operation is given so (B) is not our ans.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

398 of 1876

- in conditional branch or Unconditional branch you are able to place new value into the program counter but
here it is doing one extra thing it is placing the old value of program counter into the memory so (C) is not our
ans.
so our ans is (D)
-- Ankit Chourasiya ( 289 points)

2 votes

option d.
-- Supromit Roy ( 483 points)

1 votes

3.112 Microprogramming: GATE2004_67 top

gateoverflow.in/1061

The microinstructions stored in the control memory of a processor have a width of 26 bits. Each microinstruction is divided
into three fields: a micro-operation field of 13 bits, a next address field (X), and a MUX select field ( Y). There are 8 status
bits in the input of the MUX.


How many bits are there in the X and Y fields, and what is the size of the control memory in number of words?

A. 10, 3, 1024
B. 8, 5, 256
C. 5, 8, 2048
D. 10, 3, 512

gate2004

co&architecture

microprogramming

normal

Selected Answer

x + y + 13 = 26 (1)
y = 3 // y is no of bits used to represent 8 different states of multiplexer (2)
x is no of bits required represent size of control memory
x = 10 from (1) and (2)
size of control memory = 2x = 210 = 1024
4 votes

-- Digvijay Pandey ( 26235 points)

3.113 Microprogramming: GATE2004-IT_49 top


A CPU has only three instructions I1, I2 and I3, which use the following signals in time steps T1-T5:
I1 : T1 : Ain, Bout, Cin

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/3692

GATE Overflow

April 2016

399 of 1876

T2 : PCout, Bin
T3 : Zout, Ain
T4 : Bin, Cout
T5 : End
I2 : T1 : Cin, Bout, Din
T2 : Aout, Bin
T3 : Zout, Ain
T4 : Bin, Cout
T5 : End
I3 : T1 : Din, Aout
T2 : Ain, Bout
T3 : Zout, Ain
T4 : Dout, Ain
T5 : End
Which of the following logic functions will generate the hardwired control for the signal Ain ?

A)
B)
C)
D)

T1.I1 + T2.I3 + T4.I3 + T3


(T1 + T2 + T3).I3 + T1.I1
(T1 + T2 ).I1 + (T2 + T4).I3 + T3
(T1 + T2 ).I2 + (T1 + T3).I1 + T3

gate2004-it

co&architecture

microprogramming

normal

Selected Answer

We just have to see which all options give 1 whenever A in is 1 and 0 otherwise.
So, Ain is 1 in T3 of I1, I2 and I3. Also during T1 of I1, and T2 and T4 of I3. So, answer will be
T1.I1 + T2.I3 + T4.I3 + T3.I1 + T3.I2 + T3.I3
Since CPU is having only 3 instructions, T3.I1 + T3.I2 + T3.I3 can be replaced with T3 (we don't need to see which
instruction and Ain will be activated in time step 3 of all the instructions).
So, T1.I1 + T2.I3 + T4.I3 + T3
is the answer. Option A.
6 votes

3.114 Microprogramming: GATE2005-IT_45 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/3806

A hardwired CPU uses 10 control signals S1 to S10, in various time steps T1 to T5 , to implement 4 instructions I1 to I4 as shown
below:

Which of the following pairs of expressions represent the circuit for generating control signals S5 and S10 respectively?
((Ij + Ik)Tn indicates that the control signal should be generated in time step Tn if the instruction being executed is Ij or lk)

A)

S5 = T1 + I2 T3 and
S10 = (I1 + I3 ) T4 + (I2 + I4 ) T5

Copyright GATE Overflow. All rights reserved.

GATE Overflow

B)

April 2016

400 of 1876

S5 = T1 + (I2 + I4 ) T3 and
S10 = (I1 + I3 ) T4 + (I2 + I4 ) T5

C)

S5 = T1 + (I2 + I4 ) T3 and
S10 = (I2 + I3 + I4 ) T2 + (I1 + I3 ) T4 + (I2 + I4 ) T5

D)

S5 = T1 + (I2 + I4 ) T3 and
S10 = (I2 + I3 ) T2 + I4 T3 + (I1 + I3 ) T4 + (I2 + I4 ) T5

gate2005-it

co&architecture

microprogramming

normal

Selected Answer

4. is the option for this question.


If we look at the table, we need to find those time-stamps and instructions which are using these control signals.
For example, S5 = T1 has used control signal S5 for all the instructions, or we can say irrespective of the instructions. Also,
S5 is used by instructions I2 and I4 for the time stamp T3 so that comes to:
S5 = T1 + I2 T3 + I4 T3 = T1 + (I2 + I3 ) T3

In the same way, we'll calculate for S10.


It's an example of Hardwired CU Programming used in RISC processors. It gives accurate result, but isn't good for
debugging since minor change will cause to restructure the control unit.
-- Manu Thakur ( 5261 points)

7 votes

3.115 Microprogramming: GATE2008-IT_39 top

gateoverflow.in/3349

Consider a CPU where all the instructions require 7 clock cycles to complete execution. There are 140 instructions in the
instruction set. It is found that 125 control signals are needed to be generated by the control unit. While designing the
horizontal microprogrammed control unit, single address field format is used for branch control logic. What is the minimum
size of the control word and control address register?

A)
B)
C)
D)
gate2008-it

125, 7
125, 10
135, 9
135, 10

co&architecture

microprogramming

normal

Selected Answer

Its ans shuld be D becoz 140 instruction each requiring 7 cycles means...980 cycles which will take 10 bits
since its horizontal so for control word = 125 control signals + 10 bits =135 bits will be required
2 votes

3.116 Page Fault: GATE1998_2.18 top

Copyright GATE Overflow. All rights reserved.

-- nagendra2016 ( 111 points)

gateoverflow.in/1691

GATE Overflow

April 2016

401 of 1876

If an instruction takes i microseconds and a page fault takes an additional j microseconds, the effective instruction time if on
the average a page fault occurs every k instruction is:
j

A. i + k
B. i + j k
i +j

C. k
D. (i + j) k

gate1998

co&architecture

page-fault

easy

Selected Answer

page fault rate=1/k


page hit rate=1-1/k
service time=i
page fault service time=i+j
now effective memory access time=1/k*(i+j)+(1-1/k)*i=(i+j)/k+i-i/k=i/k+j/k+i-i/k=i+j/k
so option A is correct..
-- shashi shekhar ( 327 points)

1 votes

ans a)
-- Aditi Dan ( 5103 points)

6 votes

Here, given that On an average page fault occurs at every 'k' seconds. So, probability of getting a page fault is (1/k).

Effective Instruction Time = Normal instruction execution Time + Average Page Fault Service Time
i.e. Avg Page Fault Service Time = prob. of getting page fault * page fault service time =(1/k )* j

so its "i + (1/k)*j".
-- Dolly ( 47 points)

2 votes

3.117 Pipeline: GATE2008-IT_40 top

gateoverflow.in/3350

A non pipelined single cycle processor operating at 100 MHz is converted into a synchronous pipelined processor with five
stages requiring 2.5 nsec, 1.5 nsec, 2 nsec, 1.5 nsec and 2.5 nsec, respectively. The delay of the latches is 0.5 nsec. The
speedup of the pipeline processor for a large number of instructions is

A)
4.5
B)
4.0
C)
3.33
D)
3.0
gate2008-it

co&architecture

pipeline

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

402 of 1876

Selected Answer

answer is C..
explanation:
for non pipeline system time required = 2.5 + 1.5 + 2.0 + 1.5 + 2.5 = 10
for pipelined system = max(stage delay) + max(latch delay) = 2.5 + 0.5 = 3
speedup = time in non pipelie / time in pipeline = 10/3 = 3.33
-- jayendra ( 5797 points)

10 votes

Answer C.
Synchronous pipeline - take longest time period
So in pipeline processor t= (3*5)+3*(n-1)
in non-pipeline - 2.5+1.5+2+1.5+2.5 = 10 ns
so speed-up = 10 n / t = 3.333
-- shreya ghosh ( 2801 points)

4 votes

3.118 Pipeline: GATE2006-IT_79 top

gateoverflow.in/3623

A pipelined processor uses a 4-stage instruction pipeline with the following stages: Instruction fetch (IF), Instruction decode
(ID), Execute (EX) and Writeback (WB). The arithmetic operations as well as the load and store operations are carried out in
the EX stage. The sequence of instructions corresponding to the statement X = (S - R * (P + Q))/T is given below. The
values of variables P, Q, R, S and T are available in the registers R0, R1, R2, R3 and R4 respectively, before the execution of
the instruction sequence.
ADD
R5, R0, R1
; R5 R0 + R1
MUL
R6, R2, R5
; R6 R2 * R5
SUB
R5, R3, R6
; R5 R3 - R6
DIV
R6, R5, R4
; R6 R5/R4
STORE R6, X
; X R6


The IF, ID and WB stages take 1 clock cycle each. The EX stage takes 1 clock cycle each for the ADD, SUB and STORE
operations, and 3 clock cycles each for MUL and DIV operations. Operand forwarding from the EX stage to the ID stage is
used. The number of clock cycles required to complete the sequence of instructions is

A)
B)
C)
D)

10
12
14
16



gate2006-it

co&architecture

pipeline

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

403 of 1876

This is what i have solved. so answer is 12


-- Manu Thakur ( 5261 points)

6 votes

answer = option D = 16 cycles are required

-- Amar Vashishth ( 17735 points)

2 votes

3.119 Pipeline: GATE2015-2_44 top

gateoverflow.in/8218

Consider the sequence of machine instruction given below:


MUL
DIV
ADD
SUB

R5, R0, R1
R6, R2, R3
R7, R5, R6
R8, R7, R4

In the above sequence, R0 to R8 are general purpose registers. In the instructions shown, the first register shows the result
of the operation performed on the second and the third registers. This sequence of instructions is to be executed in a
pipelined instruction processor with the following 4 stages: (1) Instruction Fetch and Decode (IF), (2) Operand Fetch (OF),
(3) Perform Operation (PO) and (4) Write back the result (WB). The IF, OF and WB stages take 1 clock cycle each for any
instruction. The PO stage takes 1 clock cycle for ADD and SUB instruction, 3 clock cycles for MUL instruction and 5 clock
cycles for DIV instruction. The pipelined processor uses operand forwarding from the PO stage to the OF stage. The number
of clock cycles taken for the execution of the above sequence of instruction is _________.
gate2015-2

co&architecture

pipeline

normal

t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t14 t15

I1 IF OF PO PO PO WB

I2

IF OF -

PO PO PO PO PO WB

I3
I4

IF -

OF PO WB

IF OF PO WB

It is mentioned in the question that operand forwarding takes place from PO stage to OF stage and not to PO stage. So,
15 clock cycles.
But since operand forwarding is from PO-OF, we can do like make the PO stage produce the output during the rising edge

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

404 of 1876

of the clock and OF stage fetch the output during the falling edge. This would mean the final PO stage and OF stage can be
done in one clock cycle making the total number of cycles = 13. And 13 is the answer given in GATE key.

t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13

I1 IF OF PO PO PO WB

I2

IF OF -

PO PO PO PO PO WB

I3
I4

IF -

OF PO WB
IF OF PO WB

Ref: http://www.cs.iastate.edu/~prabhu/Tutorial/PIPELINE/forward.html
-- Arjun Suresh ( 124085 points)

12 votes

answer = 15 cycles

-- Amar Vashishth ( 17735 points)

1 votes

3.120 Pipeline: GATE2007-IT_6 top

gateoverflow.in/3437

A processor takes 12 cycles to complete an instruction I. The corresponding pipelined processor uses 6 stages with the
execution times of 3, 2, 5, 4, 6 and 2 cycles respectively. What is the asymptotic speedup assuming that a very large
number of instructions are to be executed?

A)
B)
C)
D)
gate2007-it

1.83
2
3
6

co&architecture

pipeline

normal

Selected Answer

For non pipeline processor we have n instruction and each instruction take 12 cycle so total 12n instruction.
For pipeline processor we have each stage strict to 6ns so time to complete the n instruction is 6*6+ (n-1)*6
Lim n-> 12n / 36 + (n-1)*6 = 12 / 6 =2

9 votes

linearly n instruction would be executed in 12n time.


when pipelined the time required =3+2+5+4+6+6*n=20+6n
speedup=12n/(20+6n)

Copyright GATE Overflow. All rights reserved.

-- Arpit Dhuriya ( 1791 points)

GATE Overflow

April 2016

405 of 1876

when n is very large then speedup = 2


so option (b).
correct me if i am wrong !
-- Suvojit Mondal ( 423 points)

2 votes

3.121 Pipeline: GATE2008-76 top

gateoverflow.in/496

Delayed branching can help in the handling of control hazards


For all delayed conditional branch instructions, irrespective of whether the condition evaluates to true or false,
A. The instruction following the conditional branch instruction in memory is executed
B. The first instruction in the fall through path is executed
C. The first instruction in the taken path is executed
D. The branch takes longer to execute than any other instruction
gate2008

co&architecture

pipeline

normal

Selected Answer

76. Answer is A. In order to avoid the pipeline delay due to conditional branch instruction, a suitable instruction is placed
below the conditional branch instruction such that the instruction will be executed irrespective of whether branch is taken
or not and won't affect the program behaviour.
77. Answer is D) I4. The STORE instruction can be moved below the conditional branch instruction. Whether the branch is
taken or not, STORE will be executed as the next instruction after conditional branch instruction, due to delayed
branching.
Here, I3 is not the answer because the branch conditional variable R1 is dependent on it. Same for I1. Similarly, I4 has a
dependency on I2 and hence I2 must be executed before I4.
-- Arjun Suresh ( 124085 points)

16 votes

3.122 Pipeline: GATE2015-1_38 top

gateoverflow.in/8288

Consider a non-pipelined processor with a clock rate of 2.5 gigahertz and average cycles per instruction of four. The same
processor is upgraded to a pipelined processor with five stages; but due to the internal pipeline delay, the clock speed is
reduced to 2 gigahertz. Assume that there are no stalls in the pipeline. The speedup achieved in this pipelined processor
is_______________.
gate2015-1

co&architecture

pipeline

normal

Selected Answer

Speed up = Old execution time/New execution time


Old execution time = CPI/2.5 = 4/2.5 = 1.6 ns
With pipelining, each instruction needs old execution time * old frequency/new frequency (without pipelining) = 1.6 * 2.5
/ 2 = 2 ns
There are 5 stages and when there is no pipeline stall, this can give a speed up of up to 5 (happens when all stages take
same number of cycles). In our case this time will be 2/5 = 0.4 ns. But clock frequency being 2 GHz, clock cycle is 1/2
GHz = 0.5 ns and a pipeline stage cannot be faster than this.
So, average instruction execution time after pipelining = max (0.4, 0.5) = 0.5 ns.
So, speed up compared to non-pipelined version = 1.6 / 0.5 = 3.2.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

406 of 1876
-- Arjun Suresh ( 124085 points)

6 votes

answer = 3.2
To compute cycle time, we know that a 2.5GHz processor means it completes 2.5G cycles in a second. so, for an instruction which on an
average takes 4 cycles to get completed will take 4/2.5G seconds.
On successful piplelining(i.e one which has no stalls) CPI = 1 as during it an instruction takes just one cycle time to get completed. So,


-- naresh1845 ( 1135 points)

13 votes

3.123 Pipeline: GATE2015-3_51 top

gateoverflow.in/8560

Consider the following reservation table for a pipeline having three stages S1 , S2 and S3 .
Time

S1

S2

S3

The minimum average latency (MAL) is ______


gate2015-3

co&architecture

pipeline

difficult

numerical-answers

first we find forbidden latency which is distance between each pair or X in the same row=(2,4) ... FL
indicate another task can not initiated after this
permissible latency =(1,3) we may initiate another task after this.
now we can find collision vector using FL ..
this collision vector will b known as initial state of the pipeline
collision vector = cycles (4,3,2,1) (one bit for each cycle )and bit at 2 and 4 will b one because of collision=
(1010)
now we can construct state diagram using permissible latency .
at 1 ..we will shift right 1 bit to collision vector (it is initial state ) and perform OR operation to result with
collision vector =
1010 after one right shift 0101
1010+0101=1111
same for at 3 ..1011
same for at >=5 ..1010

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

407 of 1876

now we have consider these points to find MAL


from the state diagram we can determine optimal latency cycle which result in MAL.
we have to find simple cycle which is a latency cycle in which each state appears only once
some simple cycle are greedy cycle which is one whose edges are all made with minimum latencies from
their respective starting state
so here we find latency cycle (3) and (1,5)
so the answer will b min of (3 which have constant latency or avg latency of (1,5)=(1+5)/2=3)
so the answer is 3
http://www2.cs.siu.edu/~cs401/Textbook/ch3.pdf
-- Anoop Sonkar ( 4167 points)

4 votes

3.124 Pipeline: GATE2004-IT_47 top

gateoverflow.in/3690

Consider a pipeline processor with 4 stages S1 to S4. We want to execute the following loop:
for (i = 1; i < = 1000; i++)
{I1, I2, I3, I4}


where the time taken (in ns) by instructions I1 to I4 for stages S1 to S4 are given below:

The output of I1 for i = 2 will be available after



A)
11 ns
B)
12 ns
C)
13 ns
D)
28 ns
gate2004-it

co&architecture

pipeline

normal

Selected Answer

time

I1
I2

s1 s2 s2 s3 s4 s4


s1 s1 s2 s3 s3 s4

I3

s1 s2 -

I4

s1 s1 s2 -

I1

10 11 12 13

s3 s3 s4

s4

s3

s4

s4

s3 s3

s1 s2 s2 -

so total time would be=13 ns


so option (c).
correct me if i am wrong...
7 votes

Copyright GATE Overflow. All rights reserved.

-- Suvojit Mondal ( 423 points)

GATE Overflow

April 2016

408 of 1876

3.125 Pipeline: GATE2000_12 top

gateoverflow.in/683

An instruction pipeline has five stages where each stage take 2 nanoseconds and all instruction use all five stages. Branch
instructions are not overlapped. i.e., the instruction after the branch is not fetched till the branch instruction is completed.
Under ideal conditions,
a. Calculate the average instruction execution time assuming that 20% of all instructions executed are branch instruction.
Ignore the fact that some branch instructions may be conditional.
b. If a branch instruction is a conditional branch instruction, the branch need not be taken. If the branch is not taken,
the following instructions can be overlapped. When 80% of all branch instructions are conditional branch instructions,
and 50% of the conditional branch instructions are such that the branch is taken, calculate the average instruction
execution time.
gate2000

co&architecture

pipeline

normal

Selected Answer

Each stage is 2ns. So, after 5 time units each of 2ns, the first instruction finishes (i.e., after 10ns), in every 2ns after that
a new instruction gets finished. This is assuming no branch instructions. Now, once the pipeline is full, we can assume that
the initial fill time doesn't matter our calculations and average execution time for each instruction is 2ns assuming no
branch instructions.
(a) Now, we are given that 20% of instructions are branch (like JMP) and when a branch instruction is executed, no
further instruction enters the pipeline. So, we can assume every 5th instruction is a branch instruction. So, with this
assumption, total time to finish 5 instruction will be 5 * 2 + 8 = 18 ns (as when a branch instruction enters the pipeline
and before it finishes, 4 pipeline stages will be empty totaling 4 * 2 = 8 ns, as it is mentioned in question that the next
instruction fetch starts only when branch instruction completes). And this is the same for every set of 5 instructions, and
hence the average instruction execution time = 18/5 = 3.6 ns
(b) This is just a complex statement. But what we need is to identify the % of branch instructions which cause a branch to
be taken as others will have no effect on the pipeline flow.
20% of branch instructions are branch instructions. 80% of branch instructions are conditional.
That means .2*.8 = 16% of instructions are conditional branch instructions and it is given that 50% of those result in a
branch being taken.
So, 8% of instructions are conditional branches being taken and we also have 20% of 20% = 4% of unconditional branch
instructions which are always taken.
So, percentage of instructions where a branch is taken is 8+4 = 12% instead of 20% in (a) part.
So, in 100 instructions there will be 12 branch instructions. We can do a different calculation here as compared to (a) as
12 is not a divisor of 100. Each branch instruction causes a pipeline delay of 4*2 = 8 ns. So, 12 instructions will cause a
delay of 12 * 8 = 96 ns. For 100 instructions, we need 100 * 2 = 200 ns without any delay and with delay we require 200
+ 96 = 296 ns for 100 instructions.
So, average instruction execution time = 296/100 = 2.96 ns
(We can also use this method for part (a) which will give 100 * 2 + 20*8 = 360 ns for 100 instructions)

11 votes

-- Arjun Suresh ( 124085 points)

if an instruction branches then it takes 2ns 5 = 10ns, coz if branch is taken then the instruction after that branch
instruction is not fetched until entire current branch instruction is completed, this means it will go through all stages.
if an instruction is non-branch or branching does not happen then, it takes 2ns to get completed.
Q.a) average time taken = 0.8 2ns + 0.2 10ns = 3.6ns
Q.b)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

409 of 1876

Average time taken = 0.8 2ns + 0.2 0.2 10ns + 0.8 (0.5 10ns + 0.5 2ns ) = 2.96ns

-- Amar Vashishth ( 17735 points)

2 votes

3.126 Pipeline: GATE1999_13 top

gateoverflow.in/1512

An instruction pipeline consists of 4 stages Fetch (F), Decode field (D), Execute (E) and Result Write (W). The 5
instructions in a certain instruction sequence need these stages for the different number of clock cycles as shown by the
table below

Instruction
1
2
3
4
5

No. of cycles needed for


F
D
1
2
1
2
2
1
1
3
1
2

E
1
2
3
2
1

W
1
1
2
1
2


Find the number of clock cycles needed to perform the 5 instructions.


gate1999

co&architecture

pipeline

normal

5 6

7 8 9

D
F

D
-

E W
D D E


E W

10 11 12 13 14 15

D D
- -

D
-

E
D

E
-

W
E W W


therefore 15 clock cycles needed.

-- Danish ( 1967 points)

4 votes

3.127 Pipeline: GATE2005-IT_44 top

gateoverflow.in/3805

We have two designs D1 and D2 for a synchronous pipeline processor. D1 has 5 pipeline stages with execution times of 3
nsec, 2 nsec, 4 nsec, 2 nsec and 3 nsec while the design D2 has 8 pipeline stages each with 2 nsec execution time How
much time can be saved using design D2 over design D1 for executing 100 instructions?

A)
B)

Copyright GATE Overflow. All rights reserved.

214 nsec
202 nsec

GATE Overflow

April 2016

C)
D)

410 of 1876

86 nsec
- 200 nsec

gate2005-it

co&architecture

pipeline

normal

Selected Answer

(B) is the correct option for this question.


Execution time for Pipeline = (K+n-1)*execution_time where k = no of stages in pipeline n = no of instructions
execution time = Max(all stages execution time)
D1 = (5+100-1)*4 = 416
D2 = (8+100-1)*2 = 214
Time saved using D2 = 416-214 =202
-- Manu Thakur ( 5261 points)

6 votes

3.128 Pipeline: GATE2013_45 top

gateoverflow.in/330

Consider an instruction pipeline with five stages without any branch prediction: Fetch Instruction (FI), Decode Instruction
(DI), Fetch Operand (FO), Execute Instruction (EI) and Write Operand (WO). The stage delays for FI, DI, FO, EI and WO are
5 ns, 7 ns, 10 ns, 8 ns and 6 ns, respectively. There are intermediate storage buffers after each stage and the delay of each
buffer is 1 ns. A program consisting of 12 instructions I1, I2, I3, , I12 is executed in this pipelined processor. Instruction I4
is the only branch instruction and its branch target is I9. If the branch is taken during the execution of this program, the
time (in ns) needed to complete the program is
(A) 132 (B) 165 (C) 176 (D) 328

gate2013

normal

co&architecture

pipeline

Selected Answer

answer = option B

cycles in pink are stall cycles, at EI-4 it was notified to the system that instruction 9 has to be loaded next.
We have completed execution in a total of 15 cycles where each cycle was (10+1)ns long,
Hence, answer = 15 11 = 165ns
7 votes

-- Amar Vashishth ( 17735 points)

After pipelining we have to adjust the stage delays such that no stage will be waiting for another to ensure smooth
pipelining (continuous flow). Since we can not easily decrease the stage delay, we can increase all the stage delays to the
maximum delay possible. So, here maximum delay is 10ns. Buffer delay given is 1ns. So, each stage takes 11ns in total.
FI of I9 can start only after the EI of I4. So, the total execution time will be

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

411 of 1876

15 11 = 165

T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15

I1 FI DI FO EI WO

I2

FI

DI FO EI

WO

I3
I4

FI DI FO
FI DI

EI
FO

WO

EI WO

stall

stall


stall

I9

FI

DI FO

EI

WO

I10
I11

FI DI
FI

FO
DI

EI
FO

WO

EI WO

I12

FI

DI

FO

EI

WO


-- gatecse ( 9515 points)

16 votes

3.129 Pipeline: GATE2006_42 top

gateoverflow.in/1818

A CPU has a five-stage pipeline and runs at 1 GHz frequency. Instruction fetch happens in the first stage of the pipeline. A
conditional branch instruction computes the target address and evaluates the condition in the third stage of the pipeline. The
processor stops fetching new instructions following a conditional branch until the branch outcome is known. A program
executes 109 instructions out of which 20% are conditional branches. If each instruction takes one cycle to complete on
average, the total execution time of the program is:
(A) 1.0 second
(B) 1.2 seconds
(C) 1.4 seconds
(D) 1.6 seconds
gate2006

co&architecture

pipeline

normal

Selected Answer

Delay slots in pipeline caused due to a branch instruction is 2 as after the 3rd stage of current instruction (during 4th
stage) IF of next begins. Ideally this should be during 2nd stage.
So, for total no. of instructions = 109 and 20% branch, we have 0.2 2 109 = 4 108 cycle penalty.
Since, clock speed is 1GHz and each instruction on average takes 1 cycle, total execution time in seconds will be
109 /109 + 4 108 /109 = 1.4
6 votes

-- Arjun Suresh ( 124085 points)

No. of non branch instructions = 8 108


No. of branch instructions = 2 108
When the branch condition is evaluated in third stage- first and second stage of pipeline are empty. So,
no. of stalls created by control hazard(branch instruction) = 2 2 108 = 4 108
Then, total no of cycle for execution = 8 108 + 2 108 + 4 108 ns = 14 108 ns = 1.4s
3 votes

Copyright GATE Overflow. All rights reserved.

-- tariq husain khan ( 85 points)

GATE Overflow

April 2016

3.130 Pipeline: GATE2005_68 top

412 of 1876

gateoverflow.in/1391


A 5 stage pipelined CPU has the following sequence of stages:
IF instruction fetch from instruction memory
RD Instruction decode and register read
EX Execute: ALU operation for data and address computation
MA Data memory access for write access, the register read at RD state is used.
WB Register write back
Consider the following sequence of instructions:
I1 : L R0, loc 1; R0 <= M[loc1]
I2 : A R0, R0 1; R0 <= R0 +R0
I3 : S R2, R0 1; R2 <= R2-R0
Let each stage take one clock cycle
What is the number of clock cycles taken to complete the above sequence of instructions starting from the fetch of I1 ?

A. 8
B. 10
C. 12
D. 15

gate2005

co&architecture

pipeline

normal

Selected Answer

answer = option A
8 cycles required with operand forwarding.

it is not given that RD and WB stage could overlap.

3 votes

Copyright GATE Overflow. All rights reserved.

-- Amar Vashishth ( 17735 points)

GATE Overflow

April 2016

413 of 1876

Without data forwarding:



T1
IF

T2
RD

T3
EX

T4
MA

T5
WB

T6

T7

T8

T9

T10

T11

IF

RD

EX

MA

WB

IF

RD

EX

MA

WB

With data forwarding:


T1
IF

T2
RD

T3
EX

T4
MA

T5
WB

T6

T7

T8

IF

RD

EX

MA

WB

IF

RD

EX

MA

WB


"For write access, the register read at RD state is used." This means, no operand forwarding for memory writes. So, we
can assume data forwarding is there for other operations. Hence, answer will be 8.
http://www.cs.iastate.edu/~prabhu/Tutorial/PIPELINE/forward.html
-- Arjun Suresh ( 124085 points)

7 votes

3.131 Pipeline: GATE2002_2.6 top

gateoverflow.in/836

The performance of a pipelined processor suffers if



A. the pipeline stages have different delays
B. consecutive instructions are dependent on each other
C. the pipeline stages share hardware resources
D. All of the above

gate2002

co&architecture

pipeline

easy

Selected Answer

Answer: D
A: Yes. Total delay = Max (All delays) + Register Delay.
B: Yes, if data forwarding is not there.
C: Yes, like ID and EX shares ID/EX register.
3 votes

3.132 Pipeline: GATE2004_69 top

-- Rajarshi Sarkar ( 27781 points)

gateoverflow.in/1063

A 4-stage pipeline has the stage delays as 150, 120, 160 and 140 nanoseconds respectively. Registers that are used
between the stages have a delay of 5 nanoseconds each. Assuming constant clocking rate, the total time taken to process
1000 data items on this pipeline will be

A. 120.4 microseconds
B. 160.5 microseconds

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

414 of 1876

C. 165.5 microseconds
D. 590.0 microseconds

gate2004

co&architecture

pipeline

normal

Selected Answer

Pipelining requires all stages to be synchronized meaning, we have to make the delay of all stages equal to the maximum
pipeline stage delay which here is 160.
Time for execution of the first instruction = (160+5) * 3 + 160 = 655 ns (5 ns for intermediate registers which is not
needed for the final stage).
Now, in every 165 ns, an instruction can be completed. So,
Total time for 1000 instructions = 655 + 999*165 = 165.49 microseconds
-- Arjun Suresh ( 124085 points)

7 votes

3.133 Pipeline: GATE2007_37 top

gateoverflow.in/1235

Consider a pipelined processor with the following four stages:


IF: Instruction Fetch
ID: Instruction Decode and Operand Fetch
EX: Execute
WB: Write Back
The IF, ID and WB stages take one clock cycle each to complete the operation. The number of clock cycles for the EX stage
depends on the instruction. The ADD and SUB instructions need 1 clock cycle and the MUL instruction needs 3 clock cycles in
the EX stage. Operand forwarding is used in the pipelined processor. What is the number of clock cycles taken to complete
the following sequence of instructions?
ADD
MUL
SUB

R2, R1, R0
R4, R3, R2
R6, R5, R4

R2 R1 + R0
R4 R3 * R2
R6 R5 - R4


A. 7
B. 8
C. 10
D. 14

gate2007

co&architecture

pipeline

normal

Selected Answer

Answer: option B
considering EX to EX data forwarding.

I1
I2

IF

ID
IF

EX
ID

WB
EX


EX


EX


WB

I3

IF

ID

EX

WB


7 votes

Copyright GATE Overflow. All rights reserved.

-- Rajarshi Sarkar ( 27781 points)

GATE Overflow

April 2016

415 of 1876

Correct answer would be 8 cycles.


ADD: |IF|ID|EX|WB|
MUL: |IF|ID|....EX........|WB|
SUB: |IF|ID| |EX|WB|
-- suraj ( 3299 points)

1 votes

3.134 Pipeline: GATE2003_10 top

gateoverflow.in/901

For a pipelined CPU with a single ALU, consider the following situations
I. The j+1 st instruction uses the result of the j-th instruction as an operand
II. The execution of a conditional jump instruction
III. The j-th and j+1 st instructions require the ALU at the same time.
Which of the above can cause a hazard

A. I and II only
B. II and III only
C. III only
D. All the three


gate2003

co&architecture

pipeline

normal

Selected Answer

1. Data hazard
2. Control hazard
3. Structural hazard as only one ALU is there
So, D all of these.
http://www.cs.iastate.edu/~prabhu/Tutorial/PIPELINE/hazards.html
-- Arjun Suresh ( 124085 points)

5 votes

3.135 Pipeline: GATE2009_28 top

gateoverflow.in/1314

Consider a 4 stage pipeline processor. The number of cycles needed by the four instructions I1, I2, I3, I4 in stages S1, S2,
S3, S4 is shown below:

S1

S2

S3

S4

I1

I2
I3

1
2

3
1

2
1

2
3

I4


What is the number of cycles needed to execute the following loop?
For (i=1 to 2) {I1; I2; I3; I4;}

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

416 of 1876


A. 16
B. 23
C. 28
D. 30

gate2009

co&architecture

pipeline

normal

this is the loop level level paralellism question but when we apply the loop level parallelism then we get 25 cycles so dis is
not in option so we have to do it without loop level parallelism and the frst time loop output the result at 15 cc so total 30
cc for 2 iterations
5 votes

-- Shreyans Dhankhar ( 2265 points)

Here bound of the loop are constants, therefore compiler will do the loop unrolling(If compiler won't then prefetcher will
do) to increase the instruction level parallelism. And after loop unrolling 23 cycles are required for execution. Therefore

correct answer would be (B).


4 votes

Concept for solving this question:


Stage S i is allocated to instruction Ii iff
1. Eligibility: Ii must have completed S i-1 ... X time
2. Availability: I i-1 must have released S i ... Y time
Time of allocation = Max(X,Y)
In first iteration:
I1 completes after 5th cycle
I2 completes after 10th cycle
I3 completes after 13th cycle
I4 completes after 15th cycle
In second iteration
I1 completes after 16th cycle
I2 completes after 18th cycle

Copyright GATE Overflow. All rights reserved.

-- suraj ( 3299 points)

GATE Overflow

April 2016

417 of 1876

I3 completes after 21th cycle


I4 completes after 23th cycle
Answer : B
-- Vikrant Singh ( 10051 points)

2 votes

3.136 Pipeline: GATE2001_12 top

gateoverflow.in/753

Consider a 5-stage pipeline - IF (Instruction Fetch), ID (Instruction Decode and register read), EX (Execute), MEM
(memory), and WB (Write Back). All (memory or register) reads take place in the second phase of a clock cycle and all
writes occur in the first phase. Consider the execution of the following instruction sequence:
I1:
I2:
I3:
I4:

sub r2, r3, r4;


sub r4, r2, r3;
sw r2, 100(r1)
sub r3, r4, r2

/*
/*
/*
/*

r2 r3 r4
r4 r2 r3
M[r1 + 100] r2
r3 r4 r2

*/
*/
*/
*/


a. Show all data dependencies between the four instructions.
b. Identify the data hazards.
c. Can all hazards be avoided by forwarding in this case.

gate2001

co&architecture

pipeline

Selected Answer

4 RAW

3 WAR

With operand forwarding:

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

418 of 1876


Without it:
(both tables represent the same pipeline)


-- Amar Vashishth ( 17735 points)

6 votes

RAW dependencies:
I1 <- I2
I1 <- I3
I1 <- I4
I2 <- I4
WAR
I2 <- I1
I4 <- I1
I4 <- I2
Consider a normal pipeline execution.

t1

t2

t3

t4

t5

t6

t7

t8

I1

IF

ID

EX

MEM

WB

I2

IF

ID

EX

MEM

WB

I3

IF

ID

EX

MEM

WB

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

I4

t1

t2

t3

t4
IF

t5
ID

t6
EX

t7
MEM

419 of 1876

t8
WB

So, here are RAW hazards for I2 and I3 with I1 and for I4 with I2. These can be eliminated with pipeline stalls as follows:

t8

t9

t10

t11

I1 IF ID EX MEM
I2
IF -

t1 t2 t3 t4

t5

WB

ID EX MEM

t6 t7


WB

I3

IF

ID EX

MEM

WB

I4

IF

ID

EX

WB

MEM


Now, with operand forwarding from EX - EX stage we can do as follows:

t1

t2

t3

t4

t5

t6

t7

t8

I1

IF

ID

EX

MEM

WB

I2

IF

ID

EX

MEM

WB

I3

IF

ID

EX

MEM

WB

I4

IF

ID

EX

MEM

WB

Thus all hazards are eliminated.


Ref: http://cseweb.ucsd.edu/classes/wi05/cse240a/pipe2.pdf

-- Arjun Suresh ( 124085 points)

2 votes

3.137 Pipeline: GATE2014-1_43 top

gateoverflow.in/1921

Consider a 6-stage instruction pipeline, where all stages are perfectly balanced. Assume that there is no cycle-time overhead
of pipelining. When an application is executing on this 6-stage pipeline, the speedup achieved with respect to non-pipelined
execution if 25% of the instructions incur 2 pipeline stall cycles is ____________
gate2014-1

co&architecture

pipeline

numerical-answers

normal

Selected Answer

Time without pipeline = 6 stages=6 cycles


Time with pipeline =1+stall freqency*stall cycle
=1+.25*2
=1.5
Speed up = 6/1.5
=4
12 votes

3.138 Pipeline: GATE2006-IT_78 top

-- aravind90 ( 599 points)

gateoverflow.in/3622

A pipelined processor uses a 4-stage instruction pipeline with the following stages: Instruction fetch (IF), Instruction decode
(ID), Execute (EX) and Writeback (WB). The arithmetic operations as well as the load and store operations are carried out in
the EX stage. The sequence of instructions corresponding to the statement X = (S - R * (P + Q))/T is given below. The
values of variables P, Q, R, S and T are available in the registers R0, R1, R2, R3 and R4 respectively, before the execution of
the instruction sequence.
ADD
R5, R0, R1
; R5 R0 + R1
MUL
R6, R2, R5
; R6 R2 * R5
SUB
R5, R3, R6
; R5 R3 - R6
DIV
R6, R5, R4
; R6 R5/R4

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016
STORE

R6, X

420 of 1876
; X R6



The number of Read-After-Write (RAW) dependencies, Write-After-Read( WAR) dependencies, and Write-After-Write (WAW)
dependencies in the sequence of instructions are, respectively,

A)
B)
C)
D)

2, 2, 4
3, 2, 3
4, 2, 2
3, 3, 2

gate2006-it

co&architecture

pipeline

normal

Selected Answer

(C) is the correct option for this question:


RAW
1. I1 - I2 (R5)
2. I2 - I3 (R6)
3. I3 - I4 (R5)
4. I4 - I5 (R6)
WAR
1. I2 - I3 (R5)
2. I4 - I5 (R6)
WAW
1. I1 - I3 (R5)
2. I2 - I4 (R6)
7 votes

3.139 Pipeline: GATE2011_41 top

-- Manu Thakur ( 5261 points)

gateoverflow.in/2143

Consider an instruction pipeline with four stages (S1, S2, S3 and S4) each with combinational circuit only. The pipeline registers are required
between each stage and at the end of the last stage. Delays for the stages and for the pipeline registers are as given in the figure.

What is the approximate speed up of the pipeline in steady state under ideal conditions when compared to the corresponding non-pipeline
implementation?
(A) 4.0
(B) 2.5
(C) 1.1
(D) 3.0

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

421 of 1876



gate2011

co&architecture

pipeline

normal

Selected Answer

Answer is (B) 2.5


In pipeline system Time taken is determined by the max delay at any stage i.e., 11ns plus the delay incurred by pipeline
stages i.e., 1ns = 12ns. In non-pipeline system Delay = 5ns + 6ns + 11ns + 8ns = 30ns.


-- Sona Praneeth Akula ( 3473 points)

12 votes

3.140 Pipeline: GATE2010_33 top

gateoverflow.in/2207

A 5-stage pipelined processor has Instruction Fetch (IF), Instruction Decode (ID), Opearnd Fetch (OF), Perform Operation
(PO) and Write Operand (WO) stages. The IF, ID, OF and WO stages take 1 clock cycle each for any instruction. The PO
stage takes 1 clock cycle for ADD and SUB instructions, 3 clock cycles for MUL instruction and 6 clock cycles for DIV
instruction respectively. Operand forwarding is used in the pipeline. What is the number of clock cycles needed to execute
the following sequence of instructions?
Instruction
t0 : MUL R2 , R0 , R1

Meaning of instruction
R2 R0 R1

t1 : DIV R5 , R3 , R4
t2 : ADD R2 , R5 , R2

R5 R3 /R4
R2 R5 + R2

t3 : SUB R5 , R2 , R6

R5 R2 R6


(A) 13
(B) 15
(C) 17
(D) 19

gate2010

co&architecture

pipeline

normal

Selected Answer

t1 t2 t3 t4 t5 t6 t7

t8 t9 t10 t11 t12 t13 t14 t15

IF ID OF PO PO PO WO






IF ID OF

PO PO PO PO PO PO WO

IF ID

IF ID

OF

PO WO

OF

PO WO

Operand forwarding allows an output to be passed for the next instruction. Here from the output of PO stage of DIV
instruction operand is forwarded to the PO stage of ADD instruction and similarly between ADD and SUB instructions.
Hence, 15cycles required.
http://www.cs.iastate.edu/~prabhu/Tutorial/PIPELINE/forward.html
11 votes

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

GATE Overflow

April 2016

422 of 1876

Let IF=F, ID=D, OF=O, PO=P, WO=W



I1 FDOPPPW
I2 HFDO--PPPPPPW
I3 HHFD-------OPW
I4 HHHFD-------OPW

(I3 depends upon R5 n R2, n using operator forwarding we can use R5 value directly when PO of I2
completes). Same happens for I4. So the total time taken until I4 completion is 15. (B) would be correct
answer
-- Madhur Rawat ( 2379 points)

1 votes

3.141 Pipeline: GATE 2016-1-32 top

gateoverflow.in/39691

The stage delays in a 4-stage pipeline are 800, 500, 400 and 300 picoseconds. The first stage (with delay 800 picoseconds) is
replaced with a functionality equivalent design involving two stages with respective delays 600 and 350 picoseconds. The
throughput increase of the pipeline is ___________ percent.
gate2016-1

co&architecture

pipeline

normal

numerical-answers

Selected Answer

33.33 % increase
initial through put is 1 instruction for 3200 pico seconds
Reason : 4*800 ( here 800 is maximum stage delay of any stage in an instruction so its selected as syncronous clock
cycle time )
in the next design
through put will be 1 instruction for 2400 pico seconds
reason : 4*600 ( here 600 is maximum stage delay of any stage in an instuction so its selected as syncronous clock cycle
time)
now increase in throughput is caluclated by ((1/2400)-(1/3200))/(1/3200)*100
now there is an assumption that the pipeline used is syncronous because if assyncronous is used the through put is
droped but not increased
-- Bharani Viswas ( 667 points)

4 votes

In pipeline ideally cpi=1


So in 1 cycle 1 instruction gets completed
Throughout is instructions in unit time
In pipeline 1,cycle time=max stage delay =800 *10^-12 sec
In 800 *10^-12 sec-> 1 instn
In 1 sec (10^12)\800 instructions which is also the throughput for pipeline 1
Similarly pipeline 2, throughput=(10^12)/600
Throughput increase in percentage
=(new-old ) /old *100
= ((10^12)/600-(10^12)/800) / (10^12)/800
=(200/600 ) *100
=100/3 =33.33 %

Copyright GATE Overflow. All rights reserved.

*100

GATE Overflow

April 2016

423 of 1876
-- Anurag Semwal ( 4775 points)

6 votes

3.142 Pipeline: GATE2014-3_43 top

gateoverflow.in/2077

An instruction pipeline has five stages, namely, instruction fetch (IF), instruction decode and register fetch (ID/RF),
instruction execution (EX), memory access (MEM), and register writeback (WB) with stage latencies 1 ns, 2.2 ns, 2 ns, 1 ns,
and 0.75 ns, respectively (ns stands for nanoseconds). To gain in terms of frequency, the designers have decided to split the
ID/RF stage into three stages (ID, RF1, RF2) each of latency 2.2/3 ns. Also, the EX stage is split into two stages (EX1, EX2)
each of latency 1 ns. The new design has a total of eight pipeline stages. A program has 20% branch instructions which
execute in the EX stage and produce the next instruction pointer at the end of the EX stage in the old design and at the end
of the EX2 stage in the new design. The IF stage stalls after fetching a branch instruction until the next instruction pointer is
computed. All instructions other than the branch instruction have an average CPI of one in both the designs. The execution
times of this program on the old and the new design are P and Q nanoseconds, respectively. The value of P/Q is
__________.
gate2014-3

co&architecture

pipeline

numerical-answers

normal

Selected Answer

cpi for first case = 2.2(1+2*.2) as the stall required is 2 and 2.2 is the maximum stage delay.
cpi for second state = 1*(1+5*.2) as now stall increase to 5 as there are five stages before the address is calculated and
the maximum stage delay now is 1.
cpu_time1/cpu_time2 = 3.08/2 = 1.54
14 votes

-- Arpit Dhuriya ( 1791 points)

five
stages:
(IF),
instruction
decode
and
register
fetch
(ID/RF),
instruction
execution
(EX),
memory
access
(MEM),
and
register
writeback
(WB)

P old

design:

with
stage
latencies
1
ns,
2.2
ns,
2
ns,
1
ns,
and
0.75
ns
MAX(
1
ns,
2.2
ns,
2
ns,
1
ns,
and
0.75
ns)
=
2.2nsec
AVG
instruction
execution
time
is

Tavg=(1+no
of
stalls*branch
penality)*cycle
time

=(1+0.20*2)2.2

{
branch
peanlity
is
2
because
the
next
instruction
pointer
at
the
end

of
the
EX
stage
in
the
old
design.}

=3.08
nsec
Q
:new
DESIGN:
the
designers
decided
to
split
the
ID/RF
stage
into
three
stages
(ID,
RF1,
RF2)
each
of
latency
2.2/3
ns.
Also,
the
EX
stage
is
split
into
two
stages
(EX1,
EX2)
each
of
latency
1
ns.
The
new
design
has
a
total
of
eight
pipeline
stages.
time
of
stages
in
new
design
={1
ns,
0.73ns,
0.73ns,
0.73ns
,
1ns,1ns,
1
ns,
and
0.75
ns}
(IF),
instruction
decode
register
fetch
(ID/RF)
---->
further
divided
into
3
ie
with
latency
0.73
of
each

instruction
execution
(EX)--->further
divided
int
1
nsec
of
each)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

424 of 1876

memory
access
(MEM)

register
writeback
(WB)
MAX(
1
ns,
0.73ns,
0.73ns,
0.73ns
,
1ns,1ns,
1
ns,
and
0.75
ns)
=1nsec

AVG
instruction
execution
time
is

Tavg=(1+no
of
stalls*branch
penality)*cycle
time

=(1+0.20*5)1

{
branch
peanlity
is
5
because
the
next
instruction
pointer
at
the
end

of
the
EX2
stage
in
the
new
design.}

=2
nsec
final
result

P/Q=3.08/2

=1.54


-- kunal chalotra ( 3573 points)

5 votes

3.143 Pipeline: GATE2014-3_9 top

gateoverflow.in/2043

Consider the following processors (ns stands for nanoseconds). Assume that the pipeline registers have zero latency.
P1: Four-stage pipeline with stage latencies 1 ns, 2 ns, 2 ns, 1 ns.
P2: Four-stage pipeline with stage latencies 1 ns, 1.5 ns, 1.5 ns, 1.5 ns.
P3: Five-stage pipeline with stage latencies 0.5 ns, 1 ns, 1 ns, 0.6 ns, 1 ns.
P4: Five-stage pipeline with stage latencies 0.5 ns, 0.5 ns, 1 ns, 1 ns, 1.1 ns.
Which processor has the highest peak clock frequency?
(A) P1
(B) P2
(C) P3
(D) P4


gate2014-3

co&architecture

pipeline

normal

Selected Answer

frequency = 1 / max( time in stages)


for P3 it is 1/1 GHz
for P1 it is 1/2 = 0.5 GHz
for P2, it is 1/1.5 = 0.67 GHz
for P4, it is 1/1.1 GHz
9 votes

Here , time for pipeline P1= 2 ns, and Frequency = 1/tp = 1/ 2 ghz= 0.5 ns.
Time for p2=1.5 ns, similarly fp = 0.66 ns

Copyright GATE Overflow. All rights reserved.

-- Arpit Dhuriya ( 1791 points)

GATE Overflow

April 2016

425 of 1876

same for p3= 1 ns ,so fp = 1 ns and p4= 1.1 ns , so fp =0.909 ns .


Hence , My ans will be P3.
-- Abhishek Kumar ( 129 points)

2 votes

3.144 Pipeline: GATE2008_36 top

gateoverflow.in/447

Which of the following are NOT true in a pipelined processor?


I. Bypassing can handle all RAW hazards
II. Register renaming can eliminate all register carried WAR hazards
III. Control hazard penalties can be eliminated by dynamic branch prediction

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

gate2008

pipeline

co&architecture

normal

Selected Answer

(B) I and III


I - False Bypassing can't handle all RAW hazard, consider when any instruction depends on the result of LOAD
instruction, now LOAD updates register value at Memory Access Stage (MA), so data will not be available directly on
Execute stage.
II - True, register renaming can eliminate all WAR Hazard.
III- False, It cannot completely eliminate, though it can reduce Control Hazard Penalties
-- Prateeksha Keshari ( 1619 points)

11 votes

3.145 Pipeline: GATE2008-77 top


Delayed branching can help in the handling of control hazards
The following code is to run on a pipelined processor with one branch delay slot:
I1: ADD R2 R7 + R8
I2: Sub R4 R5 R6
I3: ADD R1 R2 + R3
I4: STORE Memory [R4] R1
BRANCH to Label if R1 == 0
Which of the instructions I1, I2, I3 or I4 can legitimately occupy the delay slot without any program modification?
A. I1
B. I2
C. I3
D. I4

gate2008

co&architecture

pipeline

Copyright GATE Overflow. All rights reserved.

normal

gateoverflow.in/43487

GATE Overflow

April 2016

3.146 Pipeline: GATE2012_20 top

426 of 1876

gateoverflow.in/52

Register renaming is done in pipelined processors


(A) as an alternative to register allocation at compile time
(B) for efficient access to function parameters and local variables
(C) to handle certain kinds of hazards
(D) as part of address translation
gate2012

co&architecture

pipeline

easy

Selected Answer

Register renaming is done to eliminate WAR (Write after Read) and WAW (Write after Write) dependency between
instructions which could have caused pipieline stalls. Hence (C) is the answer.
Example:
I1: Read A to B
I2: Write C to A
Here, there is a WAR dependency and pipeline would need stalls. In order to avoid it register renaming is done and
Write C to A
will be
Write C to A'
WAR dependency is actually called anti-dependency and there is no real dependency except the fact that both uses same
memory location. Register renaming can avoid this. Similarly WAW also.
http://people.ee.duke.edu/~sorin/ece252/lectures/4.2-tomasulo.pdf
-- Arjun Suresh ( 124085 points)

4 votes

3.147 Pipeline: GATE2000_1.8 top

gateoverflow.in/631

Comparing the time T1 taken for a single instruction on a pipelined CPU with time T2 taken on a non-pipelined but identical CPU, we can say
that

a. T1 T2
b. T1 T2
c. T1 < T2
d. T1 and T2 plus the time taken for one instruction fetch cycle

gate2000

pipeline

co&architecture

easy

Selected Answer

Here we are comparing the execution time of only a single instruction. Pipelining in no way increases the execution time of
a single instruction (the time from its start to end). It increases the overall performance by splitting the execution to
multiple pipeline stages so that the following instructions can use the finished stages of the previous instructions. But in
doing so pipelining causes some problems also as given in the below link, which might slow some instructions. So, (B) is
the answer.
http://www.cs.wvu.edu/~jdm/classes/cs455/notes/tech/instrpipe.html
10 votes

3.148 Virtual Memory: GATE2008_38 top

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/449

GATE Overflow

April 2016

427 of 1876

In an instruction execution pipeline, the earliest that the data TLB (Translation Lookaside Buffer) can be accessed is

A. before effective address calculation has started
B. during effective address calculation
C. after effective address calculation has completed
D. after data cache lookup has completed

gate2008

co&architecture

virtual-memory

normal

Selected Answer

C as only after the calculation of Virtual address you can look up in the TLB
-- Shaun Patel ( 5445 points)

8 votes

in case of indirect addressing mode.the flow will be


[data from address field ] -> memory access-> TLB ->actual frame address ->data in that memory location -> back to
processor->now this data is my effective address.
sir,so i think answer should be B.


-- viv696 ( 1431 points)

2 votes

3.149 Virtual Memory: GATE1991_03,iii top

gateoverflow.in/517

03. Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
(iii) The total size of address space in a virtual memory system is limited by
a. the length of MAR
b. the available secondary storage
c. the available main memory
d. all of the above
e. none of the above

gate1991

co&architecture

virtual-memory

normal

Answer is (a) and (b)


Virtual memory concept is independent of size of main memory and depends only on the availability of the secondary
storage.
MAR holds the address generated by CPU and this obviously limits the total virtual memory address space.
6 votes

3.150 Virtual Memory: GATE2004_47 top

-- Kalpna Bhargav ( 2931 points)

gateoverflow.in/318

Consider a system with a two-level paging scheme in which a regular memory access takes 150 nanoseconds, and servicing

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

428 of 1876

a page fault takes 8 milliseconds. An average instruction takes 100 nanoseconds of CPU time, and two memory accesses.
The TLB hit ratio is 90%, and the page fault rate is one in every 10,000 instructions. What is the effective average instruction
execution time?
(A) 645 nanoseconds
(B) 1050 nanoseconds
(C) 1215 nanoseconds
(D) 1230 nanoseconds
gate2004

co&architecture

virtual-memory

normal

Selected Answer

Average Instruction execution time


= Average CPU execution time + Average time for getting data(instruction operands from memory for each
instruction)
= Average CPU execution time
+ Average address translation time for each instruction
+ Average memory fetch time for each instruction
+ Average page fault time for each instruction
1

= 100 + 2 0.9(0) + 0.1(2 150) + 2 150 + 10000 8 106


(Page Fault Rate per 10,000 instruction is directly given in question.Two memory accesses per
instruction and hence we need 2 address translation time for average instruction execution time)
[ TLB access time assumed as 0 and 2 page tables need to be accessed in case of TLB miss as the
system uses two-level paging ]
= 100 + 60 + 300 + 800
= 1260ns
18 votes

-- Arjun Suresh ( 124085 points)

(gate 2004 qus)


EAIET=[CPU execution time]+(TLB Hit*2*Memory access time +TLB miss ratio(page table access time+2*memory access time
))+{page fault probability*page fault service time}
That is 100ns+(0.9*2*150+0.1(150+150+2*150))+800ns.....[800ns herecomes from 0.0001*8*10^6]
=100ns+2*(135+30)ns+800ns
=100ns+2*165ns+800ns
=1230ns
4 votes

3.151 Writeback: Gate q-43_44 top

-- Rohan Ghosh ( 1515 points)

gateoverflow.in/21189

Consider a cache memory hit ratios for read and write operations are 80% and 90% respectively. If there is a miss then 2
word block is to be through from main memory to cache. Consider 30% updations and the cache access time is 20ns/word
and memory access time 100 ns/word.
Q43 calculate the efficiency of the cache using write through scheme?
A. 13.8 million words/ sec
B 12.8 million words/sec

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

429 of 1876

C 14.8 million words/sec


D 11.8 million words/sec
Q 44 find efficiency of cache using write back scheme?( in million words per sec)
A.15.5 b. 16.5 c. 14.5 d. 13.5
co&architecture

writeback

write_through

cache-memory

1. Write through
Tread = 20 + 0.2 2 100 = 60ns
Twrite = 100ns (Write through always goes to memory, so hit rate does not matter for time)
Tavg = 0.7 60 + 0.3 100 = 72ns
Amount of data transferred

time taken

7210 9

So, throughput =

= 13.8million words per second.

Efficiency is a ratio - should be a mistake in question.


2. Write back. To solve this we need amount of dirty bits or percentage of dirty page replacement. This is missing in
question.
See 35154 for reference.

-- Arjun Suresh ( 124085 points)

0 votes

3.152 GATE2008_37 top

gateoverflow.in/448

The use of multiple register windows with overlap causes a reduction in the number of memory accesses for
I. Function locals and parameters
II. Register saves and restores
III. Instruction fetches

A. I only
B. II only
C. III only
D. I, II and III
gate2008

co&architecture

normal

Selected Answer

I. Functions locals and parameters


this is true because overlapped registers eliminates the need for memory accesses. we here got to use registers instead.
II. Register saves and restores
this is false bc we need to see where memory accesses are reduced here before also we were using register as it says
Register saves... later also (i.e. after using multiple register windows) registers will are refered. So NO memory accesses
are reduced here.
III. Instruction fetches
it has nothing to do with reduction in memory accesses.
Hence, option A is correct.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

430 of 1876

-- Amar Vashishth ( 17735 points)

3 votes

3.152 GATE2008_71,72,73 in this question if virtual address is 32 bit how


can the virtual page address be 0xFF000 which is 20 bits? top

gateoverflow.in/6354

The question specifies the system uses a 32 bit virtual address. And the virtual page size is 4Kb. So the there can be
232 /212 = 220 virual pages, which can be addressed using a 20 bits. so 0xFF000 is the page address not the actual virtual
address
-- Gowthaman Arumugam ( 1079 points)

1 votes

3.153 GATE1991_01,ii top

gateoverflow.in/499

In interleaved memory organization, consecutive words are stored in consecutive memory modules in _______ interleaving,
whereas consecutive words are stored within the module in ________ interleaving.

gate1991

co&architecture

normal

Selected Answer

Consecutive words in consecutive memory modules in low order interleaving as the lower order bits determine the
module.
Consecutive words in same memory module in high order interleaving as the higher order bits determine the module.
http://heather.cs.ucdavis.edu/~matloff/154A/PLN/Interleaving.pdf
2 votes

-- Arjun Suresh ( 124085 points)

3.153 GATE2008_71,72,73 in this question how the 32 bit virtual address can
be used in finding the mapping in cache i.e the tags blocks etc........should
we not first covert it into physical address ?????/ top

gateoverflow.in/6352

That depends on where the cache is. A cache can be either virtually indexed or physically indexed. If it is physically
indexed, a cache can be accessed only after address translation. But for virtually indexed ones, we don't need this. The
"tag" can also be either physical or virtual.
Virtually indexed, physically tagged cache is the norm today.
0 votes

-- Arjun Suresh ( 124085 points)

3.154 GATE2001_1.10 top


Suppose a processor does not have any stack pointer register. Which of the following statements is true?
(A) It can not have subroutine call instruction
(B) It can have subroutine call instruction, but no nested subroutine calls
(C) Nested subroutine calls are possible, but interrupts are not

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/703

GATE Overflow

April 2016

431 of 1876

(D) All sequences of subroutine calls and also interrupts are possible
gate2001

co&architecture

normal

i think ans is B.
because in nested subroutine calls we used to push old subroutines into stack and pointing most recent call with stack
pointer.
-- jayendra ( 5797 points)

5 votes

3.155 GATE2000_1.10 top

gateoverflow.in/633

The most appropriate matching for the following pairs


X: Indirect addressing
Y: Immediate addressing
Z: Auto decrement addressing

1: Loops
2: Pointers
3: Constants

is

a. X - 3 Y - 2 Z - 1
b. X - 1 Y - 3 Z - 2
c. X - 2 Y - 3 Z - 1
d. X - 3 Y - 1 Z - 2

gate2000

co&architecture

normal

Selected Answer

C is the most appropriate one


-- Bhagirathi Nayak ( 10239 points)

5 votes

3.156 GATE1997_2.4 top

gateoverflow.in/2230

The correct matching for the following pairs is:


(A) DMA I/O
(B) Cache
(C) Interrupt I/O
(D) Condition Code Register

(1) High speed RAM


(2) Disk
(3) Printer
(4) ALU

A. A-4 B-3 C-1 D-2


B. A-2 B-1 C-3 D-4
C. A-4 B-3 C-2 D-1
D. A-2 B-3 C-4 D-1
gate1997

co&architecture

normal

Selected Answer

Answer: B
3 votes

Copyright GATE Overflow. All rights reserved.

-- Rajarshi Sarkar ( 27781 points)

GATE Overflow

April 2016

432 of 1876

3.157 GATE2014-1_55 top

gateoverflow.in/1935

Consider two processors P 1 and P 2 executing the same instruction set. Assume that under identical conditions, for the same input, a program running on P 2 takes
25% less time but incurs 20% more CPI (clock cycles per instruction) as compared to the program running on P 1 . If the clock frequency of P 1 is 1GHZ, then the
clock frequency of P 2 (in GHz) is ______.

gate2014-1

co&architecture

numerical-answers

normal

Selected Answer

CPU TIME ( T ) = No. of Instructions( I ) x No. of Cycles Per Instruction (c) x Cycle Time (t)
OR
CPU TIME ( T ) = No. of Instructions( I ) x No. of Cycles Per Instruction (c) x [Clock frequency ( f ) ] -1
===> T = I x c x f -1 ===> f = ( I x c) / T

P1 & P2 executing same instruction set -----> No. of Instructions same for both = I 1 = I 2 = I
If P1 takes T1 time ------> T2 = 0.75 x T1 -----> T2 / T1 = 0.75
If P1 incurs c1 clock cycles per instruction------> c2 = 1.2 x c1 -----> c2 / c1 = 1.2
Since I is same for both ----> ( f1 x T1 ) / c1 = ( f2 x T2 ) / c2 and f1 = 1 GHz
------> f2 = (c2/c1) x (T1/T2) x f1 = 1.2 / 0.75 x 1 GHz = 1.6 GHz
Hence,the clock frequency of P 2 is = 1.6 GHz.

-- Suraj Kaushal ( 317 points)

12 votes

Execution time (T) = CPI * #instructions * time for a clock


= CPI * #instructions / clock frequency (F)
Given P1 and P2 execute the same set of instructions and
T2 = 0.75 T 1,
CPI 2 = 1.2 CPI 1 and
F1 = 1GHz.
So,
T1

T2

CPI1

CPI2

F1 =

F2

T1

0.75T1

CPI1

1.2CPI1

1GHz =

F2

1.2

 F2 = 0.75 GHz
= 1.6GHz
3 votes

3.158 GATE2006_43 top

-- Arjun Suresh ( 124085 points)

gateoverflow.in/1819

Consider a new instruction named branch-on-bit-set (mnemonic bbs). The instruction bbs reg, pos, label jumps to label if
bit in position pos of register operand reg is one. A register is 32 bits wide and the bits are numbered 0 to 31, bit in
position 0 being the least significant. Consider the following emulation of this instruction on a processor that does not have
bbs implemented.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

433 of 1876

temp reg&mask
Branch to label if temp is non-zero. The variable temp is a temporary register. For correct emulation, the variable mask
must be generated by
(A) mask 0x1 << pos
(B) mask 0xffffffff << pos
(C) mask pos
(D) mask 0xf
gate2006

co&architecture

normal

a. mask 0x1 << pos


We want to check for a particular bit position say 2 (third from right). Let the number be 0xA2A7 (last 4 bits being 0111).
Here, the bit at position 2 from right is 1. So, we have to AND this with 0x0004 as any other flag would give wrong value
(may count other bits or discard the bit at position "pos"). And 0x0004 is obtained by 0x1 << 2 (by shifting 1 "pos" times
to the left we get a flag with 1 being set only for the "pos" bit position).
-- Arjun Suresh ( 124085 points)

3 votes

This question can be simply frame into bit manipulation question.


We can say that "find the bit is set or not at position "pos" in given register "reg".
So finding the bit is set or not simply we need to perform an "AND" operation with '1' of that bit if result is 0 then bit is
not set and if result is not 0 then bit is set. Now if given "pos" is not 0 then we need to left shift 1 by pos ( 0x1 << pos ).
-- admin ( 1411 points)

1 votes

3.159 GATE1999_2.22 top

gateoverflow.in/1499

The main difference(s) between a CISC and a RISC processor is/are that a RISC processor typically
(a) has fewer instructions
(b) has fewer addressing modes
(c) has more registers
(d) is easier to implement using hard-wired logic
gate1999

co&architecture

normal

Selected Answer

All are properties of RISC processor..


http://cs.stanford.edu/people/eroberts/courses/soco/projects/risc/whatis/index.html
http://cs.stanford.edu/people/eroberts/courses/soco/projects/risc/risccisc/index.html
http://homepage3.nifty.com/alpha-1/computer/Control_E.html
3 votes

3.160 GATE2002_1.13 top

Copyright GATE Overflow. All rights reserved.

-- Digvijay Pandey ( 26235 points)

gateoverflow.in/817

GATE Overflow

April 2016

434 of 1876

Which of the following is not a form of memory


A. instruction cache
B. instruction register
C. instruction opcode
D. translation look-a-side buffer

gate2002

co&architecture

easy

Selected Answer

The instruction opcode is a part of the instruction which tells the processor what operation is to be performed so it is not a
form of memory while the others are
-- Bhagirathi Nayak ( 10239 points)

7 votes

3.161 GATE2004-IT_50 top

gateoverflow.in/790

In an enhancement of a design of a CPU, the speed of a floating point until has been increased by 20% and the speed of a
fixed point unit has been increased by 10%. What is the overall speedup achieved if the ratio of the number of floating point
operations to the number of fixed point operations is 2:3 and the floating point operation used to take twice the time taken
by the fixed point operation in the original design?
(A) 1.155 (B) 1.185 (C) 1.255 (D) 1.285
gate2004-it

normal

co&architecture

Selected Answer

Speed up = Original time taken/ new time taken


Let x be the time for a fixed point operation
Original time taken = (3x + 2*2x)/5 = 7x/5
New time taken = ((3x/1.1) + (4x/1.2))/5 = 8x/1.32*5
So, speed up = 7*1.32/8 = 1.155

-- gatecse ( 9515 points)

7 votes

Answer is (B)
Say in old system: 20 floating point operation and 30 fixed point operations
say floating point takes 2 units and fixed point takes 1 unit
Total time in old system= 20*2 +30 *1= 70 units
In Enhanced system floating point takes = 2* 0.8= 1.6 units
fixed point takes= 1*0.9= 0.9 units
Total time = 20*1.6 +30 *0.9 = 59 units
Speedup= 70/59= 1.1864



2 votes

Copyright GATE Overflow. All rights reserved.

-- Sandeep_Uniyal ( 5063 points)

GATE Overflow

April 2016

435 of 1876

3.162 GATE1992_01,iii top

gateoverflow.in/547

(iii) Many microprocessors have a specified lower limit on clock frequency (apart from the maximum clock frequency limit)
because _____
gate1992

normal

co&architecture

Selected Answer

Clock frequency becomes low means time period of clock becomes high. When this time period increases beyond the time
period in which the non-volatile memory contents must be refreshed, we loose those contents. So, clock frequency can't
go below this value.
Ref: http://gateoverflow.in/261/microprocessors-specified-frequency-frequency-__________
-- Rajarshi Sarkar ( 27781 points)

2 votes

3.163 GATE1992_01,iv top

gateoverflow.in/548

Many of the advanced microprocessors prefetch instructions and store it in an instruction buffer to speed up processing. This
speed up is achieved because ________
gate1992

co&architecture

easy

Instruction prefetching is also useful in case of execution of branch instruction on pipelined processors.
Target instructions can be prefetched thereby reducing the chance of pipeline flush/clean when a branch instruction is
executed.
-- sameer2009 ( 1203 points)

0 votes

3.164 GATE2007-IT_36 top

gateoverflow.in/3469

The floating point unit of a processor using a design D takes 2t cycles compared to t cycles taken by the fixed point unit.
There are two more design suggestions D1 and D2. D1 uses 30% more cycles for fixed point unit but 30% less cycles for
floating point unit as compared to design D. D2 uses 40% less cycles for fixed point unit but 10% more cycles for floating
point unit as compared to design D. For a given program which has 80% fixed point operations and 20% floating point
operations, which of the following ordering reflects the relative performances of three designs?
(Di > Dj denotes that Di is faster than Dj)

A)
B)
C)
D)
gate2007-it

D1 > D > D2
D2 > D > D1
D > D2 > D1
D > D1 > D2

co&architecture

normal

Selected Answer

(B)
0.8 * (time taken in fixed point) + 0.2 (time taken in floating point)
D2 = 0.92
D = 1.2
D1 = 1.32
5 votes

Copyright GATE Overflow. All rights reserved.

-- Vicky Bajoria ( 3147 points)

GATE Overflow

April 2016

436 of 1876

3.165 GATE1992_02,iii top

gateoverflow.in/557

Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Bit-slice processors
(a). can be cascaded to get any desired word length processor
(b). speed of operation is independent of the word length configured
(c). do not contain anything equivalent of program counter in a 'normal' microprocessor
(d). Contain only the data path of a 'normal' CPU
gate1992

co&architecture

normal

answer: A
-- Laksin ( 11 points)

0 votes

3.166 GATE1995_1.2 top

gateoverflow.in/2589

Which of the following statements is true?


A. ROM is a Read/Write memory
B. PC points to the last instruction that was executed
C. Stack works on the principle of LIFO
D. All instructions affect the flags

gate1995

co&architecture

normal

Selected Answer

It is C.
Only the top of the stack can be accessed at any time. You can imagine a stack to be opened from only one side data
structure. So that if we put one thing over the other, we are able to access the last thing we inserted first. That is Last in
First Out (LIFO).
ROM is Read Only Memory.
PC points to the next instruction to be executed.
Not all instructions affect the flags.
6 votes

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

GATE Overflow

April 2016

437 of 1876

Operating System top

4.1 Ambiguous: GATE 2016-1-50 top

gateoverflow.in/39719

Consider the following proposed solution for the critical section problem. There are n processes : P0 . . . . Pn 1 . In the code,
function pmax returns an integer not smaller than any of its arguments .For all i, t[i] is initialized to zero.
Code for Pi;
do {
c[i]=1; t[i]= pmax (t[0],....,t[n-1])+1; c[i]=0;
for every j != i in {0,....,n-1} {
while (c[j]);
while (t[j] != 0 && t[j] <=t[i]);
}
Critical Section;
t[i]=0;
Remainder Section;
}

while (true);

Which of the following is TRUE about the above solution?


A. At most one process can be in the critical section at any time
B. The bounded wait condition is satisfied
C. The progress condition is satisfied
D. It cannot cause a deadlock
gate2016-1

operating-system

resource-allocation

difficult

ambiguous

Answer is A.

while (t[j] != 0 && t[j] <=t[i]);

This ensures that when a process i reaches Critical Section, all processes j which started before it must have its t[j] = 0.
This means no two process can be in critical section at same time as one of them must be started earlier.

returns an integer not smaller


is the issue here for deadlock. This means two processes can have same t value and hence
while (t[j] != 0 && t[j] <=t[i]);

can go to infinite wait. ( t[j] == t[i]). Starvation is also possible as there is nothing to ensure that a request is granted in a
timed manner. But bounded waiting (as defined in Galvin) is guaranteed here as when a process i starts and gets t[i]
value, no new process can enter critical section before i (as their t value will be higher) and this ensures that access to
critical section is granted only to a finite number of processes (those which started before) before eventually process i
gets access.
But in some places bounded waiting is defined as finite waiting and since deadlock is possible here, bounded waiting is not
guaranteed as per that definition.
6 votes

4.2 Cache Memory: GATE2001_1.7 top


More than one word are put in one cache block to
(a) exploit the temporal locality of reference in a program
(b) exploit the spatial locality of reference in a program
(c) reduce the miss penalty
(d) none of the above

Copyright GATE Overflow. All rights reserved.

-- Arjun Suresh ( 124085 points)

gateoverflow.in/700

GATE Overflow

gate2001

April 2016

operating-system

easy

438 of 1876

cache-memory

Selected Answer

exploit the spatial locality of reference in a program as, if the next locality is addressed immediately, it will already be in
the cache.
-- Arjun Suresh ( 124085 points)

7 votes

4.3 Computer Organization: GATE2004_68 top

gateoverflow.in/1062

A hard disk with a transfer rate of 10 Mbytes/second is constantly transferring data to memory using DMA. The processor
runs at 600 MHz, and takes 300 and 900 clock cycles to initiate and complete DMA transfer respectively. If the size of the
transfer is 20 Kbytes, what is the percentage of processor time consumed for the transfer operation?

A. 5.0%
B. 1.0%
C. 0.5%
D. 0.1%

gate2004

operating-system

disk

normal

computer-organization

Selected Answer

Clock cycle time = (1/600) x 10 ^6


For DMA initiation and completion = (900+300)/(600 x 10 ^6) = 2 microsec .
Disk Transfer rate = 10 Mbytes/sec
1 byte = 1/10^7 sec
20 Kbytes = 2 milisec = 2000 micro sec
Percentage = (2/2000 +2)*100 =0.0999 0.1%

% of cpu time consume= x/x+y


x= cpu busy
y= cpu block

5 votes

Clock cycle time = (1/600) x 10 ^6


For DMA initiation and competion = (900+300) /(600 x 10 ^6) = 2 microsec .
Disk Transfer rate = 10 M bytes. 1 byte = 1/10^7 sec
20 K bytes = 2000 microsec Percentage = (2/2000)*100 =0.1%
so, ans D

Copyright GATE Overflow. All rights reserved.

-- Anirudh Pratap Singh ( 4093 points)

GATE Overflow

April 2016

439 of 1876

.
-- Pranay Datta ( 6199 points)

2 votes

4.4 Computer Peripherals: GATE1992_02,xii top

gateoverflow.in/569

Choose the correct alternatives (more than one may be correct) and write the corresponding letters only:
Which of the following is an example of a spooled device?
(a). The terminal used to input data for a program being executed.
(b). The secondary memory device in a virtual memory system
(c). A line printer used to print the output of a number of jobs.
(d). None of the above.
gate1992

operating-system

computer-peripherals

easy

Selected Answer

Answer: C
Spool stands for simultaneous peripheral operations on-line.
-- Rajarshi Sarkar ( 27781 points)

6 votes

4.5 Concurrency: GATE2015-1_9 top

gateoverflow.in/8121

The following two functions P1 and P2 that share a variable B with an initial value of 2 execute concurrently.
P1() {
C = B - 1;
B = 2 * C;
}

P2(){
D = 2 * B;
B = D - 1;
}

The number of distinct values that B can possibly take after the execution is______________________.
gate2015-1

operating-system

concurrency

normal

Selected Answer

3 distinct value (2,3,4)


P1-P2: B = 3
P2-P1: B = 4
P1-P2-P1: B = 2
7 votes

4.6 Context Switch: GATE2011_6 top

-- Anoop Sonkar ( 4167 points)

gateoverflow.in/2108

Let the time taken to switch between user and kernel modes of execution be t1 while the time taken to switch between two processes be t2 . Which of the
following is TRUE?
(A) t1 > t2
(B) t1 = t2

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

440 of 1876

(C) t1 < t2
(D) nothing can be said about the relation between t1 and t2

gate2011

operating-system

context-switch

easy

Selected Answer

Time taken to switch two processes is very large as compared to time taken to switch between kernel and user mode of
execution because :
When you switch processes, you have to do a context switch, save the PCB of previous process (note that the PCB of a
process in Linux has over 95 entries), then save registers and then load the PCB of new process and load its registers etc.
When you switch between kernel and user mode of execution, OS has to just change a single bit at hardware level
which is very fast operation.
So answer is : C
-- CrimeMasterGoGo ( 2221 points)

13 votes

4.7 Context Switch: GATE1999_2.12 top

gateoverflow.in/1490

Which of the following actions is/are typically not performed by the operating system when switching context from process A
to process B?
A. Saving current register values and restoring saved register values for process B.
B. Changing address translation tables.
C. Swapping out the memory image of process A to the disk.
D. Invalidating the translation look-aside buffer.

gate1999

operating-system

context-switch

normal

Selected Answer

option C) because swapping out of the memory image of a process to disk is not done on every context switch as it would
cause a huge over head but can solve problems like trashing.
-- GateMaster Prime ( 1263 points)

9 votes

4.8 Dining Philosopher: TIFR2011-B-26 top


Consider the following two scenarios in the dining philosophers problem:
(i) First a philosopher has to enter a room with the table that restricts the number of philosophers to four.
(ii) There is no restriction on the number of philosophers entering the room. Which of the following is true?
a. Deadlock is possible in (i) and (ii).
b. Deadlock is possible in (i).
c. Starvation is possible in (i).
d. Deadlock is not possible in (ii).
e. Starvation is not possible in (ii)
tifr2011

operating-system

process-synchronization

dining-philosopher

First of all, In Dining Philosopher two things are definitely going to happen:

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/20572

GATE Overflow

April 2016

441 of 1876

1. Starvation, as one philosopher always has to wait for every other philosophers to finish.
2. No deadlock, since resource/s of the waiting philosopher is/are always available.
Above Point 2 eliminates every probability of a deadlock in Dining Philosopher problem so option a,b,e are out except d.
Examining closely Option d, we find that the number of philosophers keep on increasing but the rate at which philosopher
is done with its job leads to a deadlock.
Therefore, option c is the answer, with absolute starvation in (i).
-- Harsh Patil ( 31 points)

0 votes

4.9 Disk: GATE1997_74 top

gateoverflow.in/19704

A program P reads and processes 1000 consecutive records from a sequential file F stored on device D without using any file
system facilities. Given the following
Size of each record = 3200 bytes
Access time of D = 10 msecs
Data transfer rate of D = 800 103 bytes/second
CPU time to process each record = 3 msecs
What is the elapsed time of P if
a. F contains unblocked records and P does not use buffering?
b. F contains unblocked records and P uses one buffer (i.e., it always reads ahead into the buffer)?
c. records of F are organized using a blocking factor of 2 (i.e., each block on D contains two records of F) and P uses one
buffer?
gate1997

operating-system

disk

here Access time = 10ms


Process each Record = 3ms
Transfer time = 3200/800*10^3 = 4ms
A) Elapsed time = ( Access time + Transfer time + processing time)* number of records
(10+4+3)*1000 =17000 ms = 17sec
B) In this case P uses one ' Read ahead' buffer the processing and transferring of records can be overlapped
"Processing time is less than transfer time."
Elapsed time = ( Access time + Transfer time)*number of records
= (10+4)*1000 = 14sec
C) In this case each block contain two records so we can access 500 time to transfer 1000 records.
Elapsed time = ( Access time + Transfer time)*number of records
= (10+4+4+3+3)*500 = 12 sec
-- Umang Raman ( 10379 points)

0 votes

4.10 Disk: GATE2009-51 top

gateoverflow.in/1337

A hard disk has 63 sectors per track, 10 platters each with 2 recording surfaces and 1000 cylinders. The address of a sector
is given as a triple c, h, s, where c is the cylinder number, h is the surface number and s is the sector number. Thus, the 0 th
sector is addresses as 0, 0, 0, the 1 st sector as 0, 0, 1, and so on
51. The address <400, 16, 29> corresponds to sector number:
A. 505035
B. 505036
C. 505037
D. 505038
gate2009

operating-system

disk

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

442 of 1876

Selected Answer

The data on a disk is ordered in the following way. It is first stored on the first sector of the first surface of the first
cylinder. Then in the next sector, and next, until all the sectors on the first track are exhausted. Then it moves on to the
first sector of the second surface (remains at the same cylinder), then next sector and so on. It exhausts all available
surfaces for the first cylinder in this way. After that, it moves on to repeat the process for the next cylinder.
So, to reach to the cylinder numbered 400 (401 th cylinder) we need to skip 400 * (10*2) * 63 = 504,000 sectors.
Then, to skip to the 16th surface of the cylinder numbered 400, we need to skip another 16*63 = 1,008 sectors.
Finally, to find the 29 sector, we need to move another 29 sectors.
In total, we moved 504,000 + 1,008 + 29 = 505,037 sectors.
Hence, the answer to 51 is option C.
-- Pragy Agarwal ( 13675 points)

13 votes

4.11 Disk: GATE2015-2_49 top

gateoverflow.in/8251

Consider a typical disk that rotates at 15000 rotations per minute (RPM) and has a transfer rate of 50 106 bytes/sec. If the
average seek time of the disk is twice the average rotational delay and the controller's transfer time is 10 times the disk
transfer time, the average time (in milliseconds) to read or write a 512-byte sector of the disk is _____.
gate2015-2

operating-system

disk

normal

Selected Answer

Average time to read/write = Avg. seek time + Avg. rotational delay + Effective transfer time
Rotational delay = 60/15 = 4 ms
Avg. rotational delay = 1/2 * 4 = 2 ms
Avg. seek time = 2 * 2 = 4 ms
Disk transfer time = 512/(50 * 10 3) = 0.0102 ms
Effective transfer time = 10 * disk transfer time = 0.102 ms
So, avg. time to read/write = 4 + 2 + 0.1 = 6.1 ms
Ref: http://www.csc.villanova.edu/~japaridz/8400/sld012.htm

11 votes

-- Arjun Suresh ( 124085 points)

Ans 6.11
1 votes

4.12 Disk: GATE1993_7.8 top


The root directory of a disk should be placed
(A) at a fixed address in main memory
(B) at a fixed location on the disk
(C) anywhere on the disk

Copyright GATE Overflow. All rights reserved.

-- Vikrant Singh ( 10051 points)

gateoverflow.in/2296

GATE Overflow

April 2016

443 of 1876

(D) at a fixed location on the system disk


(E) anywhere on the system disk
gate1993

operating-system

disk

normal

Selected Answer

file system uses directories which are the files containing the name and location of other file in the file system. unlike
other file,directory does not store the user data. Directories are the file that can point to other directories. Root directory
point to various user directory.so they will be stored in such a way that user cannot easily modify them. They should be
placed at fixed location on the disk.
-- neha pawar ( 3561 points)

4 votes

4.13 Disk: GATE2001_20 top

gateoverflow.in/761

Consider a disk with the 100 tracks numbered from 0 to 99 rotating at 3000 rpm. The number of sectors per track is 100 and
the time to move the head between two successive tracks is 0.2 millisecond.
a. Consider a set of disk requests to read data from tracks 32, 7, 45, 5 and 10. Assuming that the elevator algorithm is
used to schedule disk requests, and the head is initially at track 25 moving up (towards larger track numbers), what is
the total seek time for servicing the requests?
b. Consider an initial set of 100 arbitrary disk requests and assume that no new disk requests arrive while servicing these
requests. If the head is initially at track 0 and the elevator algorithm is used to schedule disk requests, what is the
worse case time to complete all the requests?
gate2001

operating-system

disk

normal

Selected Answer

Answer A)
We are using SCAN - Elevator algorithms.
We will need to go from 25->99->5. (As we will move up all the way to 99,servicing all request, then come back to 5.)
So total seeks = 74+94= 168
Total time = 168*0.2 = 33.60000
Answer for B)
We need to consider rotational latency too - >
3000 rpm
i.e. 50 rps
1 r = 1000 /50 msec = 20 msec
So rotational latency = 20/2 = 10 msec per access.
In worst case we need to go from tracks 0-99. I.e. 99 seeks
Total time = 99 * 0.2 + 10*100 = 1019.8msec = 1.019 sec
5 votes

4.14 Disk: GATE2004-IT_51 top

-- Akash ( 26265 points)

gateoverflow.in/3694

The storage area of a disk has innermost diameter of 10 cm and outermost diameter of 20 cm. The maximum storage
density of the disk is 1400bits/cm. The disk rotates at a speed of 4200 RPM. The main memory of a computer has 64-bit
word length and 1s cycle time. If cycle stealing is used for data transfer from the disk, the percentage of memory cycles
stolen for transferring one word is

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

444 of 1876


A)
B)
C)
D)
gate2004-it

0.5%
1%
5%
10%

operating-system

disk

normal

Selected Answer

As the max density is given so we take the inner most diameter as it is denser there(2Rpi). The capacity of each track is pi*D*Density=3.14*10*1400 bits=14000pi bits
Now rotational latency is 60/RPM=60/4200=1/70 s.
So in 1/70 sec the disk can traverse one entire track and can read total 14000pi bits . Now this is done by the cpu. Now the data transfer is done by the DMA controller
which will be operated in memory cycle time i.e 1 micro sec and it has 64 bit word length. So in 1 cycle it is able to transfer total of 64 bits. In 1 sec it can transfer 64*10^6
bits.(1sec memory cycle)
In 1 sec the disk can read total of 14000pi*70=3.08*10^6 bits (considering pi=22/7)
So total memory cycle stolen is 3.08*10^6/(64*10^6) %= 5%(approx)

-- Shaun Patel ( 5445 points)

4 votes

Answer is (C)
-- Sandeep_Uniyal ( 5063 points)

1 votes

4.15 Disk: GATE2005-IT_63 top

gateoverflow.in/3824

In a computer system, four files of size 11050 bytes, 4990 bytes, 5170 bytes and 12640 bytes need to be stored. For storing
these files on disk, we can use either 100 byte disk blocks or 200 byte disk blocks (but can't mix block sizes). For each block
used to store a file, 4 bytes of bookkeeping information also needs to be stored on the disk. Thus, the total space used to
store a file is the sum of the space taken to store the file and the space taken to store the book keeping information for the
blocks allocated for storing the file. A disk block can store either bookkeeping information for a file or data from a file, but
not both.
What is the total space required for storing the files using 100 byte disk blocks and 200 byte disk blocks respectively?

A)
B)
C)
D)
gate2005-it

35400 and 35800 bytes


35800 and 35400 bytes
35600 and 35400 bytes
35400 and 35600 bytes

operating-system

disk

normal

Selected Answer

for 100 bytes block:


11050 = 111 blocks requiring 111 * 4 = 444 bytes of bookkeeping info which requires another 5 disk blocks. So, totally
111 + 5 = 116 disk blocks. Similarly,
4990 = 50 + (50*4)/100 = 52
5170 = 52 + (52*4)/100 = 55
12640 = 127 + (127*4/100) = 133
----356 x 100 = 35600 bytes
For 200 bytes block:
56 + (56*4/200) = 58
25 + (25 * 4 / 200) = 26
26 + (26 * 4 / 200) = 27
64 + (64 * 4 / 200) = 66
----177 x 200 = 35400

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

445 of 1876

So, C option.
-- Viral Kapoor ( 1777 points)

8 votes

4.16 Disk: GATE1993_6.7 top

gateoverflow.in/2289

A certain moving arm disk storage, with one head, has the following specifications:
Number of tracks/recording surface = 200
Disk rotation speed = 2400 rpm
Track storage capacity = 62,500 bits

The average latency of this device is P ms and the data transfer rate is Q bits/sec. Write the values of P and Q.
gate1993

operating-system

disk

normal

Selected Answer

RPM = 2400
So, in 60 s, the disk rotates 2400 times.
Average latency is the time for half a rotation = 0.5 * 60 / 2400 s = 3/240 s = 12.5 ms.
In one full rotation, entire data in a track can be transferred. Track storage capacity = 62500 bits.
So, disk transfer rate = 62500 * 2400 / 60 s = 2.5 * 10 6 bps.
-- Arjun Suresh ( 124085 points)

8 votes

Average Rotational Latency = 12.5 ms


Transfer rate = 2.5Mbps
-- Digvijay Pandey ( 26235 points)

1 votes

4.17 Disk: GATE2001_8 top

gateoverflow.in/749

Consider a disk with following specifications: 20 surface, 1000 tracks/surface, 16 sectors/track, data destiny 1 KB/sector,
rotation speed 3000 rpm. The operating system initiates the transfer between the disk and the memory sector-wise. Once
the head has been placed on the right track, the disk reads a sector in a single scan. It reads bits from the sector while the
head is passing over the sector. The read bits are formed into bytes in a serial-in-parallel-out buffer and each byte is then
transferred to memory. The disk writing is exactly a complementary process.
For parts (C) and (D) below, assume memory read-write time = 0.1 microsecond/byte, interrupt driven transfer has an
interrupt overhead = 0.4 microseconds, the DMA initialization and termination overhead is negligible compared to the total
sector transfer time. DMA requests are always granted.
A. What is the total capacity of the desk?
B. What is the data transfer rate?
C. What is the percentage of time the CPU is required for this disk I/O for bite-wise interrupts driven transfer?
D. What is the maximum percentage of time the CPU is held up for this disk I/O for cycle-stealing DMA transfer?

gate2001

operating-system

disk

normal

Selected Answer

Q.a) 20 1000 16 1KB = 3, 20, 000KB


Q.b)

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

446 of 1876

3000 rotations = 60 seconds


60
1 rotation =

3000

seconds

1
1 rotation = 1 track = 50 seconds
1
50
1 track = 16 1KB =
seconds
800KB = 1 second
Hence, transfer rate = 800 KB/sec
Q.c) Data is transferred Byte wise; given in the question.
CPU read/write time for a Byte = 0.1 s
Interrupt overhead (counted in CPU utilization time only) = 0.4 s
transfer time for 1 Byte data which took place at the rate of 800 KB/sec = 1.25 s
0.1+0.4

Percentage of CPU time required for this job = 0.5+1.25 100 = 28.57%
Q.d)
0.1+0

Percentage of CPU time required for this job = 0.1+1.25 100 = 7.407%
4 votes

-- Amar Vashishth ( 17735 points)

a) 20*1000*16*1=32000 KB
b) in 60 sec 3000 rounds
in 1 sec 50 rounds
therefore 50 tracks can be read in 1 sec
therefore 50*16*1 KB of data read in 1 sec
data rate =800 KB/sec
c) 800 KB of data is read in 1 sec
1 Byte of data can be read in 1/(800*1024) secs= 1.22 micro Sec
overhead =.1+.4=.5 micro Sec
total time = .5 + 1.22 = 1.72 micro sec
% of cpu time required =(.5/1.72)*100 =29%
d) Since there is no overhead(assumed in question) for DMA transfer. Therefore :
Byte transfer takes 1.22 microsecond (same logic as in part (c)).
writing this to memory takes 0.1 microsecond
%age of CPU involvement= (0.1)/(0.1+1.22)= 7.5%


2 votes

4.18 Disk: GATE2005_21 top


What is the swap space in the disk used for?

A. Saving temporary html pages

Copyright GATE Overflow. All rights reserved.

-- Danish ( 1967 points)

gateoverflow.in/1357

GATE Overflow

April 2016

447 of 1876

B. Saving process data


C. Storing the super-block
D. Storing device drivers

gate2005

operating-system

disk

easy

Selected Answer

Answer is b.
-- anshu ( 2155 points)

4 votes

4.19 Disk: GATE1995_14 top

gateoverflow.in/2650

If the overhead for formatting a disk is 96 bytes for a 4000 byte sector,
a. Compute the unformatted capacity of the disk for the following parameters:
Number of surfaces: 8
Outer diameter of the disk: 12 cm
Inner diameter of the disk: 4 cm
Inner track space: 0.1 mm
Number of sectors per track: 20
b. If the disk in (a) is rotating at 360 rpm, determine the effective data transfer rate which is defined as the number of
bytes transferred per second between disk and memory.

gate1995

operating-system

disk

normal

For A part :
No of track = Recording widh/ inner space between track
Recording width= (OuterDiameter - Inner Diameter )/2= (12-4)/2= 4 cm
therefore no of track = 4cm / 0.1 mm= 400 track
Since they have ask capacity of unformatted disk , so no 96 bytes in 4000 bytes would be wasted for non data purpose
Whole 4000 is used
So total capacity = 400 *8*20*4000 = 256*10 6 Bytes = 256 MB

For B part :
its is given 360 rotations in 60 seconds
that is 360 rotations = 60 *10 3 sec
therefore 1 rotations will take (1/6)sec
In (1/6) sec - we can read one track= 20*(4000-96) B = 20 * 3904 B
then in 1 sec it will be = 20*3904*6 bytes = Data transfer rate = 468.480 KBps
5 votes

Copyright GATE Overflow. All rights reserved.

-- spriti1991 ( 1127 points)

GATE Overflow

April 2016

448 of 1876

ans for A:
outer dia- inner dia = 12-4 = 8cm
inter track space 0.1mm therefore 8cm/0.1mm = 800 tracks
capacity in sectors = 800*20 = 16000 sectors/surface
total unformatted capacity = 8*16000*4000 bytes
ans for B:
360 rotation : 60 sec
1 rotation : 1/6 sec
1/6 sec : 20*4000 bytes
therefore in 1 sec 20*4000*6 bytes,which is Data transfer rate
-- jayendra ( 5797 points)

1 votes

4.20 Disk: GATE2001_1.22 top

gateoverflow.in/715

Which of the following requires a device driver?


(A) Register
(B) Cache
(C) Main memory
(D) Disk
gate2001

operating-system

disk

easy

Selected Answer

A disk driver is a device driver that allows a specific disk drive to communicate with the remainder of the computer. A
good example of this driver is a floppy disk driver.
-- Bhagirathi Nayak ( 10239 points)

10 votes

ans is D
-- jayendra ( 5797 points)

2 votes

4.21 Disk: GATE2007-IT_44 top


A hard disk system has the following parameters :
Number of tracks = 500
Number of sectors/track = 100
Number of bytes /sector = 500
Time taken by the head to move from one track to adjacent track = 1 ms
Rotation speed = 600 rpm.
What is the average time taken for transferring 250 bytes from the disk ?

A)
B)
C)
D)

Copyright GATE Overflow. All rights reserved.

300.5 ms
255.5 ms
255 ms
300 ms

gateoverflow.in/3479

GATE Overflow

April 2016

gate2007-it

operating-system

disk

449 of 1876

normal

Selected Answer

Avg. time to transfer = Avg. seek time + Avg. rotational delay + Data transfer time
RPM = 600
So, rotational delay = 60 / 600 = 0.1 s
In 1 rotations we can transfer the whole data in a track which is equal to number of sectors in a track * bytes per track
= 100 * 500 = 50,000
i.e., in 0.1 s, we can transfer 50,000 bytes.
Hence time to transfer 250 bytes = 0.1 * 250 / 50,000 = 0.5 ms
Avg. rotational delay = 0.5 * rotational delay = 0.5 * 0.1s = 50 ms
Avg. seek time = (0 + 1 + 2 + .... + 499)/500 (as time to move between successive tracks is 1 ms and we have 500 such
tracks) = 499 * 250 /500 = 249.5
So, average time for transferring 250 bytes = 249.5 + 50 + 0.5 = 300 ms
-- Arjun Suresh ( 124085 points)

4 votes

4.22 Disk: GATE1999_2.18 top

gateoverflow.in/1496

One of more options can be correct. Mark all of them.


Raid configurations of the disks are used to provide

A. Fault-tolerance
B. High speed
C. High data density
D. None of the above

gate1999

operating-system

disk

easy

Selected Answer

A) Fault tolerance and


B) High Speed
4 votes

4.23 Disk: GATE2003_25 top


Using a larger block size in a fixed block size file system leads to
A. better disk throughput but poorer disk space utilization
B. better disk throughput and better disk space utilization
C. poorer disk throughput but better disk space utilization
D. poorer disk throughput and poorer disk space utilization

Copyright GATE Overflow. All rights reserved.

-- GateMaster Prime ( 1263 points)

gateoverflow.in/915

GATE Overflow
gate2003

April 2016

operating-system

disk

450 of 1876

normal

Selected Answer

Answer is A. Larger block size means less number of blocks to fetch and hence better throughput. But larger block size
also means space is wasted when only small size is required.
-- Arjun Suresh ( 124085 points)

7 votes

4.24 Disk: GATE2009-52 top

gateoverflow.in/43477

A hard disk has 63 sectors per track, 10 platters each with 2 recording surfaces and 1000 cylinders. The address of a sector
is given as a triple c, h, s, where c is the cylinder number, h is the surface number and s is the sector number. Thus, the 0 th
sector is addresses as 0, 0, 0, the 1 st sector as 0, 0, 1, and so on
The address of the 1039 th sector is
A. 0, 15, 31
B. 0, 16, 30
C. 0, 16, 31
D. 0, 17, 31

gate2009

operating-system

disk

normal

Selected Answer

1039th sector will be stored in track number (1039 + 1)/63 = 16.5 (as counting starts from 0 as given in question) and
each track has 63 sectors. So, we need to go to 17 th track which will be numbered 16 and each cylinder has 20 tracks (10
platters * 2 recording surface each) . Number of extra sectors needed = 1040-16*63 = 32 and hence the sector number
will be 31. So, option C.
-- Pragy Agarwal ( 13675 points)

1 votes

4.25 Disk: GATE2005-IT_81b top

gateoverflow.in/3846

A disk has 8 equidistant tracks. The diameters of the innermost and outermost tracks are 1 cm and 8 cm respectively. The
innermost track has a storage capacity of 10 MB.
If the disk has 20 sectors per track and is currently at the end of the 5 th sector of the inner-most track and the head can
move at a speed of 10 meters/sec and it is rotating at constant angular velocity of 6000 RPM, how much time will it take to
read 1 MB contiguous data starting from the sector 4 of the outer-most track?

A)
B)
C)
D)
gate2005-it

13.5 ms
10 ms
9.5 ms
20 ms

operating-system

disk

normal

Radius of inner track is 0.5 cm (where the head is standing ) and the radius of outermost track is 4 cm.
So the header has to seek (4-0.5)=3.5 cm. It will take (3.5x1000/1000)=3.5 ms.
now angular velocity is constant and header is now end of 5th sector . To start from front of 4th sector it must rotate upto 18
sector.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

451 of 1876

6000 rotation in 60000ms


1 rotation in 10 ms.( same time to traverse 20 sector)
So to traverse sector 18 it takes 9 ms.
in 10 ms 10 MB data is read.
1 MB can be read in 1 ms.
So total time is =(1+9+3.5) ms =13.5ms
-- Palash Nandi ( 1373 points)

8 votes

4.26 Disk: GATE2008_32 top

gateoverflow.in/443

For a magnetic disk with concentric circular tracks, the seek latency is not linearly proportional to the seek distance due to

A. non-uniform distribution of requests
B. arm starting and stopping inertia
C. higher capacity of tracks on the periphery of the platter
D. use of unfair arm scheduling policies

gate2008

operating-system

disk

normal

Selected Answer

According to wiki http://en.wikipedia.org/wiki/Hard_disk_drive_performance_characteristics#Seek_time


answer should be B.
-- Vikrant Singh ( 10051 points)

5 votes

4.27 Disk: GATE2004_49 top

gateoverflow.in/1045

A unix-style I-nodes has 10 direct pointers and one single, one double and one triple indirect pointers. Disk block size is 1
Kbyte, disk block address is 32 bits, and 48-bit integers are used. What is the maximum possible file size?

A. 224 bytes
B. 232 bytes
C. 234 bytes
D. 248 bytes

gate2004

operating-system

disk

normal

Selected Answer

no of address in one block= 210 /22 = 28 as triple pointer used max possible size = 28 28 28 210 = 234 Bytes
ans is C

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

452 of 1876
-- Pooja ( 22745 points)

2 votes

Size of Disk Block = 1024Byte


Disk Blocks address = 4B
No of addresses per block 1024/4 = 256 = 2^8 addresses
we Have
10 Direct
1 SI = 2^8 Indirect* 2^10 = 2^18 Byte
1 DI = 2^8 SI = (2^8)^2 Direct = 2^16 Direct ** 2^10 = 2^26 Byte
1 TI = 2^8 DI = (2^8)^2 SI = (2^8)^3 = 2^24 Direct =2^24 * 2^10 = 2^34 Byte.
So total size = 2^18 + 2^26 + 2^34 Byte + 10240 Byte. Which is nearly 2^34 Bytes. (We don't have exact option
available. Choose approximate one)
Answer -> C
-- Akash ( 26265 points)

1 votes

4.28 Disk: GATE2007_11 top

gateoverflow.in/1209

Consider a disk pack with 16 surfaces, 128 tracks per surface and 256 sectors per track. 512 bytes of data are stored in a bit
serial manner in a sector. The capacity of the disk pack and the number of bits required to specify a particular sector in the
disk are respectively:

A. 256 Mbyte, 19 bits
B. 256 Mbyte, 28 bits
C. 512 Mbyte, 20 bits
D. 64 Gbyte, 28 bits

gate2007

operating-system

disk

normal

Selected Answer

ans is A.
16 surfaces= 4 bits, 128 tracks= 7 bits, 256 sectors= 8 bits, sector size 512 bytes = 9 bits
capacity of disk = 2^(4+7+8+9) = 2^28 = 256MB
to specify a particular sector we do not need sector size, so bits required = 4+7+8 = 19
-- jayendra ( 5797 points)

6 votes

4.29 Disk: GATE2013_29 top

gateoverflow.in/1540

Consider a hard disk with 16 recording surfaces (0-15) having 16384 cylinders (0-16383) and each cylinder contains 64
sectors (0-63). Data storage capacity in each sector is 512 bytes. Data are organized cylinder-wise and the addressing
format is <cylinder no., surface no., sector no.> . A file of size 42797 KB is stored in the disk and the starting disk location
of the file is <1200, 9, 40>. What is the cylinder number of the last sector of the file, if it is stored in a contiguous manner?
(A) 1281 (B) 1282 (C) 1283 (D) 1284
gate2013

operating-system

disk

Copyright GATE Overflow. All rights reserved.

normal

GATE Overflow

April 2016

453 of 1876

Selected Answer

I think there is an easy method:


First convert <1200,9,40> into sector address.
(1200 '* 16 * 64) + ( 9 * 64) + 40 = 1229416
number of sectors to store file = ( 42797 KB) / 512 = 85594

last sector to store file = 1229416+85594=1315010


Now do reverse engineering,
1315010/(16*64)=1284.189453 // 1284 will be cylinder number and remaining sectors =194.
194/64 = 3.03125 // 3 is surface number and remaining sectors are 2.
<1284,3,2> is last sector address.
-- Laxmi ( 683 points)

21 votes

42797 KB = 42797 * 1024 bytes require 42797 * 1024 / 512 sectors = 85594 sectors.
<1200, 9, 40> is the starting address. So, we can have 24 sectors in this recording surface. Remaining 85570 sectors.
85570 sectors require 85570/64 = 1337.031 1338 recording surfaces. We start with recording surface 9, so we can
have 7 more in the given cylinder. So, we have 1338 - 7 = 1331 recording surfaces left.
In a cylinder we have 16 recording surfaces. So, 1331 recording surfaces require 1331/16 = 83.18 84 different
cylinders.
The first cylinder (after the current one) starts at 1201. So, last one should be 1284.
<1284, 3, 2> will be the end address. (1331 - 16 * 83 = 3, and 85570 - 1337 * 64 = 2)
-- Arjun Suresh ( 124085 points)

3 votes

4.30 Disk: GATE1998-25b top

gateoverflow.in/41055

Consider a disk with c cylinders, t tracks per cylinder, s sectors per track and a sector length sl. A logical file dl with fixed
record length rl is stored continuously on this disk starting at location (cL, tL, sL), where cL, tL and SL are the cylinder, track and
sector numbers, respectively. Derive the formula to calculate the disk address (i.e. cylinder, track and sector) of a logical
record n assuming that rl = sl.
gate1998

operating-system

disk

descriptive

Here logical file size d1


Now , d1 has n records of size r1
So, d1= n r1
No of sectors for the file say (sec)=n r1 % s [Now, r1=s1, then sec=0]
No of tracks say (track) =sec % t
No. of cylinder say (cyl)= sec / t
Now, disk address of the logical record is <c L , tL , sL>+ <cyl, track,sec>
0 votes

4.31 Disk: GATE2011_44 top


Copyright GATE Overflow. All rights reserved.

-- srestha ( 11537 points)

gateoverflow.in/2146

GATE Overflow

April 2016

454 of 1876

An application loads 100 libraries at startup. Loading each library requires exactly one disk access. The seek time of the disk to a random
location is given as 10 ms. Rotational speed of disk is 6000 rpm. If all 100 libraries are loaded from random locations on the disk, how long
does it take to load all libraries? (The time to transfer data from the disk block once the head has been positioned at the start of the block may
be neglected.)
(A) 0.50 s
(B) 1.50 s
(C) 1.25 s
(D) 1.00 s

gate2011

operating-system

disk

normal

Selected Answer

disk access time =seek time +rotational latency+transfer time (given that transfer time is neglected)
here seek time=10msec
rotational speed=6000rpm
60sec ----- 6000 rotation
1 rotation------60/6000 sec
rotational latency---1/2 *60/6000 sec=5msec
total time to transfer one library=10+5=15 msec
total time to transfer 100 libraries=100*15msec=1.5 sec
-- neha pawar ( 3561 points)

11 votes

4.32 Disk: GATE1998_2.9 top

gateoverflow.in/1681

Formatting for a floppy disk refers to


A. arranging the data on the disk in contiguous fashion
B. writing the directory
C. erasing the system data
D. writing identification information on all tracks and sectors

gate1998

operating-system

disk

normal

Selected Answer

Ans is D .
When a soft-sectored disk is low-level "formatted", each track is written with a number of bytes calculated to fit within 360
degrees at the highest expected motor speed; identification data showing where each sector should start is written at this
time. The system of punched holes used by hard-sectored disks is not needed; a single hole is retained to indicate the
start of the track (3 12-inch disks use an alignment pin rather than a hole). If the motor is spinning any slower than the
highest acceptable speed, which is usually the case, the data will fit in fewer than 360 degrees, resulting in a gap at the
end of the track. Additionally, if a sector were to be rewritten on a drive running faster than the drive was running when
the track was formatted, the new data would be larger (occupy more degrees of rotation) than the original sector.
Therefore, during formatting a gap must be left between sectors to allow a rewritten sector to be larger without overwriting the following sector.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

455 of 1876

Reference :-https://en.wikipedia.org/wiki/Floppy_disk_format
-- Akash ( 26265 points)

3 votes

4.33 Disk: GATE2012_41 top

gateoverflow.in/2149

A file system with 300 GByte disk uses a file descriptor with 8 direct block addresses, 1 indirect block address and 1 doubly
indirect block address. The size of each disk block is 128 Bytes and the size of each disk block address is 8 Bytes. The
maximum possible file size in this file system is
(A) 3 KBytes
(B) 35 KBytes
(C) 280 KBytes
(D) dependent on the size of the disk
gate2012

operating-system

disk

normal

Selected Answer

direct block addressing will point to 8 disk blocks = 8*128 B = 1 KB


Singly Indirect block addressing will point to 1 disk block which has 128/8 disc block addresses = (128/8)*128 B = 2 KB
Doubly indirect block addressing will point to 1 disk block which has 128/8 addresses to disk blocks which in turn has
128/8 addresses to disk blocks = 16*16*128 B= 32 KB
Total = 35 KB
Ans B
-- Vikrant Singh ( 10051 points)

6 votes

4.34 Disk: GATE1998_17 top

gateoverflow.in/1731

Calculate the total time required to read 35 sectors on a 2-sided floppy disk. Assume that each track has 8 sectors and the
track-to-track step time is 8 milliseconds. The first sector to be read is sector 3 on track 10. Assume that the diskette is soft
sectored and the controller has a 1-sector buffer. The diskette spins at 300 RPM and initially, the head is on track 10.
gate1998

operating-system

disk

normal

numerical-answers

4.35 Disk: GATE2015-1_48 top

gateoverflow.in/8354

Consider a disk pack with a seek time of 4 milliseconds and rotational speed of 10000 rotations per minute (RPM). It has 600
sectors per track and each sector can store 512 bytes of data. Consider a file stored in the disk. The file contains 2000
sectors. Assume that every sector access necessitates a seek, and the average rotational latency for accessing each sector is
half of the time for one complete rotation. The total time (in milliseconds) needed to read the entire file
is__________________.
gate2015-1

operating-system

disk

normal

Selected Answer

Since each sector requires a seek,


Total time = 2000 * (seek time + avg. rotational latency + data transfer time)
Since data transfer rate is not given, we can take that in 1 rotation, all data in a track is read. i.e., in 60/10000 = 6ms,
600 * 512 bytes are read. So, time to read 512 bytes = 6/600 ms = 0.01 ms
= 2000 * (4 ms + 60 * 1000 /2* 10000 + 0.01)
= 2000 * (7.01 ms)
= 14020 ms.

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

456 of 1876

http://www.csee.umbc.edu/~olano/611s06/storage-io.pdf
-- Arjun Suresh ( 124085 points)

16 votes

Seek time (given) = 4ms


RPM = 10000 rotation in 1 min [60 sec]
So, 1 rotation will be =60/10000 =6ms [rotation speed]
Rotation latency= 1/2 * 6ms=3ms
# To access a file, total time includes =seek time + rot. latency +transfer time
TO calc. transfer time, find transfer rate Transfer rate = bytes on track /rotation speed
so, transfer rate = 600*512/6ms =51200 B/ms
transfer time= total bytes to be transferred/ transfer rate
so, Transfer time =2000*512/51200 = 20ms
Given as each sector requires seek tim + rot. latency = 4ms+3ms =7ms
Total 2000 sector takes = 2000*7 ms =14000 ms To read entire file ,total time = 14000 + 20(transfer time) = 14020 ms
-- Nilam dhatrak ( 301 points)

1 votes

4.36 Disk: GATE2005-IT_81a top

gateoverflow.in/3845

A disk has 8 equidistant tracks. The diameters of the innermost and outermost tracks are 1 cm and 8 cm respectively. The
innermost track has a storage capacity of 10 MB.
What is the total amount of data that can be stored on the disk if it is used with a drive that rotates it with (i) Constant
Linear Velocity (ii) Constant Angular Velocity?

A)
B)
C)
D)

(i) 80 MB (ii) 2040 MB


(i) 2040 MB (ii) 80 MB
(i) 80 MB (ii) 360 MB
(i) 360 MB (ii) 80 MB

gate2005-it

operating-system

disk

normal

Selected Answer

With Constant Linear Velocity, CLV, the density of bits is uniform from cylinder to cylinder. Because there are
more sectors in outer cylinders, the disk spins slower when reading those cylinders, causing the rate of bits passing
under the read-write head to remain constant. This is the approach used by modern CDs and DVDs.
With Constant Angular Velocity, CAV, the disk rotates at a constant angular speed, with the bit density decreasing
on outer cylinders. ( These disks would have a constant number of sectors per track on all cylinders. )
CLV=10+20+30+40+..80=360
CAV=10*8 = 80 so answer should be d
6 votes

-- spriti1991 ( 1127 points)

Constant linear velocity - RPM will be same, means bit density will be same So outer track has more data than inner
10+20+30....+80 = 360 MB
Constant Angular velocity - RPM will not be same, Density will not be same, Same amount of data per track
8*10 = 80 MB

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

457 of 1876
-- Saumya ( 489 points)

1 votes

4.37 Disk: GATE1998-25a top

gateoverflow.in/1740

Free disk space can be used to keep track of using a free list or a bit map. Disk addresses require d bits. For a disk with B
blocks, F of which are free, state the condition under which the tree list uses less space than the bit map.
gate1998

operating-system

disk

descriptive

Solution for Part a :Assume that size of each block is S bits.


Then no of bits required for free list is = Fd, No of blocks required = Fd/S
No of bits required for Bit map = B (No of blocks ) , No of block required is = B /S
Condition under which free list uses less space than the bit map.
Fd / S < B / S
-- Akash ( 26265 points)

2 votes

4.38 Disk Scheduling: GATE2015-1_30 top

gateoverflow.in/8227

Suppose the following disk request sequence (track numbers) for a disk with 100 tracks is given:
45, 20, 90, 10, 50, 60, 80, 25, 70.
Assume that the initial position of the R/W head is on track 50. The additional distance that will be traversed by the R/W
head when the Shortest Seek Time First (SSTF) algorithm is used compared to the SCAN (Elevator) algorithm (assuming
that SCAN algorithm moves towards 100 when it starts execution) is________________tracks.
gate2015-1

operating-system

disk-scheduling

normal

check : http://www.cs.iit.edu/~cs561/cs450/disksched/disksched.html

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

458 of 1876

So, for SSTF it takes 130 head movements and for SCAN it takes 140 head movements.
Hence, not additional but 140 130 = 10 less head movements SSTF takes.
7 votes

-- Amar Vashishth ( 17735 points)

SSTF:
Initial position 50. So, shortest sequence will be
50 45 60 70 80 90 25 20 10
and the corresponding distances will be
0 5 15 10 10 10 65 5 10
giving total distance of 130.
SCAN:
Here requests from 50 are serviced in ascending order of their track number (as the movement is from 50 to 100) and at
the end of the sequence, the remaining requests are serviced in the descending order. So, the service order will be
50 60 70 80 90 45 25 20 10
and the corresponding distances
0 10 10 10 10 45 20 5 10

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

459 of 1876

giving a total distance of 120


So, extra distance of SSTF = 130 - 120 = 10
Ref: http://courses.cs.vt.edu/cs2506/Fall2014/Notes/L17.IOScheduling.pdf
-- Arjun Suresh ( 124085 points)

1 votes

4.39 Disk Scheduling: GATE2007-IT_83 top

gateoverflow.in/3535

The head of a hard disk serves requests following the shortest seek time first (SSTF) policy. The head is initially positioned at
track number 180.
What is the maximum cardinality of the request set, so that the head changes its direction after servicing every request if
the total number of tracks are 2048 and the head can start from any track?

A)
B)
C)
D)
gate2007-it

9
10
11
12

operating-system

disk-scheduling

normal

Ans) C (11) Consider the following request set (1025,1023,1028,1017,1040,993,1088,897,1280,513,2048) Suppose head
is initially positioned at track number 1024.So very first time there is tie between two requests 1025 and 1024 (because
both are same distance). So without loss of generality let's assume initially head moving toward right direction(mean first
1025 track request will be serviced). So apply the SSTF afterwards.
-- Abhishek Verma ( 137 points)

0 votes

4.40 Disk Scheduling: GATE2007-IT_82 top

gateoverflow.in/3534

The head of a hard disk serves requests following the shortest seek time first (SSTF) policy. The head is initially positioned at
truck number 180.
Which of the request sets will cause the head to change its direction after servicing every request assuming that the head
does not change direction if there is a tie in SSTF and all the requests arrive before the servicing starts?

A)
B)
C)
D)
gate2007-it

11, 139, 170, 178, 181, 184, 201, 265


10, 138, 170, 178, 181, 185, 201, 265
10, 139, 169, 178, 181, 184, 201, 265
10, 138, 170, 178, 181, 185, 200, 265

operating-system

disk-scheduling

normal

Selected Answer

It should be B.
When the head starts from 180... it seeks the nearest track.. which is 181. Then from 181 it seeks the nearest one which
is 178 and 184. But the difference in both from 181 is same and as given in the question... if there is a tie then the head
wont change its direction, and therefore to change the direction we need to consider 178. and thus we can eliminate
option A and C.
Coming next to option B and D.. following the above procedure you'll see that option D is eliminated on similar ground.
And thus you can say option B is correct.
2 votes

Copyright GATE Overflow. All rights reserved.

-- Gate Keeda ( 16619 points)

GATE Overflow

April 2016

4.41 Disk Scheduling: GATE1995_20 top

460 of 1876

gateoverflow.in/2658

The head of a moving head disk with 100 tracks numbered 0 to 99 is currently serving a request at track 55. If the queue of
requests kept in FIFO order is
10, 70, 75, 23, 65
which of the two disk scheduling algorithms FCFS (First Come First Served) and SSTF (Shortest Seek Time First) will require
less head movement? Find the head movement for each of the algorithms.
gate1995

operating-system

disk-scheduling

normal

Selected Answer

FCS:55->10->70->75->23->65 => 45+60+5+52+42=204.


SSTF:55->65->70->75->23->10 => 10+5+5+52+13=85
Hence SSTF.

-- kireeti ( 883 points)

6 votes

4.42 Disk Scheduling: GATE2014-1_19 top

gateoverflow.in/1786

Suppose a disk has 201 cylinders, numbered from 0 to 200. At some time the disk arm is at cylinder 100, and there is a queue of disk access requests for
cylinders 30, 85, 90, 100, 105, 110, 135 and 145. If Shortest-Seek Time First (SSTF) is being used for scheduling the disk access, the request for cylinder 90 is
serviced after servicing ____________ number of requests.

gate2014-1

operating-system

disk-scheduling

numerical-answers

normal

Selected Answer

Requests are serviced in following order


100 105 110 90 85 135 145 30
So request of 90 is serviced after 3 requests
1 votes

-- Pooja ( 22745 points)

3 requests..
1 votes

4.43 Disk Scheduling: GATE2004-IT_62 top

-- aditi ( 307 points)

gateoverflow.in/3705

A disk has 200 tracks (numbered 0 through 199). At a given time, it was servicing the request of reading data from track
120, and at the previous request, service was for track 90. The pending requests (in order of their arrival) are for track
numbers.
30 70 115 130 110 80 20 25.
How many times will the head change its direction for the disk scheduling policies SSTF(Shortest Seek Time First) and FCFS
(First Come Fist Serve)?

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

461 of 1876


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

gate2004-it

operating-system

disk-scheduling

normal

Selected Answer

Answer is (C)
SSTF: (90) 120 115 110 130 80 70 30 25 20
Direction changes at 120,110,130
FCFS: (90) 120 30 70 115 130 110 80 20 25
direction changes at 120,30,130,20
-- Sandeep_Uniyal ( 5063 points)

4 votes

4.44 Disk Scheduling: GATE2004_12 top

gateoverflow.in/1009

Consider an operating system capable of loading and executing a single sequential user process at a time. The disk head
scheduling algorithm used is First Come First Served (FCFS). If FCFS is replaced by Shortest Seek Time First (SSTF), claimed
by the vendor to give 50% better benchmark results, what is the expected improvement in the I/O performance of user
programs?

A. 50%
B. 40%
C. 25%
D. 0%

gate2004

operating-system

disk-scheduling

normal

Selected Answer

Question says "single sequential user process". So, all the requests to disk scheduler will be in sequence and hence there
is no use of any disk scheduling algorithm. Anyone will give the same sequence and hence the improvement will be 0%.
-- Arjun Suresh ( 124085 points)

10 votes

4.45 Disk Scheduling: GATE 2016-1-48 top

gateoverflow.in/39716

Cylinder a disk queue with requests for I/O to blocks on cylinders 47, 38, 121, 191, 87, 11, 92, 10. The C-LOOK scheduling algorithm
is used. The head is initially at cylinder number 63, moving towards larger cylinder numbers on its servicing pass. The
cylinders are numbered from 0 to 199. The total head movement (in number of cylinders) incurred while servicing these
requests is__________.
gate2016-1

operating-system

disk-scheduling

Selected Answer

Copyright GATE Overflow. All rights reserved.

normal

numerical-answers

GATE Overflow

April 2016

462 of 1876

63->191 = 128
191->10 = 181
10->47 = 37
Total = 346
7 votes

-- Abhilash Panicker ( 6507 points)

Answer is 346 as already calculated in answers here.Those having some doubt regarding long jump ,check this image,
Now in question Total Head Movements are asked,When Head reaches any End, There is no mechanism for head to
jump directly to some arbitrary track.It has to Move.So it has to move along the tracks to reach Track Request
on other side.Therefore head will move and we must count it.
since purpose of disk scheduling algorithms is to reduce such Head movements by finding an Optimal algorithm.If you
ignore the move which is actually happening in disk,that doesn't serve the purpose of analyzing the algorithms.

4 votes

-- Anurag Semwal ( 4775 points)

Answer is 346.
63 -> 87 = 24
87 -> 92 = 5
92 -> 121 = 29
121 -> 191 = 70
191 -> 10 = 181
10 -> 11 = 1
11 -> 38 = 27
38 -> 47 = 9
Total: 24+5+29+70+181+1+27+9 = 346
3 votes

4.46 Disk Scheduling: GATE2010_24 top


Copyright GATE Overflow. All rights reserved.

-- stuts ( 43 points)

gateoverflow.in/2203

GATE Overflow

April 2016

463 of 1876

A system uses FIFO policy for system replacement. It has 4 page frames with no pages loaded to begin with. The system
first accesses 100 distinct pages in some order and then accesses the same 100 pages but now in the reverse order. How
many page faults will occur?
(A) 196
(B) 192
(C) 197
(D) 195
gate2010

operating-system

disk-scheduling

normal

Selected Answer

ans is A
when we access the 100 distinct page in some order (suppose order is 1 2 3....100) then total page fault occurs are 100.
and in last, frame contain the pages 100 99 98 97 .when we reverse the string (100,99,98....1) then first four page will
not cause the page fault bcz they already present in frame but the remaining 96 page will cause 96 page fault,so total
page fault are 100+96=196
-- neha pawar ( 3561 points)

6 votes

4.47 Disk Scheduling: GATE2009_31 top

gateoverflow.in/1317

Consider a disk system with 100 cylinders. The requests to access the cylinders occur in following sequence:
4, 34, 10, 7, 19, 73, 2, 15, 6, 20
Assuming that the head is currently at cylinder 50, what is the time taken to satisfy all requests if it takes 1ms to move from
one cylinder to adjacent one and shortest seek time first policy is used?

A. 95 ms
B. 119 ms
C. 233 ms
D. 276 ms

gate2009

operating-system

disk-scheduling

normal

Selected Answer

Answer is B.


1 votes

4.48 Disk Scheduling: GATE1999_1.10 top


Which of the following disk scheduling strategies is likely to give the best throughput?
A. Farthest cylinder next
B. Nearest cylinder next

Copyright GATE Overflow. All rights reserved.

-- Sona Praneeth Akula ( 3473 points)

gateoverflow.in/1463

GATE Overflow

April 2016

464 of 1876

C. First come first served


D. Elevator algorithm

gate1999

operating-system

disk-scheduling

normal

Option B
Nearest cylinder next but it can lead to starvation
-- Bhagirathi Nayak ( 10239 points)

2 votes

D.
Both the Nearest Cylinder and Elevator are high on throughput.But I will go with ELEVATOR.
Reason:
Nearest Cylinder Next algo will have a overhead of computing the nearest cylinders of the queue.
-- bahirNaik ( 2479 points)

1 votes

Farthest cylinder next -> This might be candidate for worst algorithm . This is false.
First come first served -> This will not give best throughput. It is random .
Elevator algorithm -> This is good but issue is that once direction is fixed we don't come back, until we go all the other
way. So it does not give best throughput.
B) Nearest cylinder next -> This is output.
-- Akash ( 26265 points)

1 votes

4.49 Dma: GATE2005_70 top

gateoverflow.in/1393

Consider a disk drive with the following specifications:


16 surfaces, 512 tracks/surface, 512 sectors/track, 1 KB/sector, rotation speed 3000 rpm. The disk is operated in cycle
stealing mode whereby whenever one 4 byte word is ready it is sent to memory; similarly, for writing, the disk interface
reads a 4 byte word from the memory in each DMA cycle. Memory cycle time is 40 nsec. The maximum percentage of time
that the CPU gets blocked during DMA operation is:

A. 10
B. 25
C. 40
D. 50

gate2005

operating-system

disk

normal

dma

B. 25
Does 3000 rotations in 60 seconds
 1 rotation in 20 ms
In 1 rotation covers data in 1 track which is = 512 1 KB
20 ms  512 KB
1 sec  25600 KB
 Transfer rate = 25600 KBps

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

465 of 1876

Transfer Rate means we can perform read or write operations(one at a time) with this speed.
In one DMA cycle of 40 ns we are able to transfer 4 Bytes to disk.
CPU Idle Time = 40 ns

4Bytes

Data Prepration Time = 25600KB = 156.25 ns


40ns

% Time CPU Blocked = 40ns+156.25ns 100 = 20.382


-- Amar Vashishth ( 17735 points)

6 votes

Rotational Latency
In 1 min. we have 3000 revolutions. Therefore, for one rotation we need
RotationalLatency = 60/3000 = 20ms
Sector Read/Write Time
In 20ms we can read 512 sectors. Therefore, for reading/writing one sector is
Time to read/write a sector = 20 ms/512 = 39.06s
To transfer 1KB of data from the disk to the memory
The transfer happens byte-wise as mentioned in the question for disk to memory.
The time to transfer 1KB of data using DMA with 40ns cycle time is
DMA Transfer Time = 40ns 1024 = 40.96s
The % time where the CPU will be blocked is
%CPU Block = DMA Transfer Time /Total Transfer Time
DMA Transfer Time

%CPU Block = DMA Transfer Time +Sector Read Time


%CPU Block = 40.96s/(40.96s + 39.96s)%CPU Block = 51.18 = (approx)50
If we consider transfer from memory to disk, since DMA transfers 4 byes in each DMA cycle, the CPU wait time is much
less (about 10%)
Therefore, the answer is (D) 50%
1 votes

-- Sriram Karunagaran ( 91 points)

ans is B.
Time takes for 1 rotation = 60/3000 . It reads 512*1 KBytes in one rotation (size of one track).
Time taken to read 4 bytes = [ 4/512 KB] * (60/300) = 153 ns 153 is approximately (160ns) .
Percentage of time CPU gets blocked = 40*100/160 = 25

1 votes

512 KB-1/50 sec


4 Byte transfer will take total :4/(512*50*2^10)=152.58 ns
DMA will transfer 4B in 40nsec
so Cpu will be blocked (40/152.58)=26 % of time
best matching ans is B

Copyright GATE Overflow. All rights reserved.

-- skrahul ( 275 points)

GATE Overflow

April 2016

466 of 1876
-- Anurag Semwal ( 4775 points)

1 votes

4.50 File: GATE2014-2_20 top

gateoverflow.in/1977

A FAT (file allocation table) based file system is being used and the total overhead of each entry in the FAT is 4 bytes in size. Given a 100 106 bytes disk on which
the file system is stored and data block size is 103 bytes, the maximum size of a file that can be stored on this disk in units of 106 bytes is _________.

gate2014-2

operating-system

disk

numerical-answers

normal

file

file-system

Selected Answer

Each datablock will have its entry.


Disk Capacity

So, Total Number of entries in the FAT =

Block size

100MB

= 1KB = 100K

each entry takes up 4B as overhead


so space occupied by overhead = 100K 4B = 400KB = 0.4MB
We have to give space to Overheads on the same file system and at the rest available space we can store data.
so, assuming that we use all available storage space to store a single file = Maximum file size =
Total File System sizeOverhead = 100MB 0.4MB = 99.6MB
-- Kalpish Singhal ( 1575 points)

8 votes

no of entries that can be stored=100*10^6/(1000+4) =0.09960*10^6


maximum file size=0.09960*10^6 * 10^3=99.6 *10^6
ans is 99.6
-- Anurag Semwal ( 4775 points)

1 votes

4.51 File System: GATE1996_23 top

gateoverflow.in/2775

A file system with a one-level directory structure is implemented on a disk with disk block size of 4K bytes. The disk is used
as follows:

Disk-block 0

File Allocation Table, consisting of one 8-bit


entry per data block, representing the data
block address of the next data block in the
file

Disk-block 1

Directory, with one 32 bit entry per file:

Disk-block 2
Disk-block 3

Data-block 1;
Data-block 2; etc.


a. What is the maximum possible number of files?
b. What is the maximum possible file size in blocks

gate1996

operating-system

disk

normal

file-system

a) Maximum possible number of files...


As per question, 32 bits (or 4 Bytes) are required per file. And there is only one block to store this, ie the Disk

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

467 of 1876

block 1, which is of size 4KB. So number of files possible is 4 KB/4 Bytes=1 K files possible...
b) Max file size..
As per question the Disk Block Address (FAT entry gives DBA) is of 8 bits.. So ideally the max file size should be
2^8=256 Block size.. But question makes it clear that two blocks , DB0 and DB1, stores control information. So
efectively we have 256-2 =254 blocks with us.. and the max file size shud be =254 * size of one block= 254 * 4 KB=
1016 KB..
-- Hunaif ( 435 points)

6 votes

4.52 File System: GATE2008_20 top

gateoverflow.in/418

The data blocks of a very large file in the Unix file system are allocated using
A. continuous allocation
B. linked allocation
C. indexed allocation
D. an extension of indexed allocation

gate2008

file-system

operating-system

normal

Selected Answer

The data blocks of a very large file in the unix file system are allocated using an extension of indexed allocation or EXT2
file system. Hence option (d) is the right answer.
-- Kalpna Bhargav ( 2931 points)

12 votes

4.53 File System: GATE2004-IT_67 top

gateoverflow.in/3710

In a particular Unix OS, each data block is of size 1024 bytes, each node has 10 direct data block addresses and three
additional addresses: one for single indirect block, one for double indirect block and one for triple indirect block. Also, each
block can contain addresses for 128 blocks. Which one of the following is approximately the maximum size of a file in the file
system?

A)
B)
C)

512 MB
2 GB
8 GB

D)

16 GB

gate2004-it

operating-system

file-system

normal

Selected Answer

Answer: B
Maximum file size = 10*1024 Bytes + 1*128*1024 Bytes + 1*128*128*1024 Bytes + 1*128*128*128*1024 Bytes =
approx 2 GB.
5 votes

-- Rajarshi Sarkar ( 27781 points)

Its 2GB
2 votes

Copyright GATE Overflow. All rights reserved.

-- Sandeep_Uniyal ( 5063 points)

GATE Overflow

April 2016

4.54 Fork: GATE2005_72 top

468 of 1876

gateoverflow.in/765

Consider the following code fragment:


if (fork() == 0)
{
a = a + 5;
printf("%d, %p n", a, &a);
}
else
{
a = a - 5;
printf ("%d, %p n", a,& a);
}

Let u,v be the values printed by the parent process and x,y be the values printed by the child process. Which one of the
following is TRUE?
a) x < u and y < v
b) x < u and y = v
c) x = u+10 and y < v
d) x = u+10 y = v
gate2005

operating-system

fork

normal

Selected Answer

(d) is the answer. Child is incrementing a by 5 and parent is decrementing a by 5. So, x = u + 10.
During fork(), address space of parent is copied for the child. So, any modifications to child variable won't affect the
parent variable or vice-verse. But this copy is for physical pages of memory. The logical addresses remains the same
between the parent and child processes.
-- gatecse ( 9515 points)

7 votes

4.55 Fork: GATE2004-IT_64 top

gateoverflow.in/3707

A process executes the following segment of code :


for(i = 1; i < = n; i++)
fork ();

The number of new processes created is



A)
B)

n
((n(n + 1))/2)

C)

2n - 1

D)

3n - 1

gate2004-it

operating-system

fork

easy

Selected Answer

option C.
At each fork, the number of processes doubles like from 1 - 2- 4 - 8 ... 2n. Of these except 1, all are child processes.
7 votes

4.56 Fork: GATE2008_66 top

Copyright GATE Overflow. All rights reserved.

-- prakash ( 245 points)

gateoverflow.in/489

GATE Overflow

April 2016

469 of 1876

A process executes the following code


for(i=0; i<n; i++) fork();

The total number of child processes created is


(A) n (B) 2 n-1 (C) 2 n (D) 2n+1 - 1

gate2008

operating-system

fork

normal

Selected Answer

Each fork() creates a child which start executing from that point onward. So, number of child processes created will be
2n - 1.
At each fork, the number of processes doubles like from 1 - 2- 4 - 8 ... 2 n. Of these except 1, all are child processes.
http://gateoverflow.in/3707/gate2004-it_64
-- Arjun Suresh ( 124085 points)

8 votes

4.57 Interrupts: GATE1998_1.18 top

gateoverflow.in/1655

Which of the following devices should get higher priority in assigning interrupts?
A. Hard disk
B. Printer
C. Keyboard
D. Floppy disk

gate1998

operating-system

interrupts

normal

Selected Answer

It should be a Hard disk. I don't think there is a rule like that. But hard disk makes sense compared to others here.
http://www.ibm1130.net/functional/IOInterrupts.html
4 votes

-- Arjun Suresh ( 124085 points)

4.58 Interrupts: GATE2011_11 top


A computer handles several interrupt sources of which of the following are relevant for this question.
Interrupt from CPU temperature sensor (raises interrupt if CPU temperature is too high)
Interrupt from Mouse (raises Interrupt if the mouse is moved or a button is pressed)
Interrupt from Keyboard (raises Interrupt if a key is pressed or released)
Interrupt from Hard Disk (raises Interrupt when a disk read is completed)
Which one of these will be handled at the HIGHEST priority?
(A) Interrupt from Hard Disk
(B) Interrupt from Mouse
(C) Interrupt from Keyboard
(D) Interrupt from CPU temperature sensor

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/2113

GATE Overflow
gate2011

April 2016

operating-system

interrupts

470 of 1876

normal

Selected Answer

Answer should be (D) Higher priority interrupt levels are assigned to requests which, if delayed or interrupted,could have
serious consequences. Devices with high speed transfer such as magnetic disks are given high priority, and slow devices
such as keyboard receive low priority. We know that mouse pointer movements are more frequent than keyboard ticks. So
its obvious that its data transfer rate is higher than keyboard. Delaying a CPU temperature sensor could have serious
consequences, overheat can damage CPU circuitry. From the above information we can conclude that priorities areCPU temperature sensor > Hard Disk > Mouse > Keyboard
-- Tejas Jaiswal ( 461 points)

10 votes

4.59 Interrupts: GATE1997_3.8 top

gateoverflow.in/2239

When an interrupt occurs, an operating system


A. ignores the interrupt
B. always changes state of interrupted process after processing the interrupt
C. always resumes execution of interrupted process after processing the interrupt
D. may change state of interrupted process to blocked and schedule another process.

gate1997

operating-system

interrupts

normal

A. Depends on the priority.


B. Not always.
C. Not always. If some high priority interrupt comes during execution of current interrupt, then?
D. Seems to be correct.
-- Monanshi Jain ( 5787 points)

5 votes

4.60 Interrupts: GATE1993_6.8 top

gateoverflow.in/2290

The details of an interrupt cycle are shown in figure.

Given that an interrupt input arrives every 1 msec, what is the percentage of the total time that the CPU devotes for the
main program execution.

gate1993

operating-system

interrupts

normal

CPU overhead will be saving context + serving interrupt + restoration .

Copyright GATE Overflow. All rights reserved.

GATE Overflow

April 2016

471 of 1876

out of 1ms these things are overhead for CPU.


OVERHEAD % = (10 + 80 +10)*10^(-6)/1*10^(-3) *100
= 10%
% of time CPU devoted to main program = 90%
-- Digvijay Pandey ( 26235 points)

3 votes

4.61 Interrupts: GATE2001_1.12 top

gateoverflow.in/705

A processor needs software interrupt to


(A) test the interrupt system of the processor
(B) implement co-routines
(C) obtain system services which need execution of privileged instructions
(D) return from subroutine
gate2001

operating-system

interrupts

easy

Selected Answer

ans is C.
A and B are obviously incorrect. In D no need to change mode while returning from any subroutine. therefore software
interrupt is not needed for that. But in C to execute any privileged instruction processor needs software interrupt while
changing mode.
-- jayendra ( 5797 points)

7 votes

4.62 Io Handling: GATE1998_1.29 top

gateoverflow.in/1666

Which of the following is an example of a spooled device?


A. The terminal used to enter the input data for the C program being executed
B. An output device used to print the output of a number of jobs
C. The secondary memory device in a virtual storage system
D. The swapping area on a disk used by the swapper

gate1998

operating-system

io-handling

easy

Selected Answer

Ans B
http://en.wikipedia.org/wiki/Spooling
4 votes

-- Keith Kr ( 5467 points)

4.63 Io Handling: GATE2005_19 top


Which one of the following is true for a CPU having a single interrupt request line and a single interrupt grant line?

A. Neither vectored interrupt nor multiple interrupting devices are possible

Copyright GATE Overflow. All rights reserved.

gateoverflow.in/1355

GATE Overflow

April 2016

472 of 1876

B. Vectored interrupts are not possible but multiple interrupting devices are possible
C. Vectored interrupts and multiple interrupting devices are both possible
D. Vectored interrupts are possible but multiple interrupting devices are not possible

gate2005

operating-system

io-handling

normal

C. is the right option.


Daisy chain can be used.
-- shreya ghosh ( 2801 points)

2 votes

4.64 Io Handling: GATE1995_17 top

gateoverflow.in/2653

a. An asynchronous serial communication controller that uses a start-stop scheme for controlling the serial I/O of a system
is programmed for a string of length seven bits, one parity