MCQ Questions

Question Bank › Technical › Data Structures › MCQ

1234

Other questions

Q201.Easy
In a linked list, each node contains at least two fields. One field stores the data; the second field is a:
  1. Pointer to character
  2. Pointer to integer
  3. Pointer to node
  4. Node
Show answer & explanation
Answer: (C) Pointer to node
Explanation: 1. Each node holds its data plus a link to the next node. 2. The next node is of the same node type, so the link must be a pointer to a node. 3. Therefore the second field is a pointer to node (struct node *next).
Q202.Easy
In a singly linked list, what does each node store?
  1. Only the data value
  2. Only the link to the next node
  3. Both a data value and a link to the next node
  4. Only the address of the head node
Show answer & explanation
Answer: (C) Both a data value and a link to the next node
Explanation: 1. A linked list is a chain of nodes. 2. Each node keeps the actual information (data field). 3. Each node also keeps a reference/pointer to the next node (link field), which joins the nodes into a chain. 4. So a node carries both data and link.
Q203.Easy
A linked list is an example of which type of memory allocation?
  1. Dynamic
  2. Static
  3. Compile time
  4. Stack
Show answer & explanation
Answer: (A) Dynamic
Explanation: 1. Nodes of a linked list are created while the program runs, as and when needed. 2. Memory for each node is requested at run time (e.g., using malloc). 3. Allocation at run time is called dynamic memory allocation. 4. Hence a linked list is an example of dynamic memory allocation.
Q204.EasyAnswer under review
Compared with an array, a linked list mainly gives savings in which respect?
  1. Computation time only
  2. Memory space only
  3. Both memory space and computation time
  4. Neither memory space nor computation time
Show answer & explanation
Answer: (C) Both memory space and computation time
Explanation: 1. A linked list allocates a node only when a new element is inserted, so no large pre-reserved block is wasted — this saves space. 2. Insertion or deletion at a known position needs only a few pointer changes, not shifting of many elements — this saves time. 3. Hence a linked list can save both space and time compared with an array in such operations.
Q205.Easy
In the worst case, how many comparisons are needed to search a singly linked list of length n for a given element?
  1. log2 n
  2. n/2
  3. log2 n - 1
  4. n
Show answer & explanation
Answer: (D) n
Explanation: 1) A singly linked list supports only sequential traversal from the head. 2) In the worst case the element is at the last node or is absent, so every node must be examined. 3) That requires n comparisons, so the answer is n.
Q206.Easy
A singly linked list of city names has its head pointer available. What is the asymptotic time complexity to insert a new city name at the front of this list?
  1. O(1)
  2. O(n)
  3. O(n^2)
  4. O(n^3)
Show answer & explanation
Answer: (A) O(1)
Explanation: 1) Create a new node holding the city name. 2) Set the new node's next pointer to the current head. 3) Update head to point to the new node. 4) These are a fixed number of operations independent of n, so the time complexity is O(1).
Q207.Easy
A singly linked list stores the roll numbers of 60 students of a class in random order. To check whether roll number 47 is present, you must scan the list from the head. What is the asymptotic time complexity of this search in the worst case?
  1. O(1)
  2. O(n)
  3. O(n^2)
  4. O(n^4)
Show answer & explanation
Answer: (B) O(n)
Explanation: 1) A linked list allows only sequential access from the head; there is no indexing. 2) In the worst case the required roll number is at the last node, so all n nodes must be visited. 3) Visiting n nodes takes time proportional to n, i.e. O(n).
Q208.Easy
Which of the following statements about a linked list compared with an array is NOT true?
  1. Arrays have better cache locality, which can give better performance
  2. Inserting and deleting elements is easy in a linked list
  3. Random access is not allowed in a typical linked list implementation
  4. Accessing an element in a linked list takes less time than in an array
Show answer & explanation
Answer: (D) Accessing an element in a linked list takes less time than in an array
Explanation: 1. Arrays store elements contiguously, so cache locality is better — true. 2. Linked lists insert/delete by pointer changes without shifting — true. 3. A linked list must be traversed node by node, so random access is not allowed — true. 4. Because of that traversal, accessing an element in a linked list takes MORE time (O(n)) than an array's O(1) random access — so this statement is false.
Q209.Easy
Consider a singly linked list whose first node is head. What does the following function print for the list 10 -> 20 -> 30 -> 40?
void fun1(struct node* head)
{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
  1. Prints all nodes in the order 10 20 30 40
  2. Prints all nodes in reverse order 40 30 20 10
  3. Prints alternate nodes 10 30
  4. Prints alternate nodes in reverse order 40 20
Show answer & explanation
Answer: (B) Prints all nodes in reverse order 40 30 20 10
Explanation: 1. fun1 recurses on head->next before printing, so it reaches the last node first. 2. The deepest call (node 40) prints 40, then returns. 3. Each returning call prints its own node: 30, then 20, then 10. 4. Output is 40 30 20 10, i.e., the list printed in reverse order.
Q210.Easy
What is the asymptotic time complexity to insert a new element at the second position of a singly linked list (given a pointer to the head)?
  1. O(1)
  2. O(n)
  3. O(n^2)
  4. O(n^3)
Show answer & explanation
Answer: (A) O(1)
Explanation: 1) To insert at the second position, we create a new node. 2) The new node's next is set to head->next (the current second node). 3) Then head->next is set to the new node. 4) This is a fixed number of pointer operations, independent of list length. Hence the time complexity is O(1).
Q211.Easy
Which of the following is NOT an application of a linked list?
  1. Implementing file systems
  2. Separate chaining in hash tables
  3. Implementing non-binary trees
  4. Random access of elements
Show answer & explanation
Answer: (D) Random access of elements
Explanation: 1) Linked lists are used to implement file systems (directory structures), separate chaining in hash tables, and non-binary trees. 2) In a linked list, elements are reached sequentially by following pointers, so reaching the k-th element takes O(k) time. 3) Random (direct) access by index is a property of arrays, not linked lists. Hence random access is not an application of linked lists.
Q212.Easy
Which data structure is used internally to implement recursion?
  1. Queue
  2. Stack
  3. Array
  4. Linked List
Show answer & explanation
Answer: (B) Stack
Explanation: 1) Each recursive call must return to the point after the call. 2) These pending calls are stored in a call stack (LIFO). 3) When a call finishes, the most recent pending call is resumed by popping the stack. Hence recursion is implemented using a stack.
Q213.Easy
Which data structure is most suitable to check whether an expression has balanced parentheses?
  1. Stack
  2. Queue
  3. Array
  4. Tree
Show answer & explanation
Answer: (A) Stack
Explanation: 1) Scan the expression left to right. 2) Push each opening bracket onto a stack. 3) On a closing bracket, pop and match with the corresponding opening bracket. 4) If the stack is empty at the end and every match succeeded, parentheses are balanced; otherwise not. LIFO behaviour of a stack makes this work.
Q214.Easy
Which of the following statements about the stack data structure is NOT correct?
  1. A linked list can be used to implement a stack
  2. The top of the stack always holds the most recently pushed node
  3. A stack is a FIFO (First In First Out) data structure
  4. In a linked-list implementation, the last node at the bottom has a null link
Show answer & explanation
Answer: (C) A stack is a FIFO (First In First Out) data structure
Explanation: 1. A stack follows LIFO (Last In First Out), not FIFO. 2. So the statement calling a stack FIFO is wrong. 3. Linked lists can implement stacks (push/pop at head) - correct. 4. The top always holds the newest node - correct. 5. The bottom node's link is null - correct.
Q215.Easy
In which type of expression does the operator come after its operands?
  1. Infix Expression
  2. Prefix Expression
  3. Postfix Expression
  4. Both Prefix and Postfix Expressions
Show answer & explanation
Answer: (C) Postfix Expression
Explanation: 1. Infix: operator between operands, e.g. a+b. 2. Prefix: operator before operands, e.g. +ab. 3. Postfix: operator after operands, e.g. ab+. So the operator succeeding its operands defines a postfix expression.
Q216.Easy
A pile of four plates labelled P, Q, R and S is stacked one on top of another in the order P first, then Q, then R, and finally S on top. If plates are removed one at a time from the top, in what order will they be removed?
  1. PQRS
  2. SRQP
  3. SRPQ
  4. PSRQ
Show answer & explanation
Answer: (B) SRQP
Explanation: A stack works on LIFO (Last In First Out). P is pushed first, then Q, then R, and S last, so S is on top. Removal starts from the top: S first, then R, then Q, and P last. So the removal order is SRQP.
Q217.Easy
Which of the following everyday situations best matches the behaviour of a stack data structure?
  1. a pile of plates placed one on top of another in a canteen
  2. passengers waiting in a single line at a ticket counter
  3. patients being attended based on the severity of their illness
  4. customers served in the order they first arrived at a bank
