0% found this document useful (0 votes)
13 views119 pages

DSA MCQs

The document contains a series of multiple-choice questions (MCQs) related to data structures and algorithms, covering topics such as arrays, stacks, queues, trees, and their applications. Each question is followed by the correct answer and an explanation of the concepts involved. The content is designed to test knowledge and understanding of fundamental data structures used in computer science.

Uploaded by

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

DSA MCQs

The document contains a series of multiple-choice questions (MCQs) related to data structures and algorithms, covering topics such as arrays, stacks, queues, trees, and their applications. Each question is followed by the correct answer and an explanation of the concepts involved. The content is designed to test knowledge and understanding of fundamental data structures used in computer science.

Uploaded by

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

DSA MCQs

1. What is a data structure?


a) A programming language
b) A collection of algorithms
c) A way to store and organize data
d) A type of computer hardware
View Answer
Answer: c
Explanation: A data structure is a way to store and organize data efficiently,
enhancing access and manipulation, unlike programming languages,
algorithms, or computer hardware.
2. What are the disadvantages of arrays?
a) Index value of an array can be negative
b) Elements are sequentially accessed
c) Data structure like queue or stack cannot be implemented
d) There are chances of wastage of memory space if elements inserted in an
array are lesser than the allocated size
View Answer
Answer: d
Explanation: Arrays are of fixed size. If we insert elements less than the
allocated size, unoccupied positions can’t be used again. Wastage will occur in
memory.
3. Which data structure is used for implementing recursion?
a) Stack
b) Queue
c) List
d) Array
View Answer
Answer: a
Explanation: Stacks are used for the implementation of Recursion.
4. The data structure required to check whether an expression contains a
balanced parenthesis is?
a) Queue
b) Stack
c) Tree
d) Array
View Answer
Answer: b
Explanation: The stack is a simple data structure in which elements are added
and removed based on the LIFO principle. Open parenthesis is pushed into the
stack and a closed parenthesis pops out elements till the top element of the
stack is its corresponding open parenthesis. If the stack is empty, parenthesis is
balanced otherwise it is unbalanced.
5. Which of the following is not the application of stack?
a) Data Transfer between two asynchronous process
b) Compiler Syntax Analyzer
c) Tracking of local variables at run time
d) A parentheses balancing program
View Answer
Answer: a
Explanation: Data transfer between the two asynchronous process uses the
queue data structure for synchronisation. The rest are all stack applications.
advertisement
6. Which data structure is needed to convert infix notation to postfix notation?
a) Tree
b) Branch
c) Stack
d) Queue
View Answer
Answer: c
Explanation: The Stack data structure is used to convert infix expression to
postfix expression. The purpose of stack is to reverse the order of the
operators in the expression. It also serves as a storage structure, as no
operator can be printed until both of its operands have appeared.
7. What is the value of the postfix expression 6 3 2 4 + – *?
a) 74
b) -18
c) 22
d) 40
View Answer
Answer: b
Explanation: Postfix Expression is (6*(3-(2+4))) which results -18 as output.
8. What data structure would you mostly likely see in non recursive
implementation of a recursive algorithm?
a) Stack
b) Linked List
c) Tree
d) Queue
View Answer
Answer: a
Explanation: In recursive algorithms, the order in which the recursive process
comes back is the reverse of the order in which it goes forward during
execution. The compiler uses the stack data structure to implement recursion.
In the forwarding phase, the values of local variables, parameters and the
return address are pushed into the stack at each recursion level. In the
backing-out phase, the stacked address is popped and used to execute the rest
of the code.
9. Which of the following statement(s) about stack data structure is/are NOT
correct?
a) Top of the Stack always contain the new node
b) Stack is the FIFO data structure
c) Null link is present in the last node at the bottom of the stack
d) Linked List are used for implementing Stacks
View Answer
Answer: b
Explanation: Stack follows LIFO.
10. The data structure required for Breadth First Traversal on a graph is?
a) Array
b) Stack
c) Tree
d) Queue
View Answer
Answer: d
Explanation: In Breadth First Search Traversal, BFS, starting vertex is first taken
and adjacent vertices which are unvisited are also taken. Again, the first vertex
which was added as an unvisited adjacent vertex list will be considered to add
further unvisited vertices of the graph. To get the first unvisited vertex we
need to follows First In First Out principle. Queue uses FIFO principle.
11. The prefix form of A-B/ (C * D ^ E) is?
a) -A/B*C^DE
b) -A/BC*^DE
c) -ABCD*^DE
d) -/*^ACBDE
View Answer
Answer: a
Explanation: Infix Expression is A-B/(C*D^E)
This can be written as: A-(B/(C*(D^E)))
Thus prefix expression is -A/B*C^DE.
12. Which of the following points is/are not true about Linked List data
structure when it is compared with an array?
a) Random access is not allowed in a typical implementation of Linked Lists
b) Access of elements in linked list takes less time than compared to arrays
c) Arrays have better cache locality that can make them better in terms of
performance
d) It is easy to insert and delete elements in Linked List
View Answer
Answer: b
Explanation: To access an element in a linked list, we need to traverse every
element until we reach the desired element. This will take more time than
arrays as arrays provide random access to its elements.
13. Which data structure is based on the Last In First Out (LIFO) principle?
a) Tree
b) Linked List
c) Stack
d) Queue
View Answer
Answer: c
Explanation: The data structure that follows the Last In First Out (LIFO)
principle is the Stack. It operates like a stack of objects, making it suitable for
specific-order management.
14. Which of the following application makes use of a circular linked list?
a) Recursive function calls
b) Undo operation in a text editor
c) Implement Hash Tables
d) Allocating CPU to resources
View Answer
Answer: d
Explanation: Generally, round robin fashion is employed to allocate CPU time
to resources which makes use of the circular linked list data structure.
Recursive function calls use stack data structure. Undo Operation in text editor
uses doubly linked lists. Hash tables uses singly linked lists.
15. What is a bit array?
a) Data structure that compactly stores bits
b) Data structure for representing arrays of records
c) Array in which elements are not present in continuous locations
d) An array in which most of the elements have the same value
View Answer
Answer: a
Explanation: It compactly stores bits and exploits bit-level parallelism.
16. Which of the following tree data structures is not a balanced binary tree?
a) Splay tree
b) B-tree
c) AVL tree
d) Red-black tree
View Answer
Answer: b
Explanation: All the tree data structures given in options are balanced, but B-
tree can have more than two children.
17. Which of the following is not the type of queue?
a) Priority queue
b) Circular queue
c) Single ended queue
d) Ordinary queue
View Answer
Answer: c
Explanation: Queue always has two ends. So, single ended queue is not the
type of queue.
18. Which of the following data structures can be used for parentheses
matching?
a) n-ary tree
b) queue
c) priority queue
d) stack
View Answer
Answer: d
Explanation: For every opening brace, push it into the stack, and for every
closing brace, pop it off the stack. Do not take action for any other character.
In the end, if the stack is empty, then the input has balanced parentheses.
19. Which algorithm is used in the top tree data structure?
a) Backtracking
b) Divide and Conquer
c) Branch
d) Greedy
View Answer
Answer: b
Explanation: Top tree is a type of data structure which is based on unrooted
dynamic binary tree and is used to solve path related problems. It allows an
algorithm called divide and conquer.
20. What is the need for a circular queue?
a) easier computations
b) implement LIFO principle in queues
c) effective usage of memory
d) to delete elements based on priority
View Answer
Answer: c
Explanation: In a linear queue, dequeue operation causes the starting elements
of the array to be empty, and there is no way you can use that space, while in a
circular queue, you can effectively use that space. Priority queue is used to
delete the elements based on their priority. Higher priority elements will be
deleted first whereas lower priority elements will be deleted next. Queue data
structure always follows FIFO principle.
21. Which of the following is the most widely used external memory data
structure?
a) B-tree
b) Red-black tree
c) AVL tree
d) Both AVL tree and Red-black tree
View Answer
Answer: a
Explanation: In external memory, the data is transferred in form of blocks.
These blocks have data valued and pointers. And B-tree can hold both the data
values and pointers. So B-tree is used as an external memory data structure.
22. Which of the following is also known as Rope data structure?
a) Linked List
b) Array
c) String
d) Cord
View Answer
Answer: d
Explanation: Array is a linear data structure. Strings are a collection and
sequence of codes, alphabets or characters. Linked List is a linear data
structure having a node containing data input and the address of the next
node. The cord is also known as the rope data structure.
23. What will be the output of the following program?

main()
{
char str[]="san foundry";
int len = strlen(str);
int i;

for(i=0;i<len;i++)
push(str[i]); // pushes an element into stack

for(i=0;i<len;i++)
pop(); //pops an element from the stack
}
a) yrdnuof nas
b) foundry nas
c) sanfoundry
d) san foundry
View Answer
Answer: a
Explanation: First, the string ‘san foundry’ is pushed one by one into the stack.
When it is popped, the output will be as ‘yrdnuof nas’.
24. Which of the following data structure can provide efficient searching of the
elements?
a) binary search tree
b) unordered lists
c) 2-3 tree
d) treap
View Answer
Answer: c
Explanation: The average case time for lookup in a binary search tree, treap
and 2-3 tree is O(log n) and in unordered lists it is O(n). But in the worst case,
only the 2-3 trees perform lookup efficiently as it takes O(log n), while others
take O(n).
25. What is an AVL tree?
a) a tree which is unbalanced and is a height balanced tree
b) a tree which is balanced and is a height balanced tree
c) a tree with atmost 3 children
d) a tree with three children
View Answer
Answer: b
Explanation: It is a self balancing tree with height difference atmost 1.
26. What is the time complexity for searching a key or integer in Van Emde
Boas data structure?
a) O (M!)
b) O (log M!)
c) O (log (log M))
d) O (M2)
View Answer
Answer: c
Explanation: In order to search a key or integer in the Van Emde Boas data
structure, the operation can be performed on an associative array. Hence, the
time complexity for searching a key or integer in Van Emde Boas data structure
is O (log (log M)).
27. The optimal data structure used to solve Tower of Hanoi is _________
a) Tree
b) Heap
c) Priority queue
d) Stack
View Answer
Answer: d
Explanation: The Tower of Hanoi involves moving of disks ‘stacked’ at one peg
to another peg with respect to the size constraint. It is conveniently done using
stacks and priority queues. Stack approach is widely used to solve Tower of
Hanoi.
28. What is the use of the bin data structure?
a) to have efficient traversal
b) to have efficient region query
c) to have efficient deletion
d) to have efficient insertion
View Answer
Answer: b
Explanation: Bin data structure allows us to have efficient region queries. A
frequency of bin is increased by one each time a data point falls into a bin.
29. Which is the most appropriate data structure for reversing a word?
a) stack
b) queue
c) graph
d) tree
View Answer
Answer: a
Explanation: Stack is the most appropriate data structure for reversing a word
because stack follows LIFO principle.
30. What is the functionality of the following piece of code?

public void display()


{
if(size == 0)
System.out.println("underflow");
else
{
Node current = first;
while(current != null)
{
System.out.println(current.getEle());
current = current.getNext();
}
}
}
a) display the list
b) reverse the list
c) reverse the list excluding top-of-the-stack-element
d) display the list excluding top-of-the-stack-element
View Answer
Answer: a
Explanation: An alias of the node ‘first’ is created which traverses through the
list and displays the elements.
31. Which of the following is the simplest data structure that supports range
searching?
a) AA-trees
b) K-d trees
c) Heaps
d) binary search trees
View Answer
Answer: c
Explanation: K-d trees are the simplest data structure that supports range
searching and also it achieves the respectable running time.
32. What is the advantage of a hash table as a data structure?
a) easy to implement
b) faster access of data
c) exhibit good locality of reference
d) very efficient for less number of entries
View Answer
Answer: b
Explanation: Hash table is a data structure that has an advantage that it allows
fast access of elements. Hash functions are used to determine the index of any
input record in a hash table.
33. Which type of data structure is a ternary heap?
a) Hash
b) Array
c) Priority Stack
d) Priority Queue
View Answer
Answer: d
Explanation: Ternary heap is a type of data structure in the field of computer
science. It is a part of the Heap data structure family. It is a priority queue type
of data structure that follows all the property of heap.
34. What is a dequeue?
a) A queue implemented with both singly and doubly linked lists
b) A queue with insert/delete defined for front side of the queue
c) A queue with insert/delete defined for both front and rear ends of the
queue
d) A queue implemented with a doubly linked list
View Answer
Answer: c
Explanation: A dequeue or a double ended queue is a queue with insert/delete
defined for both front and rear ends of the queue.
35. A data structure in which elements can be inserted or deleted at/from both
ends but not in the middle is?
a) Priority queue
b) Dequeue
c) Circular queue
d) Queue
View Answer
Answer: b
Explanation: In dequeuer, we can insert or delete elements from both the
ends. In queue, we will follow first in first out principle for insertion and
deletion of elements. Element with least priority will be deleted in a priority
queue.
36. What is the output of the following Java code?

public class array


{
public static void main(String args[])
{
int []arr = {1,2,3,4,5};
System.out.println(arr[2]);
System.out.println(arr[4]);
}
}
a) 4 and 2
b) 2 and 4
c) 5 and 3
d) 3 and 5
View Answer
Answer: d
Explanation: Array indexing starts from 0.
37. In simple chaining, what data structure is appropriate?
a) Doubly linked list
b) Circular linked list
c) Singly linked list
d) Binary trees
View Answer
Answer: a
Explanation: Deletion becomes easier with doubly linked list, hence it is
appropriate.
1. Which of these best describes an array?
a) A data structure that shows a hierarchical behavior
b) Container of objects of similar types
c) Arrays are immutable once initialised
d) Array is not a data structure
View Answer
Answer: b
Explanation: Array contains elements only of the same type.
2. How do you initialize an array in C?
a) int arr[3] = (1,2,3);
b) int arr(3) = {1,2,3};
c) int arr[3] = {1,2,3};
d) int arr(3) = (1,2,3);
View Answer
Answer: c
Explanation: This is the syntax to initialize an array in C.
3. How do you instantiate an array in Java?
a) int arr[] = new int(3);
b) int arr[];
c) int arr[] = new int[3];
d) int arr() = new int(3);
View Answer
Answer: c
Explanation: Note that int arr[]; is declaration whereas int arr[] = new int[3]; is
to instantiate an array.
advertisement
4. Which of the following is the correct way to declare a multidimensional
array in Java?
a) int[] arr;
b) int arr[[]];
c) int[][]arr;
d) int[[]] arr;
View Answer
Answer: c
Explanation: The syntax to declare multidimensional array in java is either
int[][] arr; or int arr[][];
5. What is the output of the following Java code?

Subscribe Now: Data Structure Newsletter | Important Subjects Newsletters


public class array
{
public static void main(String args[])
{
int []arr = {1,2,3,4,5};
System.out.println(arr[2]);
System.out.println(arr[4]);
}
}
a) 3 and 5
b) 5 and 3
c) 2 and 4
d) 4 and 2
View Answer
Answer: a
Explanation: Array indexing starts from 0.
6. What is the output of the following Java code?

public class array


{
public static void main(String args[])
{
int []arr = {1,2,3,4,5};
System.out.println(arr[5]);
}
}
a) 4
b) 5
c) ArrayIndexOutOfBoundsException
d) InavlidInputException
View Answer
Answer: c
Explanation: Trying to access an element beyond the limits of an array gives
ArrayIndexOutOfBoundsException.
7. When does the ArrayIndexOutOfBoundsException occur?
a) Compile-time
b) Run-time
c) Not an error
d) Not an exception at all
View Answer
Answer: b
Explanation: ArrayIndexOutOfBoundsException is a run-time exception and the
compilation is error-free.
8. Which of the following concepts make extensive use of arrays?
a) Binary trees
b) Scheduling of processes
c) Caching
d) Spatial locality
View Answer
Answer: d
Explanation: Whenever a particular memory location is referred to, it is likely
that the locations nearby are also referred, arrays are stored as contiguous
blocks in memory, so if you want to access array elements, spatial locality
makes it to access quickly.
9. What are the advantages of arrays?
a) Objects of mixed data types can be stored
b) Elements in an array cannot be sorted
c) Index of first element of an array is 1
d) Easier to store elements of same data type
View Answer
Answer: d
Explanation: Arrays store elements of the same data type and present in
continuous memory locations.
10. What are the disadvantages of arrays?
a) Data structure like queue or stack cannot be implemented
b) There are chances of wastage of memory space if elements inserted in an
array are lesser than the allocated size
c) Index value of an array can be negative
d) Elements are sequentially accessed
View Answer
Answer: b
Explanation: Arrays are of fixed size. If we insert elements less than the
allocated size, unoccupied positions can’t be used again. Wastage will occur in
memory.
11. Assuming int is of 4bytes, what is the size of int arr[15];?
a) 15
b) 19
c) 11
d) 60
View Answer
Answer: d
Explanation: Since there are 15 int elements and each int is of 4bytes, we get
15*4 = 60bytes.
12. In general, the index of the first element in an array is __________
a) 0
b) -1
c) 2
d) 1
View Answer
Answer: a
Explanation: In general, Array Indexing starts from 0. Thus, the index of the
first element in an array is 0.
13. Elements in an array are accessed _____________
a) randomly
b) sequentially
c) exponentially
d) logarithmically
View Answer
Answer: a
Explanation: Elements in an array are accessed randomly. In Linked lists,
elements are accessed sequentially.
1. Process of inserting an element in stack is called ____________
a) Create
b) Push
c) Evaluation
d) Pop
View Answer
Answer: b
Explanation: Push operation allows users to insert elements in the stack. If the
stack is filled completely and trying to perform push operation stack – overflow
can happen.
2. Process of removing an element from stack is called __________
a) Create
b) Push
c) Evaluation
d) Pop
View Answer
Answer: d
Explanation: Elements in the stack are removed using pop operation. Pop
operation removes the top most element in the stack i.e. last entered element.
3. In a stack, if a user tries to remove an element from an empty stack it is
called _________
a) Underflow
b) Empty collection
c) Overflow
d) Garbage Collection
View Answer
Answer: a
Explanation: Underflow occurs when the user performs a pop operation on an
empty stack. Overflow occurs when the stack is full and the user performs a
push operation. Garbage Collection is used to recover the memory occupied by
objects that are no longer used.
advertisement
4. Pushing an element into stack already having five elements and stack size of
5, then stack becomes ___________
a) Overflow
b) Crash
c) Underflow
d) User flow
View Answer
Answer: a
Explanation: The stack is filled with 5 elements and pushing one more element
causes a stack overflow. This results in overwriting memory, code and loss of
unsaved work on the computer.
5. Entries in a stack are “ordered”. What is the meaning of this statement?
a) A collection of stacks is sortable
b) Stack entries may be compared with the ‘<‘ operation
c) The entries are stored in a linked list
d) There is a Sequential entry that is one by one
View Answer
Answer: d
Explanation: In stack data structure, elements are added one by one using
push operation. Stack follows LIFO Principle i.e. Last In First Out(LIFO).
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
Participate Now!
6. Which of the following is not the application of stack?
a) A parentheses balancing program
b) Tracking of local variables at run time
c) Compiler Syntax Analyzer
d) Data Transfer between two asynchronous process
View Answer
Answer: d
Explanation: Data transfer between the two asynchronous process uses the
queue data structure for synchronisation. The rest are all stack applications.
7. Consider the usual algorithm for determining whether a sequence of
parentheses is balanced. The maximum number of parentheses that appear on
the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
a) 1
b) 2
c) 3
d) 4 or more
View Answer
Answer: c
Explanation: In the entire parenthesis balancing method when the incoming
token is a left parenthesis it is pushed into stack. A right parenthesis makes
pop operation to delete the elements in stack till we get left parenthesis as top
most element. 3 elements are there in stack before right parentheses comes.
Therefore, maximum number of elements in stack at run time is 3.
8. Consider the usual algorithm for determining whether a sequence of
parentheses is balanced. Suppose that you run the algorithm on a sequence
that contains 2 left parentheses and 3 right parentheses (in some order). The
maximum number of parentheses that appear on the stack AT ANY ONE TIME
during the computation?
a) 1
b) 2
c) 3
d) 4 or more
View Answer
Answer: b
Explanation: In the entire parenthesis balancing method when the incoming
token is a left parenthesis it is pushed into stack. A right parenthesis makes
pop operation to delete the elements in stack till we get left parenthesis as top
most element. 2 left parenthesis are pushed whereas one right parenthesis
removes one of left parenthesis. 2 elements are there before right parenthesis
which is the maximum number of elements in stack at run time.
9. What is the value of the postfix expression 6 3 2 4 + – *?
a) 1
b) 40
c) 74
d) -18
View Answer
Answer: d
Explanation: Postfix Expression is (6*(3-(2+4))) which results -18 as output.
10. Here is an infix expression: 4 + 3*(6*3-12). Suppose that we are using the
usual stack algorithm to convert the expression from infix to postfix notation.
The maximum number of symbols that will appear on the stack AT ONE TIME
during the conversion of this expression?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: d
Explanation: When we perform the conversion from infix to postfix expression
+, *, (, * symbols are placed inside the stack. A maximum of 4 symbols are
identified during the entire conversion.
1. The postfix form of the expression (A+ B)*(C*D- E)*F / G is?
a) AB+ CD*E – FG /**
b) AB + CD* E – F **G /
c) AB + CD* E – *F *G /
d) AB + CDE * – * F *G /
View Answer
Answer: c
Explanation: (((A+ B)*(C*D- E)*F) / G) is converted to postfix expression as
(AB+(*(C*D- E)*F )/ G)
(AB+CD*E-*F) / G
(AB+CD*E-*F * G/). Thus Postfix expression is AB+CD*E-*F*G/
2. The data structure required to check whether an expression contains a
balanced parenthesis is?
a) Stack
b) Queue
c) Array
d) Tree
View Answer
Answer: a
Explanation: The stack is a simple data structure in which elements are added
and removed based on the LIFO principle. Open parenthesis is pushed into the
stack and a closed parenthesis pops out elements till the top element of the
stack is its corresponding open parenthesis. If the stack is empty, parenthesis is
balanced otherwise it is unbalanced.
3. What data structure would you most likely see in non recursive
implementation of a recursive algorithm?
a) Linked List
b) Stack
c) Queue
d) Tree
View Answer
Answer: b
Explanation: In recursive algorithms, the order in which the recursive process
comes back is the reverse of the order in which it goes forward during
execution. The compiler uses the stack data structure to implement recursion.
In the forwarding phase, the values of local variables, parameters and the
return address are pushed into the stack at each recursion level. In the
backing-out phase, the stacked address is popped and used to execute the rest
of the code.
advertisement
4. The process of accessing data stored in a serial access memory is similar to
manipulating data on a ________
a) Heap
b) Binary Tree
c) Array
d) Stack
View Answer
Answer: d
Explanation: In serial access memory data records are stored one after the
other in which they are created and are accessed sequentially. In stack data
structure, elements are accessed sequentially. Stack data structure resembles
the serial access memory.
5. The postfix form of A*B+C/D is?
a) *AB/CD+
b) AB*CD/+
c) A*BC+/D
d) ABCD+/*
View Answer
Answer: b
Explanation: Infix expression is (A*B)+(C/D)
AB*+(C/D)
AB*CD/+. Thus postfix expression is AB*CD/+.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
Participate Now!
6. Which data structure is needed to convert infix notation to postfix notation?
a) Branch
b) Tree
c) Queue
d) Stack
View Answer
Answer: d
Explanation: The Stack data structure is used to convert infix expression to
postfix expression. The purpose of stack is to reverse the order of the
operators in the expression. It also serves as a storage structure, as no
operator can be printed until both of its operands have appeared.
7. The prefix form of A-B/ (C * D ^ E) is?
a) -/*^ACBDE
b) -ABCD*^DE
c) -A/B*C^DE
d) -A/BC*^DE
View Answer
Answer: c
Explanation: Infix Expression is (A-B)/(C*D^E)
(-A/B)(C*D^E)
-A/B*C^DE. Thus prefix expression is -A/B*C^DE.
8. What is the result of the following operation?
Top (Push (S, X))
a) X
b) X+S
c) S
d) XS
View Answer
Answer: a
Explanation: The function Push(S,X) pushes the value X in the stack S. Top()
function gives the value which entered last. X entered into stack S at last.
9. The prefix form of an infix expression (p + q) – (r * t) is?
a) + pq – *rt
b) – +pqr * t
c) – +pq * rt
d) – + * pqrt
View Answer
Answer: c
Explanation: Given Infix Expression is ((p+q)-(r*t))
(+pq)-(r*t)
(-+pq)(r*t)
-+pq*rt. Thus prefix expression is -+pq*rt.
10. Which data structure is used for implementing recursion?
a) Queue
b) Stack
c) Array
d) List
View Answer
Answer: b
Explanation: Stacks are used for the implementation of Recursion.
1. The result of evaluating the postfix expression 5, 4, 6, +, *, 4, 9, 3, /, +, * is?
a) 600
b) 350
c) 650
d) 588
View Answer
Answer: b
Explanation: The postfix expression is evaluated using stack. We will get the
infix expression as
(5*(4+6))*(4+9/3). On solving the Infix Expression, we get
(5*(10))*(4+3)
= 50*7
= 350.
2. Convert the following infix expressions into its equivalent postfix
expressions.
(A + B ⋀D)/(E – F)+G
a) (A B D ⋀ + E F – / G +)
b) (A B D +⋀ E F – / G +)
c) (A B D ⋀ + E F/- G +)
d) (A B D E F + ⋀ / – G +)
View Answer
Answer: a
Explanation: The given infix expression is (A + B ⋀D)/(E – F)+G.
(A B D ^ + ) / (E – F) +G
(A B D ^ + E F – ) + G. ‘/’ is present in stack.
A B D ^ + E F – / G +. Thus Postfix Expression is A B D ^ + E F – / G +.
3. Convert the following Infix expression to Postfix form using a stack.
x + y * z + (p * q + r) * s, Follow usual precedence rule and assume that the
expression is legal.
a) xyz*+pq*r+s*+
b) xyz*+pq*r+s+*
c) xyz+*pq*r+s*+
d) xyzp+**qr+s*+
View Answer
Answer: a
Explanation: The Infix Expression is x + y * z + (p * q + r) * s.
(x y z ) + (p * q + r) * s. ‘+’, ‘*’ are present in stack.
(x y z * + p q * r) * s. ‘+’ is present in stack.
x y z * + p q * r + s * +. Thus Postfix Expression is x y z * + p q * r + s * +.
advertisement
4. Which of the following statement(s) about stack data structure is/are NOT
correct?
a) Linked List are used for implementing Stacks
b) Top of the Stack always contain the new node
c) Stack is the FIFO data structure
d) Null link is present in the last node at the bottom of the stack
View Answer
Answer: c
Explanation: Stack follows LIFO.
5. Consider the following operation performed on a stack of size 5.

Push(1);

Pop();

Push(2);

Push(3);

Pop();

Push(4);

Pop();

Pop();

Push(5);

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.


Participate Now!
After the completion of all operation, the number of elements present in stack
is?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: a
Explanation: Number of elements present in stack is equal to the difference
between number of push operations and number of pop operations. Number
of elements is 5-4=1.
6. Which of the following is not an inherent application of stack?
a) Reversing a string
b) Evaluation of postfix expression
c) Implementation of recursion
d) Job scheduling
View Answer
Answer: d
Explanation: Job Scheduling is not performed using stacks.
7. The type of expression in which operator succeeds its operands is?
a) Infix Expression
b) Prefix Expression
c) Postfix Expression
d) Both Prefix and Postfix Expressions
View Answer
Answer: c
Explanation: The expression in which operator succeeds its operands is called
postfix expression. The expression in which operator precedes the operands is
called prefix expression. If an operator is present between two operands, then
it is called infix expressions.
8. Assume that the operators +,-, X are left associative and ^ is right
associative. The order of precedence (from highest to lowest) is ^, X, +, -. The
postfix expression for the infix expression a + b X c – d ^ e ^ f is?
a) abc X+ def ^^ –
b) abc X+ de^f^ –
c) ab+c Xd – e ^f^
d) -+aXbc^ ^def
View Answer
Answer: b
Explanation: Given Infix Expression is a + b X c – d ^ e ^ f. And X is right
associative. Thus the final postfix expression is abc X+def^^-
9. If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted
one at a time, what is the order of removal?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
View Answer
Answer: b
Explanation: Stack follows LIFO(Last In First Out). So the removal order of
elements are DCBA.
1. A linear list of elements in which deletion can be done from one end (front)
and insertion can take place only at the other end (rear) is known as
_____________
a) Queue
b) Stack
c) Tree
d) Linked list
View Answer
Answer: a
Explanation: Linear list of elements in which deletion is done at front side and
insertion at rear side is called Queue. In stack we will delete the last entered
element first.
2. The data structure required for Breadth First Traversal on a graph is?
a) Stack
b) Array
c) Queue
d) Tree
View Answer
Answer: c
Explanation: In Breadth First Search Traversal, BFS, starting vertex is first taken
and adjacent vertices which are unvisited are also taken. Again, the first vertex
which was added as an unvisited adjacent vertex list will be considered to add
further unvisited vertices of the graph. To get the first unvisited vertex we
need to follows First In First Out principle. Queue uses FIFO principle.
3. A queue follows __________
a) FIFO (First In First Out) principle
b) LIFO (Last In First Out) principle
c) Ordered array
d) Linear tree
View Answer
Answer: a
Explanation: Element first added in queue will be deleted first which is FIFO
principle.
advertisement
4. Circular Queue is also known as ________
a) Ring Buffer
b) Square Buffer
c) Rectangle Buffer
d) Curve Buffer
View Answer
Answer: a
Explanation: Circular Queue is also called as Ring Buffer. Circular Queue is a
linear data structure in which last position is connected back to the first
position to make a circle. It forms a ring structure.
5. If the elements “A”, “B”, “C” and “D” are placed in a queue and are deleted
one at a time, in what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
View Answer
Answer: a
Explanation: Queue follows FIFO approach. i.e. First in First Out Approach. So,
the order of removal elements are ABCD.
Subscribe Now: Data Structure Newsletter | Important Subjects Newsletters
6. A data structure in which elements can be inserted or deleted at/from both
ends but not in the middle is?
a) Queue
b) Circular queue
c) Dequeue
d) Priority queue
View Answer
Answer: c
Explanation: In dequeuer, we can insert or delete elements from both the
ends. In queue, we will follow first in first out principle for insertion and
deletion of elements. Element with least priority will be deleted in a priority
queue.
7. A normal queue, if implemented using an array of size MAX_SIZE, gets full
when?
a) Rear = MAX_SIZE – 1
b) Front = (rear + 1)mod MAX_SIZE
c) Front = rear + 1
d) Rear = front
View Answer
Answer: a
Explanation: When Rear = MAX_SIZE – 1, there will be no space left for the
elements to be added in queue. Thus queue becomes full.
8. Queues serve major role in ______________
a) Simulation of recursion
b) Simulation of arbitrary linked list
c) Simulation of limited resource allocation
d) Simulation of heap sort
View Answer
Answer: c
Explanation: Simulation of recursion uses stack data structure. Simulation of
arbitrary linked lists uses linked lists. Simulation of resource allocation uses
queue as first entered data needs to be given first priority during resource
allocation. Simulation of heap sort uses heap data structure.
9. Which of the following is not the type of queue?
a) Ordinary queue
b) Single ended queue
c) Circular queue
d) Priority queue
View Answer
Answer: b
Explanation: Queue always has two ends. So, single ended queue is not the
type of queue.
1. A linear collection of data elements where the linear node is given by means
of pointer is called?
a) Linked list
b) Node list
c) Primitive list
d) Unordered list
View Answer
Answer: a
Explanation: In Linked list each node has its own data and the address of next
node. These nodes are linked by using pointers. Node list is an object that
consists of a list of all nodes in a document with in a particular selected set of
nodes.
2. Consider an implementation of unsorted singly linked list. Suppose it has its
representation with a head pointer only. Given the representation, which of
the following operation can be implemented in O(1) time?

i) Insertion at the front of the linked list


ii) Insertion at the end of the linked list
iii) Deletion of the front node of the linked list
iv) Deletion of the last node of the linked list
a) I and II
b) I and III
c) I, II and III
d) I, II and IV
View Answer
Answer: b
Explanation: We know the head node in the given linked list. Insertion and
deletion of elements at the front of the linked list completes in O (1) time
whereas for insertion and deletion at the last node requires to traverse
through every node in the linked list. Suppose there are n elements in a linked
list, we need to traverse through each node. Hence time complexity becomes
O(n).
advertisement
3. In linked list each node contains a minimum of two fields. One field is data
field to store the data second field is?
a) Pointer to character
b) Pointer to integer
c) Pointer to node
d) Node
View Answer
Answer: c
Explanation: Each node in a linked list contains data and a pointer (reference)
to the next node. Second field contains pointer to node.
Note: Join free Sanfoundry classes at Telegram or Youtube
4. What would be the asymptotic time complexity to add a node at the end of
singly linked list, if the pointer is initially pointing to the head of the list?
a) O(1)
b) O(n)
c) θ(n)
d) θ(1)
View Answer
Answer: c
Explanation: In case of a linked list having n elements, we need to travel
through every node of the list to add the element at the end of the list. Thus
asymptotic time complexity is θ(n).
5. What would be the asymptotic time complexity to insert an element at the
front of the linked list (head is known)?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
View Answer
Answer: a
Explanation: To add an element at the front of the linked list, we will create a
new node which holds the data to be added to the linked list and pointer
which points to head position in the linked list. The entire thing happens within
O (1) time. Thus the asymptotic time complexity is O (1).
6. What would be the asymptotic time complexity to find an element in the
linked list?
a) O(1)
b) O(n)
c) O(n2)
d) O(n4)
View Answer
Answer: b
Explanation: If the required element is in the last position, we need to traverse
the entire linked list. This will take O (n) time to search the element.
7. What would be the asymptotic time complexity to insert an element at the
second position in the linked list?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
View Answer
Answer: a
Explanation: A new node is created with the required element. The pointer of
the new node points the node to which the head node of the linked list is also
pointing. The head node pointer is changed and it points to the new node
which we created earlier. The entire process completes in O (1) time. Thus the
asymptotic time complexity to insert an element in the second position of the
linked list is O (1).
8. The concatenation of two lists can be performed in O(1) time. Which of the
following variation of the linked list can be used?
a) Singly linked list
b) Doubly linked list
c) Circular doubly linked list
d) Array implementation of list
View Answer
Answer: c
Explanation: We can easily concatenate two lists in O (1) time using singly or
doubly linked list, provided that we have a pointer to the last node at least one
of the lists. But in case of circular doubly linked lists, we will break the link in
both the lists and hook them together. Thus circular doubly linked list
concatenates two lists in O (1) time.
9. Consider the following definition in c programming language.

struct node
{
int data;
struct node * next;
}
typedef struct node NODE;
NODE *ptr;
Which of the following c code is used to create new node?
a) ptr = (NODE*)malloc(sizeof(NODE));
b) ptr = (NODE*)malloc(NODE);
c) ptr = (NODE*)malloc(sizeof(NODE*));
d) ptr = (NODE)malloc(sizeof(NODE));
View Answer
Answer: a
Explanation: As it represents the right way to create a node.
1. What kind of linked list is best to answer questions like “What is the item at
position n?”
a) Singly linked list
b) Doubly linked list
c) Circular linked list
d) Array implementation of linked list
View Answer
Answer: d
Explanation: Arrays provide random access to elements by providing the index
value within square brackets. In the linked list, we need to traverse through
each element until we reach the nth position. Time taken to access an element
represented in arrays is less than the singly, doubly and circular linked lists.
Thus, array implementation is used to access the item at the position n.
2. Linked lists are not suitable for the implementation of ___________
a) Insertion sort
b) Radix sort
c) Polynomial manipulation
d) Binary search
View Answer
Answer: d
Explanation: It cannot be implemented using linked lists.
3. Linked list is considered as an example of ___________ type of memory
allocation.
a) Dynamic
b) Static
c) Compile time
d) Heap
View Answer
Answer: a
Explanation: As memory is allocated at the run time.
advertisement
ADVERTISEMENT
ADVERTISEMENT
4. In Linked List implementation, a node carries information regarding
___________
a) Data
b) Link
c) Data and Link
d) Node
View Answer
Answer: c
Explanation: A linked list is a collection of objects linked together by references
from an object to another object. By convention these objects are names as
nodes. Linked list consists of nodes where each node contains one or more
data fields and a reference(link) to the next node.
5. Linked list data structure offers considerable saving in _____________
a) Computational Time
b) Space Utilization
c) Space Utilization and Computational Time
d) Speed Utilization
View Answer
Answer: c
Explanation: Linked lists saves both space and time.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
Participate Now!
6. Which of the following points is/are not true about Linked List data structure
when it is compared with an array?
a) Arrays have better cache locality that can make them better in terms of
performance
b) It is easy to insert and delete elements in Linked List
c) Random access is not allowed in a typical implementation of Linked Lists
d) Access of elements in linked list takes less time than compared to arrays
View Answer
Answer: d
Explanation: To access an element in a linked list, we need to traverse every
element until we reach the desired element. This will take more time than
arrays as arrays provide random access to its elements.
7. What does the following function do for a given Linked List with first node as
head?

void fun1(struct node* head)


{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
a) Prints all nodes of linked lists
b) Prints all nodes of linked list in reverse order
c) Prints alternate nodes of Linked List
d) Prints alternate nodes in reverse order
View Answer
Answer: b
Explanation: fun1() prints the given Linked List in reverse manner.
For Linked List 1->2->3->4->5, fun1() prints 5->4->3->2->1.
8. Which of the following sorting algorithms can be used to sort a random
linked list with minimum time complexity?
a) Insertion Sort
b) Quick Sort
c) Heap Sort
d) Merge Sort
View Answer
Answer: d
Explanation: Both Merge sort and Insertion sort can be used for linked lists.
The slow random-access performance of a linked list makes other algorithms
(such as quicksort) perform poorly, and others (such as heapsort) completely
impossible. Since worst case time complexity of Merge Sort is O(nLogn) and
Insertion sort is O(n2), merge sort is preferred.
1. The following function reverse() is supposed to reverse a singly linked list.
There is one line missing at the end of the function.

/* Link list node */


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

