Sub topic 18
GATE Problem Patterns and a Structure Comparison Table
This chapter assumes you have read the earlier chapters on arrays, linked lists, stacks, queues, and heaps. You should be comfortable with Big-O notation, pointer assignment, and 0-based array indexing. The goal is to turn that material into a routine for exam questions. You will first see a table of costs, then the question patterns that recur, each with a worked trace.
The comparison table
Most multiple-choice questions on these structures reduce to one question: what does this operation cost on this structure? Learn the table below well enough to rebuild it from the memory layouts.
| Structure | Access by position | Search | Insert | Delete | Main weakness |
|---|---|---|---|---|---|
| Array | O(1) | O(n), or O(log n) if sorted | O(1) at the end, O(n) in the middle | O(1) at the end, O(n) in the middle | Fixed size, shifting |
| Singly linked list | O(n) | O(n) | O(1) at the head or after a known node, O(n) at the tail without a tail pointer | O(1) at the head, O(n) for a given node (needs its predecessor) | No random access, no backward step |
| Stack | Top only, O(1) | O(n) | push O(1) | pop O(1) | Only one end is visible |
| Queue (circular array or list with tail pointer) | Front only, O(1) | O(n) | enqueue O(1) | dequeue O(1) | Only two ends are visible |
| Binary heap | Min or max only, O(1) | O(n) | O(log n) | extract O(log n) | Not sorted, so search is linear |
Two entries cause most wrong answers. Deleting a given node of a singly linked list is O(n) because you must find the previous node. Searching a heap is O(n) because the heap property orders only parent against child.
Choosing a structure
Many questions describe a workload and ask for the best structure. Work from the dominant operation.
Pattern 1: circular queue indices
Questions give n, front, and rear, then ask for the element count, the next insert position, or whether the queue is full. Check which convention the question uses before you compute anything.
- Wasted-slot convention:
frontis the first element andrearis the next free slot. The queue is empty whenfront == rearand full when(rear + 1) % n == front. Capacity isn - 1. The count is(rear - front + n) % n. - Count-based convention (the chapter's code): the position of the next insert is
(front + size) % n. The queue is full whensize == n, so allnslots are usable.
Adding a variable like size removes the ambiguity between full and empty. A queue with only front and rear cannot tell the two states apart without wasting a slot.
Pattern 2: postfix evaluation and conversion
Postfix evaluation scans left to right. It pushes operands and, on an operator, pops the right operand first and then the left. Operand order matters for - and /.
def eval_postfix(tokens):
ops = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a // b,
}
stack = []
for t in tokens:
if t in ops:
b = stack.pop()
a = stack.pop()
stack.append(ops[t](a, b))
else:
stack.append(int(t))
return stack.pop()
print(eval_postfix("5 6 2 + * 12 4 / -".split()))This prints 37. The stack holds 5, then 5 6, then 5 6 2, then 5 8, then 40, then 40 12, then 40 12 4, then 40 3, and finally 37.
For infix to postfix, the operator stack decides the output order. Pop while the stack top has higher precedence than the incoming operator, or equal precedence and the incoming operator is left-associative. The exponent operator ^ is right-associative, so equal precedence does not pop. For example, A+B*C-D becomes ABC*+D-. Typical questions ask for the maximum operator stack depth or the final string.
Pattern 3: linked list pointer tracing
Tracing questions give a short loop that rewires next fields. Draw the nodes and update the pointers in the order the code does. The usual families are:
- Reversal, which needs three pointers (
prev,head,nxt) and runs in O(n) time and O(1) space. - Middle node, found with a slow pointer that moves one step and a fast pointer that moves two. When the fast pointer reaches the end, the slow pointer is at the middle.
- Cycle detection, where the same two pointers meet inside a cycle.
- Insertion at the tail of a circular list. If you keep only a tail pointer, both the head (
tail.next) and the tail are reachable in O(1). A singly linked list with only a head pointer needs O(n) to append.
Pattern 4: heap index arithmetic and traces
With 0-based indexing, the parent of i is (i - 1) // 2 and the children are 2i + 1 and 2i + 2. With 1-based indexing they are i // 2, 2i, and 2i + 1. Read the question's indexing before you apply either formula. In a heap of n nodes, the leaves occupy indices n // 2 through n - 1 (0-based). That fact answers questions such as where the maximum of a min-heap can be.
The next script builds a min-heap bottom-up and counts swaps.
def sift_down(a, i, n):
swaps = 0
while True:
l = 2 * i + 1
r = l + 1
smallest = i
if l < n and a[l] < a[smallest]:
smallest = l
if r < n and a[r] < a[smallest]:
smallest = r
if smallest == i:
return swaps
a[i], a[smallest] = a[smallest], a[i]
swaps += 1
i = smallest
def build_min_heap(a):
n = len(a)
swaps = 0
for i in range(n // 2 - 1, -1, -1):
swaps += sift_down(a, i, n)
return swaps
data = [9, 7, 5, 3, 1]
print(build_min_heap(data), data)The output is 3 [1, 3, 5, 9, 7]. Index 1 swaps with index 4. Then index 0 swaps with index 1, and the moved 9 swaps again with index 3.
Building bottom-up is O(n) because most nodes sit near the leaves and sift down only a short distance. Roughly n / 2^(h+1) nodes have height h, and the sum of h times that count converges to O(n). Inserting n keys one at a time costs O(n log n) in the worst case. Heap sort is the O(n) build followed by n - 1 extractions of O(log n) each, so it is O(n log n) in every case. Sorting in ascending order uses a max-heap, because each extracted maximum is placed at the end of the array.
Pattern 5: stack and queue conversions
These questions ask you to count elementary operations.
- A queue from two stacks: enqueue pushes onto the input stack, and dequeue pops from the output stack. When the output stack is empty, it first moves every element from the input stack. A single dequeue is O(n) in the worst case, but the amortized cost is O(1) because each element moves at most once.
- A stack from two queues, or from one queue: make push expensive by rotating
n - 1elements to the back after each insert. Then pop is O(1) and push is O(n).
A routine for exam questions
- Identify the structure and its convention (indexing base, empty and full test, pointer names).
- Name the operation and recall its cost from the table.
- For traces, draw the structure and update it step by step. Do not compute in your head.
- Check the boundaries: an empty structure, one element, a full queue, and a wrap-around index.
Exercise
A circular queue uses the wasted-slot convention with n = 6. The front index is 4 and the rear index (next free slot) is 1. How many elements does it hold, and how many more can be inserted before it is full?
Show answer
The count is (1 - 4 + 6) % 6 = 3, stored at indices 4, 5, and 0. Capacity is n - 1 = 5, so 2 more elements fit.
Exercise
A max-heap stores 15 distinct keys in an array with 0-based indexing. In which positions can the minimum key be, and how many positions is that?
Show answer
The minimum must be a leaf, because every internal node is greater than its children. Leaves occupy indices 15 // 2 = 7 through 14, which is 8 positions.