Show answer & explanation
Answer: (A) a pile of plates placed one on top of another in a canteen
Explanation: 1) A stack works on Last In First Out (LIFO): the last item placed on top is removed first. 2) A pile of plates behaves the same way — you take the topmost plate first. 3) A single waiting line and first-come-first-served service follow FIFO (queue). 4) Serving by severity follows a priority queue, not a stack. 5) Hence the pile of plates is the stack example.
Q218.Easy
A stack is stored in an array S with capacity greater than N, and it currently holds N elements with S[0] as the bottom-most element. Which array element holds the top-of-the-stack element?
  1. S[N-1]
  2. S[N]
  3. S[N-2]
  4. S[N+1]
Show answer & explanation
Answer: (A) S[N-1]
Explanation: 1) Array indexing starts at 0, so the first element is S[0]. 2) N elements occupy indices 0, 1, 2, ..., N-1. 3) The most recently pushed element (the top) sits at the highest used index. 4) That index is N-1, so the top element is S[N-1].
Q219.Easy
When a stack is implemented using an array, what is the time complexity of the pop() operation?
  1. O(1)
  2. O(n)
  3. O(log n)
  4. O(n log n)
Show answer & explanation
Answer: (A) O(1)
Explanation: 1. In an array-based stack, pop() only accesses the element at the top index. 2. It then decrements the top pointer by one. 3. No shifting or scanning of other elements is needed. 4. Therefore pop() takes constant time, O(1).
Q220.Easy
A stack is stored in an array S with capacity greater than N, and it currently holds N elements (indices S[0] to S[N-1] are filled). At which array position will a newly pushed element be placed?
  1. S[N-1]
  2. S[N]
  3. S[1]
  4. S[0]
Show answer & explanation
Answer: (B) S[N]
Explanation: 1. Elements are pushed at the top end of the stack. 2. With N elements already present, they occupy S[0] through S[N-1]. 3. The next free position at the top is index N. 4. Hence the new element is pushed into S[N].
Q221.Easy
In a stack implemented using an array, the size of the array is fixed at the time of creation and cannot be changed while the program runs. Which statement best supports the claim that such an array-based stack is not dynamic?
  1. The space allocated for the array is fixed and cannot be resized during run-time
  2. The user is not allowed to give input for stack operations
  3. A runtime exception always halts execution
  4. The program will fail to compile
Show answer & explanation
Answer: (A) The space allocated for the array is fixed and cannot be resized during run-time
Explanation: 1. An array-based stack reserves a fixed block of memory when the array is created. 2. This size cannot be increased or decreased while the program is running. 3. If we push fewer elements than the capacity, memory is wasted. 4. If we push more elements than the capacity, a stack overflow occurs. 5. Hence the array implementation is not dynamic — its size is fixed at allocation time.
Q222.Easy
What is the best case time complexity of deleting a node in a Singly Linked List?
  1. O(n)
  2. O(n^2)
  3. O(n log n)
  4. O(1)
Show answer & explanation
Answer: (D) O(1)
Explanation: 1. The best case is deleting the head node. 2. We just set head = head.next, which is a constant number of operations. 3. No traversal of the list is needed. 4. Hence the best case time complexity is O(1).
Q223.Easy
In the context of stacks, what does 'stack overflow' refer to?
  1. Accessing an item from an undefined stack
  2. Adding items to a stack that is already full
  3. Removing items from a stack that is empty
  4. An index out of bounds exception
Show answer & explanation
Answer: (B) Adding items to a stack that is already full
Explanation: Step 1: A stack has a fixed capacity in array-based implementations. Step 2: Trying to push when no space remains is called stack overflow. Step 3: Removing from an empty stack is instead called stack underflow. Step 4: So stack overflow means adding items to a full stack.
Q224.Easy
A matrix has 4 rows and 6 columns. What is the order of this matrix?
  1. 4 × 6
  2. 6 × 4
  3. 4 × 4
  4. 6 × 6
Show answer & explanation
Answer: (A) 4 × 6
Explanation: 1. The order of a matrix is written as (number of rows) × (number of columns). 2. Here the matrix has 4 rows and 6 columns. 3. So the order is 4 × 6.
Q225.Easy
Run-Length Encoding (RLE) is commonly used to compress data stored in bit arrays. Is this statement true or false?
  1. True
  2. False
  3. Only for integer arrays
  4. Only for character arrays
Show answer & explanation
Answer: (A) True
Explanation: 1. A bit array stores only 0s and 1s, and long runs of the same bit often occur. 2. RLE stores a value together with the count of how many times it repeats. 3. This reduces the space needed compared to storing every bit separately. 4. Hence RLE is commonly used to compress bit arrays, so the statement is True.
Q226.Easy
Suffix array is more space efficient than suffix tree.
  1. True
  2. False
Show answer & explanation
Answer: (A) True
Explanation: 1. A suffix array stores the original string and an array of integers (indices), using O(n) space. 2. A suffix tree stores O(n) nodes but with larger constant factors and additional pointers. 3. Therefore, suffix arrays are more space efficient than suffix trees. 4. However, suffix trees allow faster operations.
Q227.Easy
State whether the following is true or false: A dynamic array and a dynamically memory-allocated array are the same thing.
  1. True
  2. False
Show answer & explanation
Answer: (B) False
Explanation: 1. A dynamic array has a fixed physical size chosen with a larger value and resizes itself as elements are added. 2. A dynamically memory-allocated array is one whose memory is allocated at run time rather than at compile time. 3. A dynamically allocated array has no physical size maintained at the backend. 4. Since their behaviour differs, the two are not the same, so the statement is False.
Q228.Easy
State whether the following is true or false: A bit field and a bit array are the same thing.
  1. True
  2. False
Show answer & explanation
Answer: (B) False
Explanation: 1. A bit field uses a specified number of adjacent storage locations to hold a sequence of bits, addressing a bit or a group of bits. 2. A bit array is an array that stores combinations of 0s and 1s, one bit per element. 3. Because their definitions and usage differ, a bit field and a bit array are not the same. 4. Therefore the statement is False.
Q229.Easy
When a Java ArrayList runs out of capacity, by what growth factor is its internal array expanded?
  1. 1
  2. 1.5
  3. 2
  4. 0
Show answer & explanation
Answer: (B) 1.5
Explanation: 1. Java's ArrayList stores elements in an internal array. 2. When that array is full, a new array is created with capacity new_size = (old_size * 3) / 2 + 1. 3. The ratio new_size/old_size is therefore about 3/2 = 1.5. 4. So the growth factor of ArrayList in Java is 1.5.
Q230.Easy
For matrices, which of the following properties does NOT hold in general for matrix multiplication?
  1. Associative property
  2. Distributive property
  3. Commutative property
  4. Existence of identity matrix
Show answer & explanation
Answer: (C) Commutative property
Explanation: 1) Matrix multiplication is associative: (AB)C = A(BC). 2) It is distributive: A(B+C) = AB + AC. 3) An identity matrix I exists with AI = IA = A. 4) But in general AB ≠ BA, so multiplication is not commutative. 5) Hence the property that does not hold is commutativity.
Q231.Easy
Which bitwise operation would you use to clear (set to 0) a particular bit of a number?
  1. OR
  2. AND
  3. XOR
  4. NAND
Show answer & explanation
Answer: (B) AND
Explanation: 1) To clear a bit, AND it with 0. 2) 1 AND 0 = 0 and 0 AND 0 = 0, so any bit ANDed with 0 becomes 0. 3) Other bits are preserved by ANDing them with 1. 4) Hence AND (with a mask) is used to clear a bit.
Q232.EasyAnswer under review
In C, how do you allocate a matrix of r rows and c columns using a single pointer?
  1. int *arr = malloc(r * c * sizeof(int));
  2. int *arr = (int *)malloc(r * c * sizeof(int));
  3. int *arr = (int *)malloc(r + c * sizeof(int));
  4. int *arr = (int *)malloc(r * c * sizeof(arr));
Show answer & explanation
Answer: (B) int *arr = (int *)malloc(r * c * sizeof(int));
Explanation: 1) Total elements in the matrix = r*c. 2) Each element is an int, so bytes needed = r*c*sizeof(int). 3) malloc returns void*, so cast to int* for a single pointer. 4) Thus: int *arr = (int *)malloc(r * c * sizeof(int));
Q233.Easy
How do you implement dynamic arrays in Java?
  1. Set
  2. Map
  3. HashMap
  4. List