/* head_ref is a double pointer which points to head (or start) pointer


of linked list */
static void reverse(struct node** head_ref)
{
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
/*ADD A STATEMENT HERE*/
}
What should be added in place of “/*ADD A STATEMENT HERE*/”, so that the
function correctly reverses a linked list.
a) *head_ref = prev;
b) *head_ref = current;
c) *head_ref = next;
d) *head_ref = NULL;
View Answer
Answer: a
Explanation: *head_ref = prev; At the end of while loop, the prev pointer
points to the last node of original linked list.
We need to change *head_ref so that the head pointer now starts pointing to
the last node.
advertisement
ADVERTISEMENT
ADVERTISEMENT
2. What is the output of following function for start pointing to first node of
following linked list?

1->2->3->4->5->6
void fun(struct node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
a) 1 4 6 6 4 1
b) 1 3 5 1 3 5
c) 1 2 3 5
d) 1 3 5 5 3 1
View Answer
Answer: d
Explanation: fun() prints alternate nodes of the given Linked List, first from
head to end, and then from end to head.
If Linked List has even number of nodes, then skips the last node.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
Participate Now!
3. The following C function takes a simply-linked list as an input argument. It
modifies the list by moving the last element to the front of the list and returns
the modified list. Some part of the code is left blank. Choose the correct
alternative to replace the blank line.