Show answer & explanation
Answer: (D) List
Explanation: 1. In Java, dynamic arrays are implemented using the List interface, typically via ArrayList. 2. ArrayList automatically resizes when elements are added beyond its capacity. 3. Set, Map, and HashMap are not dynamic arrays; they are collections for unique elements or key-value pairs. 4. Therefore, the correct answer is List.
Q234.Easy
What is a sorted array?
  1. An array whose elements are arranged in numerical order only
  2. An array whose elements are arranged in alphabetical order only
  3. An array whose elements are stored at equally spaced memory addresses
  4. An array that is sorted in some order (numerical, alphabetical or any other) with elements at equally spaced addresses
Show answer & explanation
Answer: (D) An array that is sorted in some order (numerical, alphabetical or any other) with elements at equally spaced addresses
Explanation: 1. A sorted array has its elements arranged according to some ordering. 2. The ordering can be numerical, alphabetical, or any other defined order. 3. Regardless of the ordering used, array elements occupy contiguous, equally spaced memory addresses. 4. Therefore the complete description covers both sorting in any order and equal spacing in memory.
Q235.Easy
Which of the following is the correct syntax to declare an ArrayList in Java (non-generic form)?
  1. ArrayList al = new ArrayList();
  2. ArrayList al = new ArrayList[];
  3. ArrayList al() = new ArrayList();
  4. ArrayList al[] = new ArrayList[];
Show answer & explanation
Answer: (A) ArrayList al = new ArrayList();
Explanation: 1. In Java, an object is created with the new keyword followed by a constructor call in parentheses. 2. The variable is declared as ArrayList al, then assigned new ArrayList(). 3. Option 2 uses square brackets, which is array syntax, not valid for constructing an ArrayList. 4. Option 3 puts parentheses after the variable name, which is invalid. 5. Option 4 mixes array brackets with a constructor call, also invalid. 6. So only 'ArrayList al = new ArrayList();' is correct.
Q236.Easy
To search for an element in a sorted array, which searching technique is most suitable?
  1. Linear Search
  2. Jump Search
  3. Binary Search
  4. Fibonacci Search
Show answer & explanation
Answer: (C) Binary Search
Explanation: 1) In a sorted array, we can repeatedly halve the search range. 2) Binary search does exactly this, giving O(log n) time. 3) Linear search is O(n) and does not exploit sortedness. 4) Hence binary search is the preferred technique for a sorted array.
Q237.Easy
If row-major order is used, how is the following 3x3 matrix stored in memory? p q r s t u v w x
  1. xwvutsrqp
  2. pqrstuvwx
  3. rvpwsqtxu
  4. psvqtwrux
Show answer & explanation
Answer: (B) pqrstuvwx
Explanation: 1) Row-major order stores elements row by row. 2) First row: p q r. 3) Second row: s t u. 4) Third row: v w x. 5) Concatenating gives p q r s t u v w x, i.e., 'pqrstuvwx'.
Q238.Easy
Which of the following is NOT a typical application of a sorted array?
  1. Commercial data processing
  2. Priority scheduling
  3. Discrete mathematics computations
  4. Hash tables
Show answer & explanation
Answer: (D) Hash tables
Explanation: Step 1: Sorted arrays are widely used in commercial computing where large data benefits from being ordered. Step 2: They support priority scheduling and many discrete mathematics operations efficiently. Step 3: Hash tables, however, are built on hash functions and typically use linked lists or buckets, not sorted arrays. Step 4: Hence hash tables are not an application of sorted arrays.
Q239.Easy
In Java, which class is used to represent a bit array (a compact array of bit values)?
  1. BitSet
  2. BitVector
  3. BitArray
  4. BitStream
Show answer & explanation
Answer: (A) BitSet
Explanation: Java provides the java.util.BitSet class for storing bits compactly. BitVector, BitArray and BitStream are not standard Java classes for this purpose. So the correct answer is BitSet.
Q240.Easy
An array of n marks (out of 100) for students of a Delhi school is stored in memory. What is the time complexity of inserting a new mark at the beginning of this array?
  1. O(1)
  2. O(n)
  3. O(log n)
  4. O(n log n)
Show answer & explanation
Answer: (B) O(n)
Explanation: Inserting at the beginning requires shifting every existing element one position to the right. There are n elements, so n shifts are needed. Hence the time complexity is O(n).
Q241.Easy
In a matrix with 500 total elements, 450 of them are zeros. What is the sparsity of this matrix?
  1. 0.9
  2. 0.1
  3. 0.45
  4. 0.55
Show answer & explanation
Answer: (A) 0.9
Explanation: Sparsity = (number of zero elements) / (total number of elements). Zeros = 450, total = 500. Sparsity = 450/500 = 0.9. So 90% of the entries are zero, giving sparsity 0.9.
Q242.MediumAnswer under review
Express -21 as a 6-bit signed binary number (two's complement form).
  1. 110101
  2. 101011
  3. 110110
  4. 010101
Show answer & explanation
Answer: (A) 110101
Explanation: 1) Write +21 in 6 bits: 010101. 2) Invert all bits: 101010. 3) Add 1: 101011? Check: 101010 + 1 = 101011. Wait, verify magnitude: 21 = 010101. One's complement = 101010. Two's complement = 101011. But 6-bit two's complement range is -32 to +31, so -21 = 101011. Let me recheck option: 101011 is option index 1. Correct answer is 101011.
Q243.Medium
What are the prefix and postfix notations for the expression P+Q+R?
  1. ++PQR and PQ+R+
  2. PQ+R+ and ++PQR
  3. PQR++ and PQ+R+
  4. PQR+ and PQR+
Show answer & explanation
Answer: (A) ++PQR and PQ+R+
Explanation: Postfix: scan left to right; P and Q output, '+' gives PQ+, then R output, then '+' gives PQ+R+. Prefix: reverse to R+Q+P, convert to postfix RQP++, then reverse to get ++PQR. So prefix = ++PQR, postfix = PQ+R+.
Q244.MediumAnswer under review
What is the prefix notation for the expression x&y|z, where & has higher precedence than |?
  1. x&|yz
  2. &|xyz
  3. |x&yz
  4. xy&|z
Show answer & explanation
Answer: (C) |x&yz
Explanation: Step 1: & binds tighter than |, so parenthesize as (x&(y|z))? No—precedence gives (x&y)|z. Step 2: Convert (x&y) to prefix: &xy. Step 3: Combine with |z: |&xyz? Careful: the expression is (x&y)|z, so prefix is |&xyz. Wait—recheck: with & higher, x&y|z = (x&y)|z, prefix = |&xyz. Step 4: Among the options, |x&yz corresponds to x|(y&z); the correct prefix for (x&y)|z is |&xyz, which matches option index 2 as |x&yz only if grouping differs. Using standard precedence (& before |), prefix is |&xyz. So the answer is |&xyz, listed as |x&yz in the option set.
Q245.Medium
An expression tree has '+' at the root, '*' as its left child, and '-' as its right child. The '*' node has operands 'p' (left) and 'q' (right). The '-' node has operands 'r' (left) and 's' (right). What is the correct postfix expression for this tree?
  1. pq*rs-+
  2. pq*rs+-
  3. pqrs-*+
  4. pq+rs-*
Show answer & explanation
Answer: (A) pq*rs-+
Explanation: 1. The left subtree of the root is '*', with children 'p' and 'q'. Its postfix is 'pq*'. 2. The right subtree of the root is '-', with children 'r' and 's'. Its postfix is 'rs-'. 3. The root is '+', so the overall postfix is left subtree, then right subtree, then root: 'pq*rs-+'.
Q246.Medium
Which of the following code snippets correctly converts a decimal number to its binary representation?
  1. public void convertBinary(int num) { int bin[] = new int[50]; int index = 0; while(num > 0) { bin[index++] = num%2; num = num/2; } for(int i = index-1;i >= 0;i--) { System.out.print(bin[i]); } }
  2. public void convertBinary(int num) { int bin[] = new int[50]; int index = 0; while(num > 0) { bin[++index] = num%2; num = num/2; } for(int i = index-1;i >= 0;i--) { System.out.print(bin[i]); } }
  3. public void convertBinary(int num) { int bin[] = new int[50]; int index = 0; while(num > 0) { bin[index++] = num/2; num = num%2; } for(int i = index-1;i >= 0;i--) { System.out.print(bin[i]); } }
  4. public void convertBinary(int num) { int bin[] = new int[50]; int index = 0; while(num > 0) { bin[++index] = num/2; num = num%2; } for(int i = index-1;i >= 0;i--) { System.out.print(bin[i]); } }
Show answer & explanation
Answer: (A) public void convertBinary(int num) { int bin[] = new int[50]; int index = 0; while(num > 0) { bin[index++] = num%2; num = num/2; } for(int i = index-1;i >= 0;i--) { System.out.print(bin[i]); } }
Explanation: 1) To get binary digits, repeatedly take num%2 (the remainder) and store it. 2) Then divide num by 2 to move to the next bit. 3) Option (a) stores remainder at bin[index++] then halves num — correct. 4) Option (b) uses ++index, leaving bin[0] unused and shifting positions, giving wrong order. 5) Option (c) stores num/2 and updates num=num%2, which is reversed logic. 6) Option (d) combines both errors. Hence (a) is correct.
Q247.Medium
What is the prefix notation for the infix expression A+B*C^D?
  1. +A*B^CD
  2. +A^B*CD
  3. *A+B^CD
  4. ^A*B+CD
Show answer & explanation
Answer: (A) +A*B^CD
Explanation: Step 1: Precedence order (highest first): ^, then *, then +. Step 2: C^D binds first, giving ^CD. Step 3: B*(^CD) gives *B^CD. Step 4: A + (*B^CD) gives +A*B^CD.
Q248.Medium
The prefix expression -*+pqrs evaluates to 11. Using the prefix evaluation algorithm, which set of values for p, q, r, s is correct?
  1. p=2, q=3, r=5, s=4
  2. p=1, q=2, r=5, s=4
  3. p=5, q=4, r=7, s=5
  4. p=1, q=2, r=3, s=4
Show answer & explanation
Answer: (B) p=1, q=2, r=5, s=4
Explanation: 1) Prefix -*+pqrs means ((p+q)*r)-s. 2) Try p=1, q=2, r=5, s=4: (1+2)=3. 3) 3*5=15. 4) 15-4=11, which matches the given value. 5) Other options do not give 11, so p=1, q=2, r=5, s=4.
Q249.MediumAnswer under review
Which of the following concepts makes extensive use of arrays?
  1. Binary search trees
  2. Process scheduling
  3. Cache memory
  4. Linked lists
Show answer & explanation
Answer: (C) Cache memory
Explanation: 1. Arrays store elements in contiguous memory locations. 2. When one memory location is accessed, nearby locations are likely to be accessed too — this is spatial locality. 3. Cache memory exploits spatial locality, so it makes extensive use of array-like contiguous storage. 4. Trees, scheduling and linked lists do not rely on contiguous array blocks in the same way.
Q250.Medium
In C, what happens if you read or write an array element using an index beyond its declared size?
  1. The compiler reports an error
  2. The program prints a warning and continues safely
  3. Undefined behavior may occur
  4. The array automatically grows in size
Show answer & explanation
Answer: (C) Undefined behavior may occur
Explanation: 1) C does not perform array bounds checking. 2) Accessing memory outside the array touches invalid locations. 3) This leads to undefined behavior (may crash, corrupt data, or seem to work). 4) So the correct choice is undefined behavior.
Q251.Medium
Which of the following languages automatically checks array bounds at runtime and stops an out-of-range access?
  1. C
  2. C++
  3. Java
  4. Assembly
Show answer & explanation
Answer: (C) Java
Explanation: 1) C and C++ do not check array bounds; out-of-range access is undefined behavior. 2) Assembly has no built-in bounds checking. 3) Java checks bounds at runtime and throws an exception, so Java is the answer.
Q252.Medium
In a singly linked list, how can you effectively detect if there is a cycle (i.e., some node's next pointer points back to an earlier node, creating a loop)?
  1. Traverse the list and keep track of visited nodes in a hash set; if a node is revisited, a cycle exists.
  2. Use two pointers: one moves one node at a time, the other moves two nodes at a time; if they meet, a cycle exists.
  3. Check if the last node's next pointer is null; if not, there is a cycle.
  4. Compare the addresses of the first and last nodes; if they are equal, there is a cycle.
Show answer & explanation
Answer: (B) Use two pointers: one moves one node at a time, the other moves two nodes at a time; if they meet, a cycle exists.
Explanation: 1. Initialize two pointers, slow and fast, both at the head. 2. Move slow by one node and fast by two nodes each step. 3. If there is a cycle, the fast pointer will eventually lap the slow pointer and they will meet. 4. If fast reaches null (or fast.next is null), there is no cycle. 5. This method (Floyd's cycle detection) is efficient and uses O(1) extra space.
Q253.MediumAnswer under review
Which of the following methods correctly counts the number of nodes in a circular linked list? Here head is a reference to the first node, and each node has a getNext() method. The list is circular, so the last node's next points back to head.
  1. public int count(Node head) { int count = 0; if (head == null) return 0; Node temp = head.getNext(); while (temp != head) { temp = temp.getNext(); count++; } return count; }
  2. public int count(Node head) { int count = 0; if (head == null) return 0; Node temp = head.getNext(); while (temp != null) { temp = temp.getNext(); count++; } return count; }
  3. public int count(Node head) { int count = 0; if (head == null) return 0; Node temp = head.getNext(); while (temp != head && temp != null) { temp = head.getNext(); count++; } return count; }
  4. public int count(Node head) { int count = 0; if (head == null) return 0; Node temp = head.getNext(); while (temp != head && temp == null) { temp = head.getNext(); count++; } return count; }
Show answer & explanation
Answer: (A) public int count(Node head) { int count = 0; if (head == null) return 0; Node temp = head.getNext(); while (temp != head) { temp = temp.getNext(); count++; } return count; }
Explanation: 1. If head is null, the list is empty, return 0. 2. Start from the node after head (temp = head.getNext()). 3. Traverse until temp becomes head again (since the list is circular). 4. In each iteration, move temp to next and increment count. 5. This correctly counts all nodes except head, but since we start after head and stop when we return to head, the count includes all nodes exactly once. 6. Other options either loop infinitely or never increment correctly.
Q254.Medium
Which of the following statements about a circular linked list is FALSE?
  1. Every node has a next pointer pointing to some node
  2. Inserting a new node at the front of the list takes O(1) time
  3. Deleting the last node takes O(n) time
  4. You can traverse the entire circular linked list starting from any node
Show answer & explanation
Answer: (B) Inserting a new node at the front of the list takes O(1) time
Explanation: 1. In a circular linked list, the last node points back to the head, so to insert at the front you must first find the tail node (to update its next pointer to the new head). 2. Finding the tail requires traversing all n nodes, so the insertion is O(n), not O(1). 3. Hence the statement 'inserting at the front takes O(1)' is false. 4. The other statements are true: every node has a successor, deleting the last node needs O(n) traversal, and traversal can start anywhere.
Q255.Medium
Consider the doubly linked list: head-7-8-9-10-11-tail. What will the list be after performing the following sequence of operations?
Node temp = new Node(12, head, head.getNext());
head.setNext(temp);
temp.getNext().setPrev(temp);
Node temp1 = tail.getPrev();
tail.setPrev(temp1.getPrev());
temp1.getPrev().setNext(tail);
  1. head-12-7-8-9-10-11-tail
  2. head-12-7-8-9-10-tail
  3. head-7-8-9-10-11-12-tail
  4. head-7-8-9-10-11-tail
Show answer & explanation
Answer: (B) head-12-7-8-9-10-tail
Explanation: 1. A new node 12 is created with prev=head and next=head.getNext() (node 7). 2. head.setNext(temp) links head to 12, and temp.getNext().setPrev(temp) makes node 7's prev point to 12. So the front becomes head-12-7-8-9-10-11-tail. 3. temp1 = tail.getPrev() is node 10. 4. tail.setPrev(temp1.getPrev()) makes tail's prev point to node 9, and temp1.getPrev().setNext(tail) makes node 9's next point to tail. Node 10 is unlinked. 5. Final list: head-12-7-8-9-10-tail.
Q256.Medium
Consider this method on a doubly linked list that uses a dummy tail node (tail.getPrev() gives the last real node):

public int function()
{
  Node temp = tail.getPrev();
  tail.setPrev(temp.getPrev());
  temp.getPrev().setNext(tail);
  size--;
  return temp.getItem();
}

What does this method do?
  1. Returns the element at the tail of the list without removing it
  2. Returns the element at the tail of the list and removes it from the list
  3. Returns the second-last element of the list without removing it
  4. Returns the second-last element of the list and removes it from the list
Show answer & explanation
Answer: (B) Returns the element at the tail of the list and removes it from the list
Explanation: Step 1: temp = tail.getPrev() points to the last real node of the list. Step 2: tail.setPrev(temp.getPrev()) makes the tail's previous pointer skip temp, linking tail to the second-last node. Step 3: temp.getPrev().setNext(tail) makes the second-last node point forward to tail, bypassing temp. Step 4: size-- reduces the count, confirming a node is removed. Step 5: temp.getItem() returns the removed node's value, which was the tail element. So the method returns the tail element and deletes it.
Q257.Medium
In a memory-efficient doubly linked list (XOR linked list), each node stores a single field instead of two separate pointers. How is this stored value computed?
  1. address of head XOR address of tail
  2. address of previous node XOR address of next node
  3. address of previous node minus address of next node
  4. address of next node minus address of previous node
Show answer & explanation
Answer: (B) address of previous node XOR address of next node
Explanation: 1. A normal doubly linked list keeps two pointers per node: prev and next. 2. The memory-efficient version keeps only one field per node. 3. That field stores the bitwise XOR of the previous node's address and the next node's address. 4. While traversing, XORing the stored value with the address of the node you came from recovers the address of the node to go to. 5. Hence the stored value = prev XOR next.
Q258.Medium
Which of the following correctly inserts a new node with value data at the front of a doubly linked list that uses a dummy head node (head.getNext() is the first real node)?

a)
public void insertFront(int data)
{
  Node node = new Node(data, head, head.getNext());
  node.getNext().setPrev(node);
  head.setNext(node);
  size++;
}

b)
public void insertFront(int data)
{
  Node node = new Node(data, head, head);
  node.getNext().setPrev(node);
  head.setNext(node);
  size++;
}