typedef struct node


{
int value;
struct node *next;
}Node;

Node *move_to_front(Node *head)


{
Node *p, *q;
if ((head == NULL: || (head->next == NULL))
return head;
q = NULL; p = head;
while (p-> next !=NULL)
{
q = p;
p = p->next;
}
_______________________________
return head;
}
a) q = NULL; p->next = head; head = p;
b) q->next = NULL; head = p; p->next = head;
c) head = p; p->next = q; q->next = NULL;
d) q->next = NULL; p->next = head; head = p;
View Answer
Answer: d
Explanation: When while loop completes its execution, node ‘p’ refers to the
last node whereas the ‘q’ node refers to the node before ‘p’ in the linked list.
q->next=NULL makes q as the last node. p->next=head places p as the first
node. the head must be modified to ‘p’ as ‘p’ is the starting node of the list
(head=p). Thus the sequence of steps are q->next=NULL, p->next=head,
head=p.
4. The following C function takes a single-linked list of integers as a parameter
and rearranges the elements of the list. The function is called with the list
containing the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What will be the
contents of the list after the function completes execution?

struct node
{
int value;
struct node *next;
};
void rearrange(struct node *list)
{
struct node *p, * q;
int temp;
if ((!list) || !list->next)
return;
p = list;
q = list->next;
while(q)
{
temp = p->value;
p->value = q->value;
q->value = temp;
p = q->next;
q = p?p->next:0;
}
}
a) 1, 2, 3, 4, 5, 6, 7
b) 2, 1, 4, 3, 6, 5, 7
c) 1, 3, 2, 5, 4, 7, 6
d) 2, 3, 4, 5, 6, 7, 1
View Answer
Answer: b
Explanation: The function rearrange() exchanges data of every node with its
next node. It starts exchanging data from the first node itself.
5. In the worst case, the number of comparisons needed to search a singly
linked list of length n for a given element is?
a) log 2 n
b) n⁄2
c) log 2 n – 1
d) n
View Answer
Answer: d
Explanation: In the worst case, the element to be searched has to be compared
with all elements of the linked list.
6. Given pointer to a node X in a singly linked list. Only one pointer is given,
pointer to head node is not given, can we delete the node X from given linked
list?
a) Possible if X is not last node
b) Possible if size of linked list is even
c) Possible if size of linked list is odd
d) Possible if X is not first node
View Answer
Answer: a
Explanation: Following are simple steps.
struct node *temp = X->next;
X->data = temp->data;
X->next = temp->next;
free(temp);
7. You are given pointers to first and last nodes of a singly linked list, which of
the following operations are dependent on the length of the linked list?
a) Delete the first element
b) Insert a new element as a first element
c) Delete the last element of the list
d) Add a new element at the end of the list
View Answer
Answer: c
Explanation: Deletion of the first element of the list is done in O (1) time by
deleting memory and changing the first pointer.
Insertion of an element as a first element can be done in O (1) time. We will
create a node that holds data and points to the head of the given linked list.
The head pointer was changed to a newly created node.
Deletion of the last element requires a pointer to the previous node of last,
which can only be obtained by traversing the list. This requires the length of
the linked list.
Adding a new element at the end of the list can be done in O (1) by changing
the pointer of the last node to the newly created node and last is changed to a
newly created node.
8. In the worst case, the number of comparisons needed to search a singly
linked list of length n for a given element is?
a) log2 n
b) n⁄2
c) log2 n – 1
d) n
View Answer
Answer: d
Explanation: The worst-case happens if the required element is at last or the
element is absent in the list. For this, we need to compare every element in the
linked list. If n elements are there, n comparisons will happen in the worst
case.
1. Which of the following is not a disadvantage to the usage of array?
a) Fixed size
b) There are chances of wastage of memory space if elements inserted in an
array are lesser than the allocated size
c) Insertion based on position
d) Accessing elements at specified positions
View Answer
Answer: d
Explanation: Array elements can be accessed in two steps. First, multiply the
size of the data type with the specified position, second, add this value to the
base address. Both of these operations can be done in constant time, hence
accessing elements at a given index/position is faster.
2. What is the time complexity of inserting at the end in dynamic arrays?
a) O(1)
b) O(n)
c) O(logn)
d) Either O(1) or O(n)
View Answer
Answer: d
Explanation: Depending on whether the array is full or not, the complexity in
dynamic array varies. If you try to insert into an array that is not full, then the
element is simply stored at the end, this takes O(1) time. If you try to insert
into an array which is full, first you will have to allocate an array with double
the size of the current array and then copy all the elements into it and finally
insert the new element, this takes O(n) time.
3. What is the time complexity to count the number of elements in the linked
list?
a) O(1)
b) O(n)
c) O(logn)
d) O(n2)
View Answer
Answer: b
Explanation: To count the number of elements, you have to traverse through
the entire list, hence complexity is O(n).
advertisement
4. Which of the following performs deletion of the last element in the list?
Given below is the Node class.

class Node
{
protected Node next;
protected Object ele;
Node(Object e,Node n)
{
ele = e;
next = n;
}
public void setNext(Node n)
{
next = n;
}
public void setEle(Object e)
{
ele = e;
}
public Node getNext()
{
return next;
}
public Object getEle()
{
return ele;
}
}
class SLL
{
Node head;
int size;
SLL()
{
size = 0;
}
}
a)

Note: Join free Sanfoundry classes at Telegram or Youtube


public Node removeLast()
{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur.getNext() != null)
{
temp = cur;
cur = cur.getNext();
}
temp.setNext(null);
size--;
return cur;
}
b)

public void removeLast()


{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur != null)
{
temp = cur;
cur = cur.getNext();
}
temp.setNext(null);
return cur;
}
c)

public void removeLast()


{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur != null)
{
cur = cur.getNext();
temp = cur;
}
temp.setNext(null);
return cur;
}
d)

public void removeLast()


{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur.getNext() != null)
{
cur = cur.getNext();
temp = cur;
}
temp.setNext(null);
return cur;
}
View Answer
Answer: a
Explanation: Since you have to traverse to the end of the list and delete the
last node, you need two reference pointers. ‘cur’ to traverse all the way and
find the last node, and ‘temp’ is a trailing pointer to ‘cur’. Once you reach the
end of the list, setNext of ‘temp’ to null, ‘cur’ is not being pointed to by any
node, and hence it is available for garbage collection.

5. What is the functionality of the following code?

public void function(Node node)


{
if(size == 0)
head = node;
else
{
Node temp,cur;
for(cur = head; (temp = cur.getNext())!=null; cur = temp);
cur.setNext(node);
}
size++;
}
a) Inserting a node at the beginning of the list
b) Deleting a node at the beginning of the list
c) Inserting a node at the end of the list
d) Deleting a node at the end of the list
View Answer
Answer: c
Explanation: The for loop traverses through the list and then inserts a new
node as cur.setNext(node);
6. What is the space complexity for deleting a linked list?
a) O(1)
b) O(n)
c) Either O(1) or O(n)
d) O(logn)
View Answer
Answer: a
Explanation: You need a temp variable to keep track of current node, hence
the space complexity is O(1).
7. How would you delete a node in the singly linked list? The position to be
deleted is given.
a)

public void delete(int pos)


{
if(pos < 0)
pos = 0;
if(pos > size)
pos = size;
if( size == 0)
return;
if(pos == 0)
head = head.getNext();
else
{
Node temp = head;
for(int i=1; i<pos; i++)
{
temp = temp.getNext();
}
temp.setNext(temp.getNext().getNext());
}
size--;
}
b)

public void delete(int pos)


{
if(pos < 0)
pos = 0;
if(pos > size)
pos = size;
if( size == 0)
return;
if(pos == 0)
head = head.getNext();
else
{
Node temp = head;
for(int i=1; i<pos; i++)
{
temp = temp.getNext();
}
temp.setNext(temp.getNext());
}
size--;
}
c)

public void delete(int pos)


{
if(pos < 0)
pos = 0;
if(pos > size)
pos = size;
if( size == 0)
return;
if(pos == 0)
head = head.getNext();
else
{
Node temp = head;
for(int i=1; i<pos; i++)
{
temp = temp.getNext().getNext();
}
temp.setNext(temp.getNext().getNext());
}
size--;
}
d)
public void delete(int pos)
{
if(pos < 0)
pos = 0;
if(pos > size)
pos = size;
if( size == 0)
return;
if(pos == 0)
head = head.getNext();
else
{
Node temp = head;
for(int i=0; i<pos; i++)
{
temp = temp.getNext();
}
temp.setNext(temp.getNext().getNext());
}
size--;
}
View Answer
Answer: a
Explanation: Loop through the list to get into position one behind the actual
position given. temp.setNext(temp.getNext().getNext()) will delete the
specified node.

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


a) To implement file systems
b) For separate chaining in hash-tables
c) To implement non-binary trees
d) Random Access of elements
View Answer
Answer: d
Explanation: To implement file system, for separate chaining in hash-tables
and to implement non-binary trees linked lists are used. Elements are accessed
sequentially in linked list. Random access of elements is not an applications of
linked list.
9. Which of the following piece of code has the functionality of counting the
number of elements in the list?
a)

public int length(Node head)


{
int size = 0;
Node cur = head;
while(cur!=null)
{
size++;
cur = cur.getNext();
}
return size;
}
b)

public int length(Node head)


{
int size = 0;
Node cur = head;
while(cur!=null)
{
cur = cur.getNext();
size++;
}
return size;
}
c)

public int length(Node head)


{
int size = 0;
Node cur = head;
while(cur!=null)
{
size++;
cur = cur.getNext();
}
}
d)

public int length(Node head)


{
int size = 0;
Node cur = head;
while(cur!=null)
{
size++;
cur = cur.getNext().getNext();
}
return size;
}
View Answer
Answer: a
Explanation: ‘cur’ pointer traverses through list and increments the size
variable until the end of list is reached.

10. How do you insert an element at the beginning of the list?


a)

public void insertBegin(Node node)


{
node.setNext(head);
head = node;
size++;
}
b)

public void insertBegin(Node node)


{
head = node;
node.setNext(head);
size++;
}
c)
public void insertBegin(Node node)
{
Node temp = head.getNext()
node.setNext(temp);
head = node;
size++;
}
d)

public void insertBegin(Node node)


{
Node temp = head.getNext()
node.setNext(temp);
node = head;
size++;
}
View Answer
Answer: a
Explanation: Set the ‘next’ pointer point to the head of the list and then make
this new node as the head.

11. What is the functionality of the following piece of code?

public int function(int data)


{
Node temp = head;
int var = 0;
while(temp != null)
{
if(temp.getData() == data)
{
return var;
}
var = var+1;
temp = temp.getNext();
}
return Integer.MIN_VALUE;
}
a) Find and delete a given element in the list
b) Find and return the given element in the list
c) Find and return the position of the given element in the list
d) Find and insert a new element in the list
View Answer
Answer: c
Explanation: When temp is equal to data, the position of data is returned.
1. Which of the following is not a disadvantage to the usage of array?
a) Fixed size
b) There are chances of wastage of memory space if elements inserted in an
array are lesser than the allocated size
c) Insertion based on position
d) Accessing elements at specified positions
View Answer
Answer: d
Explanation: Array elements can be accessed in two steps. First, multiply the
size of the data type with the specified position, second, add this value to the
base address. Both of these operations can be done in constant time, hence
accessing elements at a given index/position is faster.
2. What is the time complexity of inserting at the end in dynamic arrays?
a) O(1)
b) O(n)
c) O(logn)
d) Either O(1) or O(n)
View Answer
Answer: d
Explanation: Depending on whether the array is full or not, the complexity in
dynamic array varies. If you try to insert into an array that is not full, then the
element is simply stored at the end, this takes O(1) time. If you try to insert
into an array which is full, first you will have to allocate an array with double
the size of the current array and then copy all the elements into it and finally
insert the new element, this takes O(n) time.
3. What is the time complexity to count the number of elements in the linked
list?
a) O(1)
b) O(n)
c) O(logn)
d) O(n2)
View Answer
Answer: b
Explanation: To count the number of elements, you have to traverse through
the entire list, hence complexity is O(n).
advertisement
4. Which of the following performs deletion of the last element in the list?
Given below is the Node class.