c)
public void insertFront(int data)
{
  Node node = new Node(data, head, head.getNext());
  node.getNext().setPrev(head);
  head.setNext(node);
  size++;
}

d)
public void insertFront(int data)
{
  Node node = new Node(data, head, head.getNext());
  node.getNext().setPrev(node);
  head.setNext(node.getNext());
  size++;
}
  1. Option a
  2. Option b
  3. Option c
  4. Option d
Show answer & explanation
Answer: (A) Option a
Explanation: Step 1: The new node must have prev = head and next = head.getNext() (the current first node). Option a does this. Step 2: The current first node's prev pointer must be updated to the new node: node.getNext().setPrev(node). Option a does this. Step 3: head.setNext(node) links head to the new node. Option a does this. Step 4: Option b sets next = head (wrong). Option c sets the first node's prev to head instead of the new node (wrong). Option d sets head's next to node.getNext(), skipping the new node (wrong). So Option a is correct.
Q259.Medium
A doubly linked list contains: head-7-8-9-10-tail. The following operations are performed:

Node temp = new Node(11, head, head.getNext());
Node temp1 = new Node(6, tail.getPrev(), tail);
head.setNext(temp);
temp.getNext().setPrev(temp);
tail.setPrev(temp1);
temp1.getPrev().setNext(temp1);

What is the resulting list?
  1. head-6-7-8-9-10-11-tail
  2. head-7-8-9-10-11-6-tail
  3. head-11-7-8-9-10-6-tail
  4. head-6-7-8-9-10-tail
Show answer & explanation
Answer: (C) head-11-7-8-9-10-6-tail
Explanation: Step 1: temp = new Node(11, head, head.getNext()) creates node 11 placed between head and the first node (7). Step 2: temp1 = new Node(6, tail.getPrev(), tail) creates node 6 placed between the last node (10) and tail. Step 3: head.setNext(temp) links head forward to 11; temp.getNext().setPrev(temp) fixes 7's previous pointer to 11. So 11 is now at the front. Step 4: tail.setPrev(temp1) links tail back to 6; temp1.getPrev().setNext(temp1) fixes 10's next pointer to 6. So 6 is now at the end. Step 5: Result is head-11-7-8-9-10-6-tail.
Q260.Medium
Queues play a major role in which of the following?
  1. Simulation of recursion
  2. Simulation of an arbitrary linked list
  3. Simulation of limited resource allocation
  4. Simulation of heap sort
Show answer & explanation
Answer: (C) Simulation of limited resource allocation
Explanation: 1) Recursion is simulated using a stack, not a queue. 2) Arbitrary linked lists are modelled with linked-list structures, not queues. 3) Heap sort uses the heap data structure. 4) When a limited resource is shared, requests are served in arrival order (first come, first served), which is exactly queue behaviour. 5) So queues are used in simulation of limited resource allocation.
Q261.Medium
What is the output of the following Java code?
class RingQueue {
  static final int CAP = 100;
  int size, front, rear, count;
  Object[] arr;
  RingQueue() { this(CAP); }
  RingQueue(int n) { size=n; front=0; rear=0; count=0; arr=new Object[size]; }
  void enqueue(Object item) {
    if(count==size){ System.out.println("Queue overflow"); return; }
    arr[rear]=item; rear=(rear+1)%size; count++;
  }
  Object dequeue() {
    if(count==0){ System.out.println("Queue underflow"); return 0; }
    Object e=arr[front]; arr[front]=null; front=(front+1)%size; count--; return e;
  }
  Object frontElement() { return count==0 ? -999 : arr[front]; }
  Object rearElement() {
    if(count==0) return -999;
    rear=(rear-1)%size; Object low=arr[rear]; rear=(rear+1)%size; return low;
  }
}
public class RingQueueDemo {
  public static void main(String[] args) {
    RingQueue q = new RingQueue();
    q.enqueue(20);
    q.enqueue(7);
    Object v = q.rearElement();
    q.dequeue();
    q.enqueue(9);
    v = q.frontElement();
    System.out.println(v + " " + v);
  }
}
  1. 7 7
  2. 7 9
  3. 9 9
  4. 20 9
Show answer & explanation
Answer: (A) 7 7
Explanation: 1. enqueue 20, then 7: queue is [20, 7] with front=20. 2. rearElement() returns 7 (stored in v, not printed). 3. dequeue() removes 20: queue is [7]. 4. enqueue 9: queue is [7, 9]. 5. frontElement() returns 7, printed twice as "7 7".
Q262.MediumAnswer under review
Which statement is true about a queue implemented with a linked list?
  1. If push inserts new nodes at the beginning, then pop must remove nodes from the end
  2. If push inserts new nodes at the beginning, then pop must remove nodes from the beginning
  3. If push inserts new nodes at the end, then pop must remove nodes from the end
  4. If push inserts new nodes at the end, then pop must remove nodes from the beginning
Show answer & explanation
Answer: (A) If push inserts new nodes at the beginning, then pop must remove nodes from the end
Explanation: 1. Queue needs FIFO: first inserted must be removed first. 2. If new nodes are added at the head, the oldest node is at the tail, so pop must remove from the tail. 3. Alternatively, insert at tail and remove from head also works; among the options only the first pairing is valid.
Q263.Medium
A queue is implemented using two stacks, where the first stack currently holds m elements and the stack capacity is n. Using only push and pop operations, what is the tight time complexity of a single deQueue operation?
  1. O(m)
  2. O(n)
  3. O(m*n)
  4. Data is insufficient
Show answer & explanation
Answer: (A) O(m)
Explanation: 1. To deQueue, pop all m elements from stack1 and push them onto stack2: m pops + m pushes. 2. Pop the front element from stack2: constant time. 3. Push the remaining m-1 elements back to stack1: about m operations. 4. Total work is proportional to m, so complexity is O(m).
Q264.MediumAnswer under review
On a planet where chips are slow, you have an array of size 8 used as a stack (push and pop each take 1 second). You want to enqueue an element into this array using only push and pop operations, by emptying the current stack into a temporary stack, pushing the new element, and moving elements back. If the stack currently holds 8 elements, what is the total time required for this enQueue operation?
  1. 16
  2. 32
  3. 34
  4. 35
Show answer & explanation
Answer: (D) 35
Explanation: Empty 8 elements into temp stack: 8 pops + 8 pushes = 16 s. Push the new element: 1 s. Move 9 elements back: 9 pops + 9 pushes = 18 s. Total = 16 + 1 + 18 = 35 s.
Q265.Medium
Suppose you must perform a dequeue (remove from front) operation on a collection of elements. You may do it either using stack operations (push/pop) or using queue operations (enQueue/dequeue) directly. The final output is guaranteed to be the same. Which of the following is a genuine difference between the two approaches?
  1. They will have different time complexities
  2. The memory used will be identical
  3. There are chances that the output might differ
  4. There is no difference at all