class Node
{
protected Node next;
protected Object ele;
Node(Object e,Node n)
{
ele = e;
next = n;
}
public void setNext(Node n)
{
next = n;
}
public void setEle(Object e)
{
ele = e;
}
public Node getNext()
{
return next;
}
public Object getEle()
{
return ele;
}
}
class SLL
{
Node head;
int size;
SLL()
{
size = 0;
}
}
a)

Note: Join free Sanfoundry classes at Telegram or Youtube


public Node removeLast()
{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur.getNext() != null)
{
temp = cur;
cur = cur.getNext();
}
temp.setNext(null);
size--;
return cur;
}
b)

public void removeLast()


{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur != null)
{
temp = cur;
cur = cur.getNext();
}
temp.setNext(null);
return cur;
}
c)

public void removeLast()


{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur != null)
{
cur = cur.getNext();
temp = cur;
}
temp.setNext(null);
return cur;
}
d)

public void removeLast()


{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur.getNext() != null)
{
cur = cur.getNext();
temp = cur;
}
temp.setNext(null);
return cur;
}
View Answer
Answer: a
Explanation: Since you have to traverse to the end of the list and delete the
last node, you need two reference pointers. ‘cur’ to traverse all the way and
find the last node, and ‘temp’ is a trailing pointer to ‘cur’. Once you reach the
end of the list, setNext of ‘temp’ to null, ‘cur’ is not being pointed to by any
node, and hence it is available for garbage collection.

5. What is the functionality of the following code?

public void function(Node node)


{
if(size == 0)
head = node;
else
{
Node temp,cur;
for(cur = head; (temp = cur.getNext())!=null; cur = temp);
cur.setNext(node);
}
size++;
}
a) Inserting a node at the beginning of the list
b) Deleting a node at the beginning of the list
c) Inserting a node at the end of the list
d) Deleting a node at the end of the list
View Answer
Answer: c
Explanation: The for loop traverses through the list and then inserts a new
node as cur.setNext(node);
6. What is the space complexity for deleting a linked list?
a) O(1)
b) O(n)
c) Either O(1) or O(n)
d) O(logn)
View Answer
Answer: a
Explanation: You need a temp variable to keep track of current node, hence
the space complexity is O(1).
7. How would you delete a node in the singly linked list? The position to be
deleted is given.
a)
public void delete(int pos)
{
if(pos < 0)
pos = 0;
if(pos > size)
pos = size;
if( size == 0)
return;
if(pos == 0)
head = head.getNext();
else
{
Node temp = head;
for(int i=1; i<pos; i++)
{
temp = temp.getNext();
}
temp.setNext(temp.getNext().getNext());
}
size--;
}
b)

public void delete(int pos)


{
if(pos < 0)
pos = 0;
if(pos > size)
pos = size;
if( size == 0)
return;
if(pos == 0)
head = head.getNext();
else
{
Node temp = head;
for(int i=1; i<pos; i++)
{
temp = temp.getNext();
}
temp.setNext(temp.getNext());
}
size--;
}
c)

public void delete(int pos)


{
if(pos < 0)
pos = 0;
if(pos > size)
pos = size;
if( size == 0)
return;
if(pos == 0)
head = head.getNext();
else
{
Node temp = head;
for(int i=1; i<pos; i++)
{
temp = temp.getNext().getNext();
}
temp.setNext(temp.getNext().getNext());
}
size--;
}
d)

public void delete(int pos)


{
if(pos < 0)
pos = 0;
if(pos > size)
pos = size;
if( size == 0)
return;
if(pos == 0)
head = head.getNext();
else
{
Node temp = head;
for(int i=0; i<pos; i++)
{
temp = temp.getNext();
}
temp.setNext(temp.getNext().getNext());
}
size--;
}
View Answer
Answer: a
Explanation: Loop through the list to get into position one behind the actual
position given. temp.setNext(temp.getNext().getNext()) will delete the
specified node.

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


a) To implement file systems
b) For separate chaining in hash-tables
c) To implement non-binary trees
d) Random Access of elements
View Answer
Answer: d
Explanation: To implement file system, for separate chaining in hash-tables
and to implement non-binary trees linked lists are used. Elements are accessed
sequentially in linked list. Random access of elements is not an applications of
linked list.
9. Which of the following piece of code has the functionality of counting the
number of elements in the list?
a)

public int length(Node head)


{
int size = 0;
Node cur = head;
while(cur!=null)
{
size++;
cur = cur.getNext();
}
return size;
}
b)

public int length(Node head)


{
int size = 0;
Node cur = head;
while(cur!=null)
{
cur = cur.getNext();
size++;
}
return size;
}
c)

public int length(Node head)


{
int size = 0;
Node cur = head;
while(cur!=null)
{
size++;
cur = cur.getNext();
}
}
d)

public int length(Node head)


{
int size = 0;
Node cur = head;
while(cur!=null)
{
size++;
cur = cur.getNext().getNext();
}
return size;
}
View Answer
Answer: a
Explanation: ‘cur’ pointer traverses through list and increments the size
variable until the end of list is reached.

10. How do you insert an element at the beginning of the list?


a)

public void insertBegin(Node node)


{
node.setNext(head);
head = node;
size++;
}
b)

public void insertBegin(Node node)


{
head = node;
node.setNext(head);
size++;
}
c)

public void insertBegin(Node node)


{
Node temp = head.getNext()
node.setNext(temp);
head = node;
size++;
}
d)
public void insertBegin(Node node)
{
Node temp = head.getNext()
node.setNext(temp);
node = head;
size++;
}
View Answer
Answer: a
Explanation: Set the ‘next’ pointer point to the head of the list and then make
this new node as the head.

11. What is the functionality of the following piece of code?

public int function(int data)


{
Node temp = head;
int var = 0;
while(temp != null)
{
if(temp.getData() == data)
{
return var;
}
var = var+1;
temp = temp.getNext();
}
return Integer.MIN_VALUE;
}
a) Find and delete a given element in the list
b) Find and return the given element in the list
c) Find and return the position of the given element in the list
d) Find and insert a new element in the list
View Answer
Answer: c
Explanation: When temp is equal to data, the position of data is returned.
1. Which of the following real world scenarios would you associate with a stack
data structure?
a) piling up of chairs one above the other
b) people standing in a line to be serviced at a counter
c) offer services based on the priority of the customer
d) tatkal Ticket Booking in IRCTC
View Answer
Answer: a
Explanation: Stack follows Last In First Out (LIFO) policy. Piling up of chairs one
above the other is based on LIFO, people standing in a line is a queue and if the
service is based on priority, then it can be associated with a priority queue.
Tatkal Ticket Booking Follows First in First Out Policy. People who click the
book now first will enter the booking page first.
2. What does the following function check for? (all necessary headers to be
included and function is called from main)

#define MAX 10

typedef struct stack


{
int top;
int item[MAX];
}stack;

int function(stack *s)


{
if(s->top == -1)
return 1;
else return 0;
}
a) full stack
b) invalid index
c) empty stack
d) infinite stack
View Answer
Answer: c
Explanation: An empty stack is represented with the top-of-the-stack(‘top’ in
this case) to be equal to -1.
advertisement
ADVERTISEMENT
ADVERTISEMENT
3. What does ‘stack underflow’ refer to?
a) accessing item from an undefined stack
b) adding items to a full stack
c) removing items from an empty stack
d) index out of bounds exception
View Answer
Answer: c
Explanation: Removing items from an empty stack is termed as stack
underflow.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
Participate Now!
4. What is the output of the following program?

public class Stack


{
protected static final int CAPACITY = 100;
protected int size,top = -1;
protected Object stk[];

public Stack()
{
stk = new Object[CAPACITY];
}

public void push(Object item)


{
if(size_of_stack==size)
{
System.out.println("Stack overflow");
return;
}
else
{
top++;
stk[top]=item;
}
}
public Object pop()
{
if(top<0)
{
return -999;
}
else
{
Object ele=stk[top];
top--;
size_of_stack--;
return ele;
}
}
}

public class StackDemo


{
public static void main(String args[])
{
Stack myStack = new Stack();
myStack.push(10);
Object element1 = myStack.pop();
Object element2 = myStack.pop();
System.out.println(element2);
}
}
a) stack is full
b) 20
c) 0
d) -999
View Answer
Answer: d
Explanation: The first call to pop() returns 10, whereas the second call to pop()
would result in stack underflow and the program returns -999.
5. What is the time complexity of pop() operation when the stack is
implemented using an array?
a) O(1)
b) O(n)
c) O(logn)
d) O(nlogn)
View Answer
Answer: a
Explanation: pop() accesses only one end of the structure, and hence constant
time.
6. Which of the following array position will be occupied by a new element
being pushed for a stack of size N elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[1]
d) S[0]
View Answer
Answer: b
Explanation: Elements are pushed at the end, hence N.
7. What happens when you pop from an empty stack while implementing using
the Stack ADT in Java?
a) Undefined error
b) Compiler displays a warning
c) EmptyStackException is thrown
d) NoStackException is thrown
View Answer
Answer: c
Explanation: The Stack ADT throws an EmptyStackException if the stack is
empty and a pop() operation is tried on it.
8. What is the functionality of the following piece of Java code?
Assume: ‘a’ is a non empty array of integers, the Stack class creates an array of
specified size and provides a top pointer indicating TOS(top of stack), push and
pop have normal meaning.

public void some_function(int[] a)


{
Stack S=new Stack(a.length);
int[] b=new int[a.length];
for(int i=0;i<a.length;i++)
{
S.push(a[i]);
}
for(int i=0;i<a.length;i++)
{
b[i]=(int)(S.pop());
}
System.out.println("output :");
for(int i=0;i<b.length;i++)
{
System.out.println(b[i]);
}
}
a) print alternate elements of array
b) duplicate the given array
c) parentheses matching
d) reverse the array
View Answer
Answer: d
Explanation: Every element from the given array ‘a’ is pushed into the stack,
and then the elements are popped out into the array ‘b’. Stack is a LIFO
structure, this results in reversing the given array.
9. Array implementation of Stack is not dynamic, which of the following
statements supports this argument?
a) space allocation for array is fixed and cannot be changed during run-time
b) user unable to give the input for stack operations
c) a runtime exception halts execution
d) improper program compilation
View Answer
Answer: a
Explanation: You cannot modify the size of an array once the memory has been
allocated, adding fewer elements than the array size would cause wastage of
space, and adding more elements than the array size at run time would cause
Stack Overflow.
10. Which of the following array element will return the top-of-the-stack-
element for a stack of size N elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[N-2]
d) S[N+1]
View Answer
Answer: a
Explanation: Array indexing start from 0, hence N-1 is the last index.
1. What is the best case time complexity of deleting a node in a Singly Linked
list?
a) O (n)
b) O (n2)
c) O (nlogn)
d) O (1)
View Answer
Answer: d
Explanation: Deletion of the head node in the linked list is taken as the best
case. The successor of the head node is changed to head and deletes the
predecessor of the newly assigned head node. This process completes in O(1)
time.
2. Which of the following statements are not correct with respect to Singly
Linked List(SLL) and Doubly Linked List(DLL)?
a) Complexity of Insertion and Deletion at known position is O(n) in SLL and
O(1) in DLL
b) SLL uses lesser memory per node than DLL
c) DLL has more searching power than SLL
d) Number of node fields in SLL is more than DLL
View Answer
Answer: d
Explanation: To insert and delete at known positions requires complete
traversal of the list in worst case in SLL, SLL consists of an item and a node
field, while DLL has an item and two node fields, hence SLL occupies lesser
memory, DLL can be traversed both ways(left and right), while SLL can traverse
in only one direction, hence more searching power of DLL. Node fields in SLL is
2 (data and address of next node) whereas in DLL is 3(data, address to next
node, address to previous node).
3. Given below is the Node class to perform basic list operations and a Stack
class with a no arg constructor.
Select from the options the appropriate pop() operation that can be included
in the Stack class. Also ‘first’ is the top-of-the-stack.

advertisement
class Node
{
protected Node next;
protected Object ele;
Node()
{
this(null,null);
}
Node(Object e,Node n)
{
ele=e;
next=n;
}
public void setNext(Node n)
{
next=n;
}
public void setEle(Object e)
{
ele=e;
}
public Node getNext()
{
return next;
}
public Object getEle()
{
return ele;
}
}

class Stack
{
Node first;
int size=0;
Stack()
{
first=null;
}
}
a)

Note: Join free Sanfoundry classes at Telegram or Youtube


public Object pop()
{
if(size == 0)
System.out.println("underflow");
else
{
Object o = first.getEle();
first = first.getNext();
size--;
return o;
}
}
b)

public Object pop()


{
if(size == 0)
System.out.println("underflow");
else
{
Object o = first.getEle();
first = first.getNext().getNext();
size--;
return o;
}
}
c)

public Object pop()


{
if(size == 0)
System.out.println("underflow");
else
{
first = first.getNext();
Object o = first.getEle();
size--;
return o;
}
}
d)

public Object pop()


{
if(size == 0)
System.out.println("underflow");
else
{
first = first.getNext().getNext();
Object o = first.getEle();
size--;
return o;
}
}
View Answer
Answer: a
Explanation: pop() should return the Object pointed to by the node ‘first’. The
sequence of operations is, first, get the element stored at node ‘first’ using
getEle(), and second, make the node point to the next node using getNext().

4. What does the following function do?

public Object some_func()throws emptyStackException


{
if(isEmpty())
throw new emptyStackException("underflow");
return first.getEle();
}
a) pop
b) delete the top-of-the-stack element
c) retrieve the top-of-the-stack element
d) push operation
View Answer
Answer: c
Explanation: This code is only retrieving the top element, note that it is not
equivalent to pop operation as you are not setting the ‘next’ pointer point to
the next node in sequence.
5. What is the functionality of the following piece of code?

public void display()


{
if(size == 0)
System.out.println("underflow");
else
{
Node current = first;
while(current != null)
{
System.out.println(current.getEle());
current = current.getNext();
}
}
}
a) reverse the list
b) display the list
c) display the list excluding top-of-the-stack-element
d) reverse the list excluding top-of-the-stack-element
View Answer
Answer: b
Explanation: An alias of the node ‘first’ is created which traverses through the
list and displays the elements.
6. What does ‘stack overflow’ refer to?
a) accessing item from an undefined stack
b) adding items to a full stack
c) removing items from an empty stack
d) index out of bounds exception
View Answer
Answer: b
Explanation: Adding items to a full stack is termed as stack underflow.
7. Given below is the Node class to perform basic list operations and a Stack
class with a no arg constructor. Select from the options the appropriate push()
operation that can be included in the Stack class. Also ‘first’ is the top-of-the-
stack.

class Node
{
protected Node next;
protected Object ele;
Node()
{
this(null,null);
}
Node(Object e,Node n)
{
ele=e;
next=n;
}
public void setNext(Node n)
{
next=n;
}
public void setEle(Object e)
{
ele=e;
}
public Node getNext()
{
return next;
}
public Object getEle()
{
return ele;
}
}

class Stack
{
Node first;
int size=0;
Stack()
{
first=null;
}
}
a)
public void push(Object item)
{
Node temp = new Node(item,first);
first = temp;
size++;
}
b)

public void push(Object item)


{
Node temp = new Node(item,first);
first = temp.getNext();
size++;
}
c)

public void push(Object item)


{
Node temp = new Node();
first = temp.getNext();
first.setItem(item);
size++;
}
d)

public void push(Object item)


{
Node temp = new Node();
first = temp.getNext.getNext();
first.setItem(item);
size++;
}
View Answer
Answer: a
Explanation: To push an element into the stack, first create a new node with
the next pointer point to the current top-of-the-stack node, then make this
node as top-of-the-stack by assigning it to ‘first’.
8. Consider these functions:
push() : push an element into the stack
pop() : pop the top-of-the-stack element
top() : returns the item stored in top-of-the-stack-node
What will be the output after performing these sequence of operations

push(20);
push(4);
top();
pop();
pop();
push(5);
top();
a) 20
b) 4
c) stack underflow
d) 5
View Answer
Answer: d
Explanation: 20 and 4 which were pushed are popped by the two pop()
statements, the recent push() is 5, hence top() returns 5.
9. Which of the following data structures can be used for parentheses
matching?
a) n-ary tree
b) queue
c) priority queue
d) stack
View Answer
Answer: d
Explanation: For every opening brace, push it into the stack, and for every
closing brace, pop it off the stack. Do not take action for any other character.
In the end, if the stack is empty, then the input has balanced parentheses.
10. Minimum number of queues to implement stack is ___________
a) 3
b) 4
c) 1
d) 2
View Answer
Answer: c
Explanation: Use one queue and one counter to count the number of elements
in the queue.
1. Which of the following properties is associated with a queue?
a) First In Last Out
b) First In First Out
c) Last In First Out
d) Last In Last Out
View Answer
Answer: b
Explanation: Queue follows First In First Out structure.
2. In a circular queue, how do you increment the rear end of the queue?
a) rear++
b) (rear+1) % CAPACITY
c) (rear % CAPACITY)+1
d) rear–
View Answer
Answer: b
Explanation: Ensures rear takes the values from 0 to (CAPACITY-1).
3. What is the term for inserting into a full queue known as?
a) overflow
b) underflow
c) null pointer exception
d) program won’t be compiled
View Answer
Answer: a
Explanation: Just as stack, inserting into a full queue is termed overflow.
advertisement
4. What is the time complexity of enqueue operation?
a) O(logn)
b) O(nlogn)
c) O(n)
d) O(1)
View Answer
Answer: d
Explanation: Enqueue operation is at the rear end, it takes O(1) time to insert a
new item into the queue.
5. What does the following Java code do?

Subscribe Now: Data Structure Newsletter | Important Subjects Newsletters


public Object function()
{
if(isEmpty())
return -999;
else
{
Object high;
high = q[front];
return high;
}
}
a) Dequeue
b) Enqueue
c) Return the front element
d) Return the last element
View Answer
Answer: c
Explanation: q[front] gives the element at the front of the queue, since we are
not moving the ‘front’ to the next element,
it is not a dequeue operation.
6. What is the need for a circular queue?
a) effective usage of memory
b) easier computations
c) to delete elements based on priority
d) implement LIFO principle in queues
View Answer
Answer: a
Explanation: In a linear queue, dequeue operation causes the starting elements
of the array to be empty, and there is no way you can use that space, while in a
circular queue, you can effectively use that space. Priority queue is used to
delete the elements based on their priority. Higher priority elements will be
deleted first whereas lower priority elements will be deleted next. Queue data
structure always follows FIFO principle.
7. Which of the following represents a dequeue operation? (count is the
number of elements in the queue)
a)

public Object dequeue()


{
if(count == 0)
{
System.out.println("Queue underflow");
return 0;
}
else
{
Object ele = q[front];
q[front] = null;
front = (front+1)%CAPACITY;
count--;
return ele;
}
}
b)

public Object dequeue()


{
if(count == 0)
{
System.out.println("Queue underflow");
return 0;
}
else
{
Object ele = q[front];
front = (front+1)%CAPACITY;
q[front] = null;
count--;
return ele;
}
}
c)

public Object dequeue()


{
if(count == 0)
{
System.out.println("Queue underflow");
return 0;
}
else
{
front = (front+1)%CAPACITY;
Object ele = q[front];
q[front] = null;
count--;
return ele;
}
}
d)

public Object dequeue()


{
if(count == 0)
{
System.out.println("Queue underflow");
return 0;
}
else
{
Object ele = q[front];
q[front] = null;
front = (front+1)%CAPACITY;
return ele;
count--;
}
}
View Answer
Answer: a
Explanation: Dequeue removes the first element from the queue, ‘front’ points
to the front end of the queue and returns the first element.

8. Which of the following best describes the growth of a linear queue at


runtime? (Q is the original queue, size() returns the number of elements in the
queue)
a)

private void expand()


{
int length = size();
int[] newQ = new int[length<<1];
for(int i=front; i<=rear; i++)
{
newQ[i-front] = Q[i%CAPACITY];
}
Q = newQ;
front = 0;
rear = size()-1;
}
b)

private void expand()


{
int length = size();
int[] newQ = new int[length<<1];
for(int i=front; i<=rear; i++)
{
newQ[i-front] = Q[i%CAPACITY];
}
Q = newQ;
}
c)

private void expand()


{
int length = size();
int[] newQ = new int[length<<1];
for(int i=front; i<=rear; i++)
{
newQ[i-front] = Q[i];
}
Q = newQ;
front = 0;
rear = size()-1;
}
d)

private void expand()


{
int length = size();
int[] newQ = new int[length*2];
for(int i=front; i<=rear; i++)
{
newQ[i-front] = Q[i%CAPACITY];
}
Q = newQ;
}
View Answer
Answer: a
Explanation: A common technique to expand the size of array at run time is
simply to double the size. Create a new array of double the previous size and
copy all the elements, after copying do not forget to assign front = 0 and rear =
size()-1, as these are necessary to maintain the decorum of the queue
operations.

9. What is the space complexity of a linear queue having n elements?


a) O(n)
b) O(nlogn)
c) O(logn)
d) O(1)
View Answer
Answer: a
Explanation: The space complexity of an algorithm is the total space taken by
the algorithm with respect to the input size. Space complexity includes both
Auxiliary space and space used by input. Because there are n elements the
space complexity of a linear queue having n elements is O(n).
10. What is the output of the following Java code?

public class CircularQueue


{
protected static final int CAPACITY = 100;
protected int size,front,rear;
protected Object q[];
int count = 0;

public CircularQueue()
{
this(CAPACITY);
}
public CircularQueue (int n)
{
size = n;
front = 0;
rear = 0;
q = new Object[size];
}

public void enqueue(Object item)


{
if(count == size)
{
System.out.println("Queue overflow");
return;
}
else
{
q[rear] = item;
rear = (rear+1)%size;
count++;
}
}
public Object dequeue()
{
if(count == 0)
{
System.out.println("Queue underflow");
return 0;
}
else
{
Object ele = q[front];
q[front] = null;
front = (front+1)%size;
count--;
return ele;
}
}
public Object frontElement()
{
if(count == 0)
return -999;
else
{
Object high;
high = q[front];
return high;
}
}
public Object rearElement()
{
if(count == 0)
return -999;
else
{
Object low;
rear = (rear-1)%size;
low = q[rear];
rear = (rear+1)%size;
return low;
}
}
}
public class CircularQueueDemo
{
public static void main(String args[])
{
Object var;
CircularQueue myQ = new CircularQueue();
myQ.enqueue(10);
myQ.enqueue(3);
var = myQ.rearElement();
myQ.dequeue();
myQ.enqueue(6);
var = mQ.frontElement();
System.out.println(var+" "+var);
}
}
a) 3 3
b) 3 6
c) 6 6
d) 10 6
View Answer
Answer: a
Explanation: First enqueue 10 and 3 into the queue, followed by a
dequeue(removes 10), followed by an enqueue(6), At this point, 3 is at the
front end of the queue and 6 at the rear end, hence a call to frontElement()
will return 3 which is displayed twice.
1. In linked list implementation of queue, if only front pointer is maintained,
which of the following operation take worst case linear time?
a) Insertion
b) Deletion
c) To empty a queue
d) Both Insertion and To empty a queue
View Answer
Answer: d
Explanation: Since front pointer is used for deletion, so worst time for the
other two cases.
2. In linked list implementation of a queue, where does a new element be
inserted?
a) At the head of link list
b) At the centre position in the link list
c) At the tail of the link list
d) At any position in the linked list
View Answer
Answer: c
Explanation: Since queue follows FIFO so new element inserted at last.
3. In linked list implementation of a queue, front and rear pointers are tracked.
Which of these pointers will change during an insertion into a NONEMPTY
queue?
a) Only front pointer
b) Only rear pointer
c) Both front and rear pointer
d) No pointer will be changed
View Answer
Answer: b
Explanation: Since queue follows FIFO so new element inserted at last.
advertisement
ADVERTISEMENT
ADVERTISEMENT
4. In linked list implementation of a queue, front and rear pointers are tracked.
Which of these pointers will change during an insertion into EMPTY queue?
a) Only front pointer
b) Only rear pointer
c) Both front and rear pointer
d) No pointer will be changed
View Answer
Answer: c
Explanation: Since its the starting of queue, so both values are changed.
5. In case of insertion into a linked queue, a node borrowed from the
__________ list is inserted in the queue.
a) AVAIL
b) FRONT
c) REAR
d) NULL
View Answer
Answer: a
Explanation: All the nodes are collected in AVAIL list.
Subscribe Now: Data Structure Newsletter | Important Subjects Newsletters
6. In linked list implementation of a queue, from where is the item deleted?
a) At the head of link list
b) At the centre position in the link list
c) At the tail of the link list
d) Node before the tail
View Answer
Answer: a
Explanation: Since queue follows FIFO so new element deleted from first.
7. In linked list implementation of a queue, the important condition for a
queue to be empty is?
a) FRONT is null
b) REAR is null
c) LINK is empty
d) FRONT==REAR-1
View Answer
Answer: a
Explanation: Because front represents the deleted nodes.
8. The essential condition which is checked before insertion in a linked queue
is?
a) Underflow
b) Overflow
c) Front value
d) Rear value
View Answer
Answer: b
Explanation: To check whether there is space in the queue or not.
9. The essential condition which is checked before deletion in a linked queue
is?
a) Underflow
b) Overflow
c) Front value
d) Rear value
View Answer
Answer: a
Explanation: To check whether there is element in the list or not.
10. Which of the following is true about linked list implementation of queue?
a) In push operation, if new nodes are inserted at the beginning of linked list,
then in pop operation, nodes must be removed from end
b) In push operation, if new nodes are inserted at the beginning, then in pop
operation, nodes must be removed from the beginning
c) In push operation, if new nodes are inserted at the end, then in pop
operation, nodes must be removed from end
d) In push operation, if new nodes are inserted at the end, then in pop
operation, nodes must be removed from beginning
View Answer
Answer: a
Explanation: It can be done by both the methods.
. With what data structure can a priority queue be implemented?
a) Array
b) List
c) Heap
d) Tree
View Answer
Answer: c
Explanation: Priority queue can be implemented using an array, a list, a binary
search tree or a heap, although the most efficient one being the heap.
2. Which of the following is not an application of priority queue?
a) Huffman codes
b) Interrupt handling in operating system
c) Undo operation in text editors
d) Bayesian spam filter
View Answer
Answer: c
Explanation: Undo operation is achieved using a stack.
3. Select the appropriate code that inserts elements into the list based on the
given key value.
(head and trail are dummy nodes to mark the end and beginning of the list,
they do not contain any priority or element)
a)