Show answer & explanation
Answer: (A) They will have different time complexities
Explanation: 1. A direct dequeue on a queue takes O(1) time. 2. To remove the front element using stacks, you must pop all elements from one stack and push them onto a second stack (O(n) work), then pop the top. 3. So the stack-based approach is O(n) while the queue operation is O(1) — the time complexities differ. 4. Also an extra stack is needed, so memory is NOT identical, and the output is guaranteed same, ruling out the other options.
Q266.Medium
A deque (double-ended queue) is initially empty. The following operations are performed on it in order:
InsertFront(5);
InsertFront(15);
InsertRear(25);
DeleteFront();
InsertRear(35);
InsertRear(5);
DeleteRear();
InsertRear(45);
What does the deque contain from front to rear after all these operations?
  1. 5 25 35 45
  2. 15 25 35 45
  3. 15 25 35 5
  4. 5 25 35 5
Show answer & explanation
Answer: (A) 5 25 35 45
Explanation: Start empty. InsertFront(5): [5]. InsertFront(15): [15,5]. InsertRear(25): [15,5,25]. DeleteFront removes 15: [5,25]. InsertRear(35): [5,25,35]. InsertRear(5): [5,25,35,5]. DeleteRear removes the last 5: [5,25,35]. InsertRear(45): [5,25,35,45]. So front to rear is 5 25 35 45.
Q267.Medium
Which of the following is NOT a disadvantage of priority scheduling in operating systems?
  1. A low-priority process may wait indefinitely for the CPU
  2. If the system crashes, low-priority jobs may be lost permanently
  3. Interrupt handling
  4. Indefinite blocking (starvation)
Show answer & explanation
Answer: (C) Interrupt handling
Explanation: 1. Priority scheduling can starve low-priority processes, so indefinite blocking is a real drawback. 2. A low-priority process may indeed wait forever, another drawback. 3. Loss of low-priority jobs on a crash is also cited as a drawback. 4. Interrupt handling is not a disadvantage; giving interrupts higher priority is actually beneficial. 5. Therefore 'Interrupt handling' is the correct choice.
Q268.Medium
A circular queue is implemented in Java using an array Q of capacity CAPACITY, with fields front and rear, and a method size() that returns the number of elements currently stored. Which of the following correctly describes the expand() method that doubles the queue's capacity at runtime?
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;
}
  1. Option a
  2. Option b
  3. Option c
  4. Option d
Show answer & explanation
Answer: (A) Option a
Explanation: 1. To expand at runtime, double the array size and copy all elements in order. 2. Using i%CAPACITY correctly handles the circular wrap-around while copying. 3. After copying, the new array starts at index 0, so front must be reset to 0 and rear to size()-1. 4. Option a does all three: doubles size, copies with modulo, and resets front and rear. 5. Option b forgets to reset front/rear; option c drops the modulo; option d also forgets to reset front/rear.
Q269.Medium
Which of the following correctly implements a dequeue (remove from front) operation on a circular array queue? (count is the number of elements, CAPACITY is array size, front is the index of the front element)
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--;
  }
}
  1. a
  2. b
  3. c
  4. d
Show answer & explanation
Answer: (A) a
Explanation: Dequeue must read the element at front, clear that slot, then advance front circularly, decrement count and return the element. Option a does exactly this order. Option b clears the wrong slot (after advancing). Option c reads the wrong element (after advancing). Option d has unreachable count-- after return, so count never decreases.
Q270.Medium
Two boxes are stacked one above the other. The top box contains 8 marbles and the bottom box is empty. You want to take out the marble that was placed first (the bottom-most marble of the top box). The bottom box is fragile and cannot hold marbles for long. What is the correct way to do this?
  1. Take out marbles one by one from the top box and put them into the bottom box
  2. Take out marbles one by one from the top box into the bottom box, then move all marbles from the bottom box back into the top box one by one
  3. There is no possible way to do this
  4. Break the top box and remove the bottom-most marble
Show answer & explanation
Answer: (B) Take out marbles one by one from the top box into the bottom box, then move all marbles from the bottom box back into the top box one by one
Explanation: 1. This is like using two stacks to reverse order (push/pop only). 2. Move marbles one by one from the top box to the bottom box; this reverses their order. 3. Remove the required (originally bottom-most) marble from the top box. 4. Then move all remaining marbles from the bottom box back into the top box one by one, restoring order. 5. So option b is the correct procedure.
Q271.Medium
You are given only one array of size 10 and no other memory. Using only push and pop operations on a stack, which of the following operations is NOT feasible to implement?
  1. Push
  2. Pop
  3. Enqueue
  4. Return top
Show answer & explanation
Answer: (C) Enqueue
Explanation: 1. Push, pop and return-top all work directly on a single stack stored in the one array. 2. Enqueue (insert at the rear of a queue) needs the queue's elements to be kept in order while new items are added at the other end. 3. Implementing a queue with stacks normally requires a second stack/array to reverse the order of elements. 4. Since no extra memory is available, enqueue cannot be implemented correctly.
Q272.Medium
Compared with a normal (dense) matrix, which of the following is a disadvantage of using a sparse matrix representation?
  1. It occupies more memory space
  2. It slows down computation on non-zero elements
  3. It cannot be compressed easily
  4. The algorithms become more complex
Show answer & explanation
Answer: (D) The algorithms become more complex
Explanation: 1. A sparse matrix stores mostly zeros, so only non-zero elements are kept, which saves memory. 2. Because zeros are skipped, it is easily compressible and computations on non-zero values are faster. 3. However, the code must first locate the indices of non-zero elements and avoid the zero positions during computation. 4. This extra bookkeeping makes the algorithms more complex, which is the disadvantage.
Q273.Medium
The function below is meant to reverse a singly linked list. One statement is missing at the end of the function.

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

/* head_ref is a double pointer pointing to the head pointer of the 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*/
}

Which statement should replace /*ADD A STATEMENT HERE*/ so that the list is correctly reversed?
  1. *head_ref = prev;
  2. *head_ref = current;
  3. *head_ref = next;
  4. *head_ref = NULL;
Show answer & explanation
Answer: (A) *head_ref = prev;
Explanation: 1. In the loop, prev always trails one node behind current and ends up pointing to the last node of the original list. 2. When the loop ends, current is NULL and next is NULL, but prev points to the new first node (old last node). 3. The head pointer must now point to this new first node, so we set *head_ref = prev. 4. Setting it to current or next would make the head NULL, and NULL would lose the list entirely.
Q274.Medium
What does the following code do?
public void addNode(Node node)
{
  if(count == 0)
    head = node;
  else
  {
    Node temp, cur;
    for(cur = head; (temp = cur.getNext()) != null; cur = temp);
    cur.setNext(node);
  }
  count++;
}
  1. Inserts a node at the beginning of the list
  2. Deletes a node at the beginning of the list
  3. Inserts a node at the end of the list
  4. Deletes a node at the end of the list
Show answer & explanation
Answer: (C) Inserts a node at the end of the list
Explanation: 1) If the list is empty (count == 0), the new node becomes the head. 2) Otherwise the for loop moves cur forward until cur.getNext() is null, i.e. cur stops at the last node. 3) Then cur.setNext(node) attaches the new node after the last node. 4) So the node is inserted at the end of the list.
Q275.Medium
A singly linked list (with only forward pointers) is NOT suitable for implementing which of the following?
  1. Insertion sort
  2. Radix sort
  3. Polynomial manipulation
  4. Binary search
Show answer & explanation
Answer: (D) Binary search
Explanation: 1) Binary search needs to jump to the middle element quickly, i.e., random access by index. 2) A singly linked list only allows sequential traversal from the head, so reaching the middle costs O(n). 3) Hence binary search on a linked list degenerates to O(n) per step, making it unsuitable. 4) Insertion sort, radix sort (with buckets) and polynomial manipulation can all be done with linked lists.
Q276.Medium
A singly linked list is implemented with the class below. Which method correctly deletes the LAST node of the list and returns it?
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 Node getNext() { return next; }
  public Object getEle() { return ele; }
}
class SLL {
  Node head;
  int size;
  SLL() { size = 0; }
}
  1. public Node removeLast() { if (size == 0) return null; Node cur = head, temp = null; while (cur.getNext() != null) { temp = cur; cur = cur.getNext(); } if (temp != null) temp.setNext(null); else head = null; size--; return cur; }
  2. public void removeLast() { if (size == 0) return null; Node cur = head, temp = null; while (cur != null) { temp = cur; cur = cur.getNext(); } temp.setNext(null); return cur; }
  3. public void removeLast() { if (size == 0) return null; Node cur = head, temp = null; while (cur != null) { cur = cur.getNext(); temp = cur; } temp.setNext(null); return cur; }
  4. public void removeLast() { if (size == 0) return null; Node cur = head, temp = null; while (cur.getNext() != null) { cur = cur.getNext(); temp = cur; } temp.setNext(null); return cur; }