advertisement
ADVERTISEMENT
ADVERTISEMENT
public void insert_key(int key,Object item)
{
if(key<0)
{
Systerm.our.println("invalid");
System.exit(0);
}
else
{
Node temp = new Node(key,item,null);
if(count == 0)
{
head.setNext(temp);
temp.setNext(trail);
}
else
{
Node dup = head.getNext();
Node cur = head;
while((key>dup.getKey()) && (dup!=trail))
{
dup = dup.getNext();
cur = cur.getNext();
}
cur.setNext(temp);
temp.setNext(dup);
}
count++;
}
}
b)

Note: Join free Sanfoundry classes at Telegram or Youtube


public void insert_key(int key,Object item)
{
if(key<0)
{
Systerm.our.println("invalid");
System.exit(0);
}
else
{
Node temp = new Node(key,item,null);
if(count == 0)
{
head.setNext(temp);
temp.setNext(trail);
}
else
{
Node dup = head.getNext();
Node cur = dup;
while((key>dup.getKey()) && (dup!=trail))
{
dup = dup.getNext();
cur = cur.getNext();
}
cur.setNext(temp);
temp.setNext(dup);
}
count++;
}
}
c)

public void insert_key(int key,Object item)


{
if(key<0)
{
Systerm.our.println("invalid");
System.exit(0);
}
else
{
Node temp = new Node(key,item,null);
if(count == 0)
{
head.setNext(temp);
temp.setNext(trail);
}
else
{
Node dup = head.getNext();
Node cur = head;
while((key>dup.getKey()) && (dup!=trail))
{
dup = dup.getNext();
cur = cur.getNext();
}
cur.setNext(dup);
temp.setNext(cur);
}
count++;
}
}
d)

public void insert_key(int key,Object item)


{
if(key<0)
{
Systerm.our.println("invalid");
System.exit(0);
}
else
{
Node temp = new Node(key,item,null);
if(count == 0)
{
head.setNext(temp);
temp.setNext(trail);
}
else
{
Node dup = head.getNext();
Node cur = head;
while((key>dup.getKey()) && (dup!=trail))
{
dup = cur
cur = cur.getNext();
}
cur.setNext(dup);
temp.setNext(cur);
}
count++;
}
}
View Answer

4. What is the time complexity to insert a node based on key in a priority


queue?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: c
Explanation: In the worst case, you might have to traverse the entire list.
5. What is the functionality of the following piece of code?

public Object delete_key()


{
if(count == 0)
{
System.out.println("Q is empty");
System.exit(0);
}
else
{
Node cur = head.getNext();
Node dup = cur.getNext();
Object e = cur.getEle();
head.setNext(dup);
count--;
return e;
}
}
a) Delete the second element in the list
b) Return but not delete the second element in the list
c) Delete the first element in the list
d) Return but not delete the first element in the list
View Answer
Answer: c
Explanation: A pointer is made to point at the first element in the list and one
more to point to the second element, pointer manipulations are done such
that the first element is no longer being pointed by any other pointer, its value
is returned.
6. What is not a disadvantage of priority scheduling in operating systems?
a) A low priority process might have to wait indefinitely for the CPU
b) If the system crashes, the low priority systems may be lost permanently
c) Interrupt handling
d) Indefinite blocking
View Answer
Answer: c
Explanation: The lower priority process should wait until the CPU completes
the processing higher priority process. Interrupt handling is an advantage as
interrupts should be given more priority than tasks at hand so that interrupt
can be serviced to produce desired results.
7. Which of the following is not an advantage of a priority queue?
a) Easy to implement
b) Processes with different priority can be efficiently handled
c) Applications with differing requirements
d) Easy to delete elements in any case
View Answer
Answer: d
Explanation: In worst case, the entire queue has to be searched for the
element having the highest priority. This will take more time than usual. So
deletion of elements is not an advantage.
8. What is the time complexity to insert a node based on position in a priority
queue?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: c
Explanation: In the worst case, you might have to traverse the entire list.
1. What is a dequeue?
a) A queue with insert/delete defined for both front and rear ends of the
queue
b) A queue implemented with a doubly linked list
c) A queue implemented with both singly and doubly linked lists
d) A queue with insert/delete defined for front side of the queue
View Answer
Answer: a
Explanation: A dequeue or a double ended queue is a queue with insert/delete
defined for both front and rear ends of the queue.
2. Select the function which performs insertion at the front end of the
dequeue?
a)

public void function(Object item)


{
Node temp = new Node(item,null);
if(isEmpty())
{
temp.setNext(trail);
head.setNext(temp);
}
else
{
Node cur = head.getNext();
temp.setNext(cur);
head.setNext(temp);
}
size++;
}
b)

advertisement
public void function(Object item)
{
Node temp = new Node(item,null);
if(isEmpty())
{
temp.setNext(trail);
head.setNext(trail);
}
else
{
Node cur = head.getNext();
temp.setNext(cur);
head.setNext(temp);
}
size++;
}
c)

Note: Join free Sanfoundry classes at Telegram or Youtube


public void function(Object item)
{
Node temp = new Node(item,null);
if(isEmpty())
{
Node cur = head.getNext();
temp.setNext(cur);
head.setNext(temp);
}
else
{
temp.setNext(trail);
head.setNext(temp);
}
size++;
}
d)

public void function(Object item)


{
Node temp = new Node(item,null);
if(isEmpty())
{
Node cur = head.getNext();
temp.setNext(cur);
cur.setNext(temp);
}
else
{
head.setNext(trail);
trail.setNext(temp);
}
size++;
}
View Answer
Answer: a
Explanation: Create a new node, if the current list is empty, the ‘head’ points
to this node and this new node points to ‘trail’. Otherwise, ‘head’ points to the
new node and this in turn points to the current first element(head.getNext()).

3. What is the functionality of the following piece of code?


public void function(Object item)
{
Node temp=new Node(item,trail);
if(isEmpty())
{
head.setNext(temp);
temp.setNext(trail);
}
else
{
Node cur=head.getNext();
while(cur.getNext()!=trail)
{
cur=cur.getNext();
}
cur.setNext(temp);
}
size++;
}
a) Insert at the front end of the dequeue
b) Insert at the rear end of the dequeue
c) Fetch the element at the rear end of the dequeue
d) Fetch the element at the front end of the dequeue
View Answer
Answer: b
Explanation: If the list is empty, this new node will point to ‘trail’ and will be
pointed at by ‘head’. Otherwise, traverse till the end of the list and insert the
new node there.
4. What are the applications of dequeue?
a) A-Steal job scheduling algorithm
b) Can be used as both stack and queue
c) To find the maximum of all sub arrays of size k
d) All of the mentioned
View Answer
Answer: d
Explanation: All of the mentioned can be implemented with a dequeue.
5. Which of the following can be used to delete an element from the front end
of the queue?
a)

public Object deleteFront() throws emptyDEQException


{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = temp;
Object e = temp.getEle();
head.setNext(cur);
size--;
return e;
}
}
b)

public Object deleteFront() throws emptyDEQException


{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = temp.getNext();
Object e = temp.getEle();
head.setNext(cur);
size--;
return e;
}
}
c)

public Object deleteFront() throws emptyDEQException


{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = temp.getNext();
Object e = temp.getEle();
head.setNext(temp);
size--;
return e;
}
}
d)

public Object deleteFront() throws emptyDEQException


{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = temp.getNext();
Object e = temp.getEle();
temp.setNext(cur);
size--;
return e;
}
}
View Answer
Answer: b
Explanation: Have two pointers, one(temp) pointing to the first element and
the other(cur) pointing to the second element. Make the ‘head’ point to the
second element, this removes all reference for ‘temp’.

6. Which of the following can be used to delete an element from the rear end
of the queue?
a)
public Object deleteRear() throws emptyDEQException
{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = temp;
while(temp.getNext() != trail)
{
temp = temp.getNext();
cur = cur.getNext();
}
Object e = temp.getEle();
cur.setNext(trail);
size--;
return e;
}
}
b)

public Object deleteRear() throws emptyDEQException


{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = head;
while(temp != trail)
{
temp = temp.getNext();
cur = cur.getNext();
}
Object e = temp.getEle();
cur.setNext(trail);
size--;
return e;
}
}
c)

public Object deleteRear() throws emptyDEQException


{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = head;
while(temp.getNext()!=trail)
{
temp = temp.getNext();
cur = cur.getNext();
}
Object e = temp.getEle();
cur.setNext(trail);
size--;
return e;
}
}
d)

public Object deleteRear() throws emptyDEQException


{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = head;
while(temp.getNext()!=trail)
{
temp = temp.getNext();
cur = cur.getNext();
}
Object e = temp.getEle();
temp.setNext(trail);
size--;
return e;
}
}
View Answer

7. What is the time complexity of deleting from the rear end of the dequeue
implemented with a singly linked list?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: c
Explanation: Since a singly linked list is used, first you have to traverse till the
end, so the complexity is O(n).
8. After performing these set of operations, what does the final list look
contain?

InsertFront(10);
InsertFront(20);
InsertRear(30);
DeleteFront();
InsertRear(40);
InsertRear(10);
DeleteRear();
InsertRear(15);
display();
a) 10 30 10 15
b) 20 30 40 15
c) 20 30 40 10
d) 10 30 40 15
View Answer
Answer: d
Explanation: A careful tracing of the given operation yields the result.
10
20 10
20 10 30
10 30
10 30 40
10 30 40 10
10 30 40
10 30 40 15
1. The number of edges from the root to the node is called __________ of the
tree.
a) Height
b) Depth
c) Length
d) Width
View Answer
Answer: b
Explanation: The number of edges from the root to the node is called depth of
the tree.
2. The number of edges from the node to the deepest leaf is called _________
of the tree.
a) Height
b) Depth
c) Length
d) Width
View Answer
Answer: a
Explanation: The number of edges from the node to the deepest leaf is called
height of the tree.
3. What is a full binary tree?
a) Each node has exactly zero or two children
b) Each node has exactly two children
c) All the leaves are at the same level
d) Each node has exactly one or two children
View Answer
Answer: a
Explanation: A full binary tree is a tree in which each node has exactly 0 or 2
children.
advertisement
ADVERTISEMENT
ADVERTISEMENT
4. What is a complete binary tree?
a) Each node has exactly zero or two children
b) A binary tree, which is completely filled, with the possible exception of the
bottom level, which is filled from right to left
c) A binary tree, which is completely filled, with the possible exception of the
bottom level, which is filled from left to right
d) A tree In which all nodes have degree 2
View Answer
Answer: c
Explanation: A binary tree, which is completely filled, with the possible
exception of the bottom level, which is filled from left to right is called
complete binary tree. A Tree in which each node has exactly zero or two
children is called full binary tree. A Tree in which the degree of each node is 2
except leaf nodes is called perfect binary tree.
5. What is the average case time complexity for finding the height of the binary
tree?
a) h = O(loglogn)
b) h = O(nlogn)
c) h = O(n)
d) h = O(log n)
View Answer
Answer: d
Explanation: The nodes are either a part of left sub tree or the right sub tree,
so we don’t have to traverse all the nodes, this means the complexity is lesser
than n, in the average case, assuming the nodes are spread evenly, the time
complexity becomes O(logn).
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
Participate Now!
6. Which of the following is not an advantage of trees?
a) Hierarchical structure
b) Faster search
c) Router algorithms
d) Undo/Redo operations in a notepad
View Answer
Answer: d
Explanation: Undo/Redo operations in a notepad is an application of stack.
Hierarchical structure, Faster search, Router algorithms are advantages of
trees.
7. In a full binary tree if number of internal nodes is I, then number of leaves L
are?
a) L = 2*I
b) L = I + 1
c) L = I – 1
d) L = 2*I – 1
View Answer
Answer: b
Explanation: Number of Leaf nodes in full binary tree is equal to 1 + Number of
Internal Nodes i.e L = I + 1
8. In a full binary tree if number of internal nodes is I, then number of nodes N
are?
a) N = 2*I
b) N = I + 1
c) N = I – 1
d) N = 2*I + 1
View Answer
Answer: d
Explanation: Relation between number of internal nodes(I) and nodes(N) is N =
2*I+1.
9. In a full binary tree if there are L leaves, then total number of nodes N are?
a) N = 2*L
b) N = L + 1
c) N = L – 1
d) N = 2*L – 1
View Answer
Answer: d
Explanation: The relation between number of nodes(N) and leaves(L) is N=2*L-
1.
10. Which of the following is incorrect with respect to binary trees?
a) Let T be a binary tree. For every k ≥ 0, there are no more than 2k nodes in
level k
b) Let T be a binary tree with λ levels. Then T has no more than 2λ – 1 nodes
c) Let T be a binary tree with N nodes. Then the number of levels is at least
ceil(log (N + 1))
d) Let T be a binary tree with N nodes. Then the number of levels is at least
floor(log (N + 1))
View Answer
Answer: d
Explanation: In a binary tree, there are atmost 2k nodes in level k and 2k-1 total
number of nodes. Number of levels is at least ceil(log(N+1)).
11. Construct a binary tree by using postorder and inorder sequences given
below.
Inorder: N, M, P, O, Q
Postorder: N, P, Q, O, M