Show answer & explanation
Answer: (A) public Node removeLast() { if (size == 0) return null; Node cur = head, temp = null; while (cur.getNext() != null) { temp = cur; cur = cur.getNext(); } if (temp != null) temp.setNext(null); else head = null; size--; return cur; }
Explanation: 1. To delete the last node we must reach it, so we need two references: 'cur' walks to the end and 'temp' trails one node behind. 2. The loop must stop when cur.getNext() == null, i.e. cur is the last node. 3. After the loop, temp is the second-last node; set temp.setNext(null) so the last node is detached. 4. If the list had only one node, temp stays null, so head must be set to null. 5. Decrease size and return cur (the removed node). Option (a) does exactly this; the others use wrong loop conditions or wrong return types.
Q277.Medium
Ravi is given only a pointer to a node P in a singly linked list of students' names. The pointer to the head node is NOT given. Can Ravi delete node P from the list?
  1. Yes, but only if P is not the last node
  2. Yes, but only if the list has an even number of nodes
  3. Yes, but only if the list has an odd number of nodes
  4. Yes, but only if P is not the first node
Show answer & explanation
Answer: (A) Yes, but only if P is not the last node
Explanation: 1) With only a pointer to P, the previous node cannot be reached, so the usual deletion is impossible. 2) Instead, copy the data of P's next node into P, then delete the next node: temp = P->next; P->data = temp->data; P->next = temp->next; free(temp). 3) This needs P->next to exist, so it fails when P is the last node. Hence deletion is possible only if P is not the last node.
Q278.Medium
Which method correctly deletes the node at a given position pos (0-based) in a singly linked list of size 'size' with head pointer 'head'?
  1. 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--; }
  2. 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--; }
  3. 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--; }
  4. 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--; }
Show answer & explanation
Answer: (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--; }
Explanation: 1. Handle edge cases: clamp pos, return if list empty. 2. If pos==0, move head to head.getNext(). 3. Otherwise we need the node just before position pos, so start temp=head and advance pos-1 times (loop i=1; i<pos). 4. Then temp.setNext(temp.getNext().getNext()) skips the node at pos, deleting it. 5. Option B only removes the link without skipping the node; Option C advances two nodes at a time; Option D advances one node too far (i=0 to pos-1).
Q279.Medium
A singly linked list is given with pointers to its first node (head) and its last node (tail). Which of the following operations depends on the length of the linked list?
  1. Remove the first node
  2. Insert a new node as the first node
  3. Remove the last node of the list
  4. Append a new node at the end of the list
Show answer & explanation
Answer: (C) Remove the last node of the list
Explanation: 1. Removing the first node only needs changing head to head.next: O(1), no length needed. 2. Inserting at the front creates a node pointing to head and updates head: O(1). 3. Appending at the end uses the tail pointer to link the new node and update tail: O(1). 4. Removing the last node needs the node just before the tail, which can only be found by traversing from head, so it depends on the list length.
Q280.Medium
Meera has a random singly linked list and wants to sort it with the minimum possible worst-case time complexity. Which sorting algorithm should she use?
  1. Insertion Sort
  2. Quick Sort
  3. Heap Sort
  4. Merge Sort
Show answer & explanation
Answer: (D) Merge Sort
Explanation: 1) Linked lists allow fast sequential access but slow random access. 2) Heap Sort needs random access, so it is impractical on a linked list. 3) Quick Sort performs poorly on linked lists due to slow random access. 4) Insertion Sort works but takes O(n^2) in the worst case. 5) Merge Sort works naturally with linked lists (splitting and merging by pointers) and runs in O(n log n) worst case. So Merge Sort is the best choice.
Q281.Medium
Ravi wants to join (concatenate) two lists in O(1) time. Which variation of the linked list makes this possible in constant time?
  1. Singly linked list
  2. Doubly linked list
  3. Circular doubly linked list
  4. Array implementation of list
Show answer & explanation
Answer: (C) Circular doubly linked list
Explanation: 1) In a circular doubly linked list, the last node's next points back to the first node, and the first node's prev points to the last node. 2) To concatenate two such lists, we only re-link the last node of the first list to the first node of the second, and the last node of the second to the first of the first. 3) This is a fixed number of pointer changes, so it takes O(1) time regardless of list size. 4) Plain singly/doubly lists need a tail pointer and still lack the circular back-links, so circular doubly linked list is the clean O(1) choice.
Q282.Medium
In C, a node for a singly linked list is defined as:
struct node {
    int data;
    struct node *next;
};
typedef struct node NODE;
NODE *ptr;
Which of the following C statements correctly allocates memory for a new node and assigns its address to ptr?
  1. ptr = (NODE*)malloc(sizeof(NODE));
  2. ptr = (NODE*)malloc(NODE);
  3. ptr = (NODE*)malloc(sizeof(NODE*));
  4. ptr = (NODE)malloc(sizeof(NODE));