a)

b)
c)

d)
View Answer
Answer: d
Explanation: Here,
Postorder Traversal: N, P, Q, O, M
Inorder Traversal: N, M, P, O, Q
Root node of tree is the last visiting node in Postorder traversal. Thus, Root
Node = ‘M’.
The partial tree constructed is:

The second last node in postorder traversal is O. Thus, node P becomes left
child of node O and node Q becomes right child of node Q. Thus, the final tree
is:

12. Construct a binary search tree by using postorder sequence given below.
Postorder: 2, 4, 3, 7, 9, 8, 5.

a)

b)
c)

d)
View Answer
Answer: b
Explanation: Postorder sequence is 2, 4, 3, 7, 9, 8, 5.
Inorder sequence is the ascending order of nodes in Binary search tree. Thus,
Inorder sequence is 2, 3, 4, 5, 7, 8, 9. The tree constructed using Postorder and
Inorder sequence is
13. Construct a binary tree using inorder and level order traversal given below.
Inorder Traversal: 3, 4, 2, 1, 5, 8, 9
Level Order Traversal: 1, 4, 5, 9, 8, 2, 3

a)
b)

c)

d)
View Answer
Answer: a
Explanation: Inorder Traversal: 3, 4, 2, 1, 5, 8, 9
Level Order Traversal: 1, 4, 5, 9, 8, 2, 3
In level order traversal first node is the root node of the binary tree.
Thus the partially formed tree is:

In level order traversal, the second node is 4. Then, node 3 becomes left child
of node 4 and node 2 becomes right child of node 4. Third node of level order
traversal is 8. Then, node 5 becomes left child of node 8 and node 9 becomes
right child of node 8. Thus, the final tree is:

1. Which of the following is false about a binary search tree?


a) The left child is always lesser than its parent
b) The right child is always greater than its parent
c) The left and right sub-trees should also be binary search trees
d) In order sequence gives decreasing order of elements
View Answer
Answer: d
Explanation: In order sequence of binary search trees will always give
ascending order of elements. Remaining all are true regarding binary search
trees.
2. How to search for a key in a binary search tree?
a)

public Tree search(Tree root, int key)


{
if( root == null || root.key == key )
{
return root;
}
if( root.key < key )
{
return search(root.right,key);
}
else
return search(root.left,key);
}
b)
advertisement
public Tree search(Tree root, int key)
{
if( root == null || root.key == key )
{
return root;
}
if( root.key < key )
{
return search(root.left,key);
}
else
return search(root.right,key);
}
c)

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.


Participate Now!
public Tree search(Tree root, int key)
{
if( root == null)
{
return root;
}
if( root.key < key )
{
return search(root.right,key);
}
else
return search(root.left,key);
}
d)

public Tree search(Tree root, int key)


{
if( root == null)
{
return root;
}
if( root.key < key )
{
return search(root.right.right,key);
}
else
return search(root.left.left,key);
}
View Answer
Answer: a
Explanation: As we know that the left child is lesser than the parent, if the
root’s key is greater than the given key, we look only into the left sub-tree,
similarly for right sub-tree.

3. What is the speciality about the inorder traversal of a binary search tree?
a) It traverses in a non increasing order
b) It traverses in an increasing order
c) It traverses in a random fashion
d) It traverses based on priority of the node
View Answer
Answer: b
Explanation: As a binary search tree consists of elements lesser than the node
to the left and the ones greater than the node to the right, an inorder traversal
will give the elements in an increasing order.
4. What does the following piece of code do?

public void func(Tree root)


{
func(root.left());
func(root.right());
System.out.println(root.data());
}
a) Preorder traversal
b) Inorder traversal
c) Postorder traversal
d) Level order traversal
View Answer
5. What does the following piece of code do?
public void func(Tree root)
{
System.out.println(root.data());
func(root.left());
func(root.right());
}
a) Preorder traversal
b) Inorder traversal
c) Postorder traversal
d) Level order traversal
View Answer
Answer: a
Explanation: In a preorder traversal, first the parent is visited, then the left
child and finally the right child.
6. How will you find the minimum element in a binary search tree?
a)

public void min(Tree root)


{
while(root.left() != null)
{
root = root.left();
}
System.out.println(root.data());
}
b)

public void min(Tree root)


{
while(root != null)
{
root = root.left();
}
System.out.println(root.data());
}
c)

public void min(Tree root)


{
while(root.right() != null)
{
root = root.right();
}
System.out.println(root.data());
}
d)

public void min(Tree root)


{
while(root != null)
{
root = root.right();
}
System.out.println(root.data());
}
View Answer
Answer: a
Explanation: Since all the elements lesser than a given node will be towards
the left, iterating to the leftmost leaf of the root will give the minimum
element in a binary search tree.

7. How will you find the maximum element in a binary search tree?
a)

public void max(Tree root)


{
while(root.left() != null)
{
root = root.left();
}
System.out.println(root.data());
}
b)

public void max(Tree root)


{
while(root != null)
{
root = root.left();
}
System.out.println(root.data());
}
c)

public void max(Tree root)


{
while(root.right() != null)
{
root = root.right();
}
System.out.println(root.data());
}
d)

public void max(Tree root)


{
while(root != null)
{
root = root.right();
}
System.out.println(root.data());
}
View Answer

8. What are the worst case and average case complexities of a binary search
tree?
a) O(n), O(n)
b) O(logn), O(logn)
c) O(logn), O(n)
d) O(n), O(logn)
View Answer
Answer: d
Explanation: Worst case arises when the tree is skewed(either to the left or
right) in which case you have to process all the nodes of the tree giving O(n)
complexity, otherwise O(logn) as you process only the left half or the right half
of the tree.
9. Given that 2 elements are present in the tree, write a function to find the
LCA(Least Common Ancestor) of the 2 elements.
a)

public void lca(Tree root,int n1, int n2)


{
while (root != NULL)
{
if (root.data() > n1 && root.data() > n2)
root = root.right();
else if (root.data() < n1 && root.data() < n2)
root = root.left();
else break;
}
System.out.println(root.data());
}
b)

public void lca(Tree root,int n1, int n2)


{
while (root != NULL)
{
if (root.data() > n1 && root.data() < n2)
root = root.left();
else if (root.data() < n1 && root.data() > n2)
root = root.right();
else break;
}
System.out.println(root.data());
}
c)

public void lca(Tree root,int n1, int n2)


{
while (root != NULL)
{
if (root.data() > n1 && root.data() > n2)
root = root.left();
else if (root.data() < n1 && root.data() < n2)
root = root.right();
else break;
}
System.out.println(root.data());
}
d)

public void lca(Tree root,int n1, int n2)


{
while (root != NULL)
{
if (root.data() > n1 && root.data() > n2)
root = root.left.left();
else if (root.data() < n1 && root.data() < n2)
root = root.right.right();
else break;
}
System.out.println(root.data());
}
View Answer
Answer: c
Explanation: The property of a binary search tree is that the lesser elements
are to the left and greater elements are to the right, we use this property here
and iterate through the tree such that we reach a point where the 2 elements
are on 2 different sides of the node, this becomes the least common ancestor
of the 2 given elements.

10. What are the conditions for an optimal binary search tree and what is its
advantage?
a) The tree should not be modified and you should know how often the keys
are accessed, it improves the lookup cost
b) You should know the frequency of access of the keys, improves the lookup
time
c) The tree can be modified and you should know the number of elements in
the tree before hand, it improves the deletion time
d) The tree should be just modified and improves the lookup time
View Answer
Answer: a
Explanation: For an optimal binary search The tree should not be modified and
we need to find how often keys are accessed. Optimal binary search improves
the lookup cost.
11. Construct a binary search tree with the below information.
The preorder traversal of a binary search tree 10, 4, 3, 5, 11, 12.

a)

b)

c)
d)
View Answer
Answer: c
Explanation: Preorder Traversal is 10, 4, 3, 5, 11, 12. Inorder Traversal of Binary
search tree is equal to ascending order of the nodes of the Tree. Inorder
Traversal is 3, 4, 5, 10, 11, 12. The tree constructed using Preorder and Inorder
traversal is

1. What will be the height of a balanced full binary tree with 8 leaves?
a) 8
b) 5
c) 6
d) 4
View Answer
Answer: d
Explanation: A balanced full binary tree with l leaves has height h, where h =
log2l + 1.
So, the height of a balanced full binary tree with 8 leaves = log28 + 1 = 3 + 1 =
4.
2. The balance factor of a node in a binary tree is defined as _____
a) addition of heights of left and right subtrees
b) height of right subtree minus height of left subtree
c) height of left subtree minus height of right subtree
d) height of right subtree minus one
View Answer
Answer: c
Explanation: For a node in a binary tree, the difference between the heights of
its left subtree and right subtree is known as balance factor of the node.
3. Figure below is a balanced binary tree. If a node inserted as child of the node
R, how many nodes will become unbalanced?

a) 2
b) 1
c) 3
d) 0
View Answer
Answer: b
Explanation: Only the node P will become unbalanced, with balance factor +2.
advertisement
4. A binary tree is balanced if the difference between left and right subtree of
every node is not more than ____
a) 1
b) 3
c) 2
d) 0
View Answer
Answer: a
Explanation: In a balanced binary tree the heights of two subtrees of every
node never differ by more than 1.
5. Which of the following tree data structures is not a balanced binary tree?
a) AVL tree
b) Red-black tree
c) Splay tree
d) B-tree
View Answer
Answer: d
Explanation: All the tree data structures given in options are balanced, but B-
tree can have more than two children.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
Participate Now!
6. Which of following figures is a balanced binary tree?

a)

b)

c)

d)
View Answer
Answer: b
Explanation: In Some tree diagrams, the root of tree has balance factor +2, so
the tree is not balanced. If every node in the tree is balanced, then it’s a
balanced tree.
7. Balanced binary tree with n items allows the lookup of an item in ____
worst-case time.
a) O(log n)
b) O(nlog 2)
c) O(n)
d) O(1)
View Answer
Answer: a
Explanation: Searching an item in balanced binary is fast and worst-case time
complexity of the search is O(log n).
8. Which of the following data structures can be efficiently implemented using
height balanced binary search tree?
a) sets
b) priority queue
c) heap
d) both sets and priority queue
View Answer
Answer: d
Explanation: Height-Balanced binary search tree can provide an efficient
implementation of sets, priority queues.
9. Two balanced binary trees are given with m and n elements respectively.
They can be merged into a balanced binary search tree in ____ time.
a) O(m+n)
b) O(mn)
c) O(m)
d) O(mlog n)
View Answer
Answer: a
Explanation: First we store the in-order traversals of both the trees in two
separate arrays and then we can merge these sorted sequences in O(m+n)
time. And then we construct the balanced tree from this final sorted array.
10. Which of the following is an advantage of balanced binary search tree, like
AVL tree, compared to binary heap?
a) insertion takes less time
b) deletion takes less time
c) searching takes less time
d) construction of the tree takes less time than binary heap
View Answer
Answer: a
Explanation: Insertion and deletion, in both the binary heap and balanced
binary search tree takes O(log n). But searching in balanced binary search tree
requires O(log n) while binary heap takes O(n). Construction of balanced binary
search tree takes O(nlog n) time while binary heap takes O(n).
11. AVL trees are more balanced than Red-black trees.
a) True
b) False
View Answer
Answer: a
Explanation: AVL tree is more balanced than a Red-black tree because AVL tree
has less height than Red-black tree given that both trees have the same
number of elements.
12. The figure shown below is a balanced binary tree. If node P is deleted,
which of the following nodes will get unbalanced?

a) U
b) M
c) H
d) A
View Answer
Answer: a
Explanation: Node U will get unbalanced if node P is deleted, because it’s
balance factor will become -2.

You might also like