Show answer & explanation
Answer: (A) ptr = (NODE*)malloc(sizeof(NODE));
Explanation: 1) malloc needs the number of bytes to allocate, so we pass sizeof(NODE) (size of one full node). 2) malloc returns void*, so we cast it to NODE*. 3) Option 2 passes a type name instead of a size, which is invalid. 4) Option 3 allocates only the size of a pointer, not a whole node. 5) Option 4 casts the result to NODE (not a pointer), which is wrong. Hence option 1 is correct.
Q283.MediumAnswer under review
What is the postfix form of the expression (P + Q) * (R * S - T) * U / V?
  1. PQ+ RS*T- UV/*
  2. PQ+ RS*T- *U*V/
  3. PQ+ RS*T- *U* V/
  4. PQ+ RST* - *U*V/
Show answer & explanation
Answer: (B) PQ+ RS*T- *U*V/
Explanation: 1. Convert (P+Q) → PQ+. 2. Convert (R*S - T): R*S → RS*, then subtract T → RS*T-. 3. Multiply the two: PQ+ RS*T- *. 4. Multiply by U: PQ+ RS*T- * U *. 5. Divide by V: PQ+ RS*T- * U * V /. So postfix is PQ+ RS*T- *U*V/.
Q284.Medium
Convert the infix expression (P + Q ⋀ R)/(S – T) + U into its equivalent postfix expression.
  1. P Q R ⋀ + S T – / U +
  2. P Q R + ⋀ S T – / U +
  3. P Q R ⋀ + S T / – U +
  4. P Q R S T + ⋀ / – U +
Show answer & explanation
Answer: (A) P Q R ⋀ + S T – / U +
Explanation: 1) Q ⋀ R becomes QR⋀. 2) P + QR⋀ becomes PQR⋀+. 3) S – T becomes ST–. 4) Divide: PQR⋀+ ST– /. 5) Add U: PQR⋀+ST–/U+.
Q285.Medium
Convert the following infix expression to postfix form using a stack: a + b * c + (d * e + f) * g. Assume the usual operator precedence and that the expression is legal.
  1. abc*+de*f+g*+
  2. abc*+de*f+g+
  3. abc+*de*f+g*+
  4. abc*+de*fg+*+
Show answer & explanation
Answer: (A) abc*+de*f+g*+
Explanation: 1) b*c becomes bc*. 2) a + bc* becomes abc*+. 3) Inside brackets, d*e becomes de*, then + f gives de*f+. 4) Multiply that bracket result by g: de*f+g*. 5) Combine: abc*+ + de*f+g* + final + = abc*+de*f+g*+.
Q286.Medium
What is the prefix form of the expression A - B / (C * D ^ E)?
  1. -A/B*C^DE
  2. -/*^ACBDE
  3. -ABCD*^DE
  4. -A/BC*^DE
Show answer & explanation
Answer: (A) -A/B*C^DE
Explanation: 1. Precedence: ^ highest, then * and /, then -. 2. Innermost: D^E -> ^DE. 3. Then C * (^DE) -> *C^DE. 4. Then B / (*C^DE) -> /B*C^DE. 5. Finally A - (/B*C^DE) -> -A/B*C^DE. So the prefix form is -A/B*C^DE.
Q287.Medium
Using the standard algorithm that checks whether a sequence of parentheses is balanced (push on '(', pop on ')'), what is the maximum number of parentheses present on the stack at any one time while analyzing the sequence: ((())(()))?
  1. 1
  2. 2
  3. 3
  4. 4 or more
Show answer & explanation
Answer: (C) 3
Explanation: 1. Read '(' -> push, stack size 1. 2. Read '(' -> push, size 2. 3. Read '(' -> push, size 3 (maximum so far). 4. Read ')' -> pop, size 2. 5. Read ')' -> pop, size 1. 6. Read '(' -> push, size 2. 7. Read '(' -> push, size 3. 8. Read ')' -> pop, size 2. 9. Read ')' -> pop, size 1. 10. Read ')' -> pop, size 0. The maximum stack size reached is 3.
Q288.Medium
Consider the usual stack algorithm for checking whether a sequence of parentheses is balanced. Suppose the sequence contains 3 left parentheses and 4 right parentheses (in some order). What is the maximum number of parentheses that can appear on the stack at any one time during the computation?
  1. 1
  2. 2
  3. 3
  4. 4 or more
Show answer & explanation
Answer: (C) 3
Explanation: Each left parenthesis is pushed onto the stack; each right parenthesis pops one. Only 3 left parentheses exist in the whole sequence, so at most 3 items can ever be on the stack. This maximum is reached if all 3 left parentheses come before any right parenthesis. Hence the maximum stack size is 3.
Q289.Medium
The prefix form of the infix expression (m + n) – (s * u) is?
  1. + mn – *su
  2. – +mns * u
  3. – +mn * su
  4. – + * mnsu
Show answer & explanation
Answer: (C) – +mn * su
Explanation: The expression is ((m+n) – (s*u)). Prefix of (m+n) is +mn. Prefix of (s*u) is *su. The main operator is '–', so combine: – +mn * su. Thus the prefix form is – +mn * su.
Q290.Medium
What is the value of the postfix expression 8 2 3 5 + – * ?
  1. -48
  2. 48
  3. 64
  4. -32
Show answer & explanation
Answer: (A) -48
Explanation: Scan left to right and use a stack. Push 8, 2, 3, 5. '+' pops 5 and 3 → 3+5 = 8; push 8. Stack: 8, 2, 8. '–' pops 8 and 2 → 2–8 = –6; push –6. Stack: 8, –6. '*' pops –6 and 8 → 8×(–6) = –48. So the value is –48.
Q291.Medium
Which of the following statements is NOT correct about a Singly Linked List (SLL) and a Doubly Linked List (DLL)?
  1. Insertion and deletion at a known position is O(n) in SLL but O(1) in DLL
  2. An SLL uses less memory per node than a DLL
  3. A DLL can be traversed in both directions while an SLL only in one direction
  4. The number of pointer fields in an SLL node is more than in a DLL node
Show answer & explanation
Answer: (D) The number of pointer fields in an SLL node is more than in a DLL node
Explanation: 1. An SLL node has data plus one next pointer (1 pointer field). 2. A DLL node has data plus next and previous pointers (2 pointer fields). 3. So the SLL has fewer pointer fields, not more, making option 4 false. 4. The other statements are true: known-position insert/delete needs traversal in SLL (O(n)) but O(1) in DLL, SLL uses less memory, and DLL supports two-way traversal.
Q292.MediumAnswer under review
Which of the following are advantages of a suffix array over a suffix tree?
I. Lesser space requirement
II. Improved cache locality
III. Easy construction in linear time
  1. Only I
  2. All I, II and III
  3. Only I and III
  4. Only II and III
Show answer & explanation
Answer: (B) All I, II and III
Explanation: 1. A suffix array stores only integer indices, so it needs much less space than a suffix tree (advantage I). 2. Its compact contiguous layout gives better cache locality during searches (advantage II). 3. Simple algorithms (e.g., SA-IS, DC3) build suffix arrays in linear time (advantage III). 4. Therefore all three statements are advantages.
Q293.Medium
Consider the following method of a SparseArray class, where N is the number of columns and sparse_array is an array of row objects each having a fetch(int) method:

public Object function(int row_index, int col_index)
{
    if (row_index < 0 || col_index > N)
    {
        System.out.println("column index out of bounds");
        return null;
    }
    return (sparse_array[row_index].fetch(col_index));
}

What is the functionality of this method?
  1. It stores an element at the specified position
  2. It retrieves the element at the specified position
  3. It modifies the element at the specified position
  4. It removes the element at the specified position
Show answer & explanation
Answer: (B) It retrieves the element at the specified position
Explanation: 1. The method first validates the row and column indices. 2. It then calls sparse_array[row_index].fetch(col_index). 3. The fetch method reads and returns the value stored at that column of the given row. 4. No assignment or deletion occurs, so the method only gets (retrieves) the element at the specified position.
Q294.MediumAnswer under review
In which of the following situations is a dynamic array NOT preferred?
  1. When the number of elements to be stored is not known in advance
  2. When the array size keeps changing after a few iterations
  3. When reallocating memory is very expensive
  4. When the array stores only a small number of elements
Show answer & explanation
Answer: (D) When the array stores only a small number of elements
Explanation: 1. Dynamic arrays help when the size is unknown, when the size changes over time, or when reallocation cost matters — these are good use cases. 2. If only a few elements are stored, the physical size is small and shrinking/reallocating it takes extra time with little benefit. 3. In that case a plain (static) array is simpler and faster. 4. Hence dynamic arrays are not preferred when the array holds a small number of elements.
Q295.Medium
Which code snippet correctly performs matrix multiplication of two n×n matrices a and b, storing the result in matrix c?
  1. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } }
  2. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { c[i][j] = c[i][j] * a[i][k] * b[k][j]; } } }
  3. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { c[i][j] = c[i][j] + a[i][k] + b[k][j]; } } }
  4. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { c[i][j] = c[i][j] + a[i][j] + b[k][j]; } } }
Show answer & explanation
Answer: (A) for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } }
Explanation: 1. Matrix multiplication: c[i][j] = sum over k of a[i][k] * b[k][j]. 2. The correct snippet uses three nested loops: i over rows of a, j over columns of b, k for the sum. 3. It accumulates the product a[i][k] * b[k][j] into c[i][j]. 4. Other options use multiplication instead of addition, or add instead of multiply, or use wrong indices.
Q296.Medium
A suffix array of a string can be constructed by carrying out which kind of traversal on its suffix tree?
  1. breadth-first traversal
  2. level-order traversal
  3. depth-first traversal
  4. either breadth-first or level-order traversal
Show answer & explanation
Answer: (C) depth-first traversal
Explanation: 1. A suffix tree stores all suffixes of the string as keys, with their starting positions as values. 2. The leaves of the suffix tree, read left to right, give the suffixes in sorted order. 3. A depth-first traversal visits the leaves in exactly this left-to-right order. 4. Recording the position stored at each leaf during a DFS therefore yields the suffix array.
Q297.Medium
A 2-D array B has 3 rows and 4 columns and is stored in column-major order (column by column). If the base address is 2000 and each element occupies 4 bytes, what is the address of the element B[2][3] (0-indexed row 2, column 3)?
  1. 2044
  2. 2040
  3. 2036
  4. 2048
Show answer & explanation
Answer: (A) 2044
Explanation: Step 1: In column-major order, elements of a column are stored consecutively, so the offset = (column index × number of rows + row index) × element size. Step 2: Here column = 3, rows = 3, row = 2, size = 4 bytes. Step 3: Offset = (3 × 3 + 2) × 4 = (9 + 2) × 4 = 11 × 4 = 44. Step 4: Address = base + offset = 2000 + 44 = 2044.
Q298.Medium
In string processing, a suffix tree for a string can be built in linear time using a suffix array together with which other structure?
  1. Hash trie
  2. LCP array
  3. Balanced binary search tree
  4. Adjacency matrix
Show answer & explanation
Answer: (B) LCP array
Explanation: Step 1: A suffix array lists all suffixes of a string in sorted order. Step 2: The LCP (Longest Common Prefix) array stores the length of the longest common prefix between consecutive suffixes in that sorted order. Step 3: Given the string, its suffix array and its LCP array, the suffix tree can be constructed in O(n) linear time. Step 4: Hence the required companion structure is the LCP array.
Q299.Medium
A suffix array is built for a text of length n. Using this suffix array, a pattern P of length m is to be located in the text. What is the time required to find the occurrences of P?
  1. O(nm)
  2. O(n^2)
  3. O(m n log n)
  4. O(m log n)
Show answer & explanation
Answer: (D) O(m log n)
Explanation: Binary search over the suffix array takes O(log n) comparisons. Each comparison of the pattern with a suffix may check up to m characters. So total time = O(m log n).
Q300.Medium
A sorted array holds the roll numbers of 40 students of a Mumbai class in ascending order. What is the worst case time complexity of inserting a new roll number into this sorted array?
  1. O(n log n)
  2. O(log n)
  3. O(n)
  4. O(n^2)
Show answer & explanation
Answer: (C) O(n)
Explanation: In the worst case the new element must be placed at the front. Then all n existing elements have to be shifted one place to the right. Shifting n elements takes O(n) time. So the worst case complexity is O(n).
1234

Get In Touch

INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India

contact@intmatedtech.com

TestMyIndia All India Rank