Skip to content
GATEiit

GATE DA · Programming, Data Structures and Algorithms

Basic data structures: stacks, queues, linked lists, trees and hash tables

Stacks, queues, linked lists, binary trees and BSTs, and hash tables: their operations and costs, traversals, collision handling, and the tracing questions GATE asks on each.

Before you start

  • Python lists and dictionaries →

    A Python list works as a stack and a dict is a hash table; questions often use Python code.

  • Big-O notation

    Every comparison between structures is stated as the cost of an operation.

  • Recursion

    Tree traversals and BST insertion are naturally recursive.

This topic comes before: Basic graph algorithms: traversals and shortest path, File organization and indexing, Introduction to graph theory, Search: informed, uninformed and adversarial

Concept notes

1. Stacks and queues

A stack is LIFO (last in, first out): push adds on top, pop removes the top, peek reads it. A queue is FIFO (first in, first out): enqueue at the rear, dequeue from the front. All these operations take O(1).

Use Structure
Function calls and recursion Stack (call stack)
Balanced brackets, undo Stack
Evaluating postfix expressions Stack
Breadth-first search, printer jobs Queue
Depth-first search (iterative) Stack

Postfix evaluation: scan left to right; push operands; on an operator pop the top two (b first, then a), push a op b. The order matters for - and /.

Circular queue in an array of size n: indices wrap with % n. With front at the first item and rear at the next free slot, the queue is empty when front == rear and full when (rear + 1) % n == front, so it holds at most n−1 items. The number of items is (rear−front+n) mod n.

In Python, a list is a stack (append, pop). For a queue use collections.deque (append, popleft), because list.pop(0) shifts every element and costs O(n).

A queue can be built from two stacks (amortised O(1) per operation), and a stack from two queues.

2. Linked lists

A singly linked list is a chain of nodes, each holding a value and a pointer next; the last node points to None. A doubly linked list also stores prev. In a circular list the last node points back to the first.

Operation Array Singly linked list
Access k-th item O(1) O(k)
Insert/delete at head O(n) O(1)
Insert after a given node O(n) O(1)
Delete a given node O(n) O(n) (need predecessor); O(1) if doubly linked
Search O(n), or O(log⁡n) if sorted O(n) even if sorted

Binary search does not help on a linked list because reaching the middle already costs O(n).

Keeping a tail pointer makes insertion at the end O(1), but deleting the last node of a singly linked list is still O(n), since the new tail must be found.

Standard tricks:

  • Reverse in place: walk with prev, curr, nxt; set curr.next = prev and advance. O(n) time, O(1) space.
  • Middle node: move slow one step and fast two steps; when fast reaches the end, slow is at the middle.
  • Cycle detection (Floyd): the same two pointers meet inside the loop if and only if there is a cycle.

3. Binary trees and traversals

A binary tree node has at most two children. The depth of a node is its number of edges from the root; the height of the tree is the largest depth (a single node has height 0). Some questions count levels instead of edges, so read the definition given.

Key counts for a binary tree of height h with n nodes:

  • At most 2i nodes at depth i, and at most 2h+1−1 nodes in all.
  • Minimum height is ⌈log⁡2(n+1)⌉−1; maximum height is n−1 (a chain).
  • If n0 is the number of leaves and n2 the number of nodes with two children, then n0=n2+1.

Traversals (each O(n)):

Name Order
Preorder root, left, right
Inorder left, root, right
Postorder left, right, root
Level order level by level, using a queue

Rebuilding a tree: inorder plus preorder (or plus postorder) fixes a unique binary tree. The first preorder item (last postorder item) is the root; find it in the inorder list to split the left and right subtrees, then recurse. Preorder plus postorder alone does not fix a unique tree in general.

PQRSTUPre: P Q S T R U In: S Q T P U R Post: S T Q U R P
A binary tree and its three depth-first traversals

4. Binary search trees

A binary search tree (BST) is a binary tree where every key in a node's left subtree is smaller than the node's key, and every key in the right subtree is larger.

  • Search/insert: start at the root, go left if the key is smaller and right if larger. Insertion adds a new leaf.
  • Inorder traversal of a BST gives the keys in sorted order. So the inorder sequence of any BST is just the sorted keys.
  • Minimum is the leftmost node; maximum is the rightmost.
  • Delete: a leaf is removed; a node with one child is replaced by that child; a node with two children takes its inorder successor (smallest key in the right subtree) or inorder predecessor, which is then deleted from its place.

All operations cost O(h) where h is the height. A tree built from random insertions has expected height O(log⁡n), but inserting keys in sorted order gives a chain of height n−1, so the worst case is O(n).

The shape of a BST depends on the insertion order: the first key is always the root. Given a preorder sequence of a BST, the tree is unique, because the inorder sequence is known (sorted).

The number of structurally different binary trees on n nodes, and of BSTs on n distinct keys, is the Catalan number 1n+1(2nn): 1, 2, 5, 14 for n=1 to 4.

5. Hash tables

A hash table stores keys in an array of m slots, using a hash function h(k) to pick a slot, for example h(k)=k mod m. Two keys with the same slot collide. The load factor is α=n/m.

Separate chaining: each slot holds a linked list. Under simple uniform hashing a chain has α keys on average, and a search takes Θ(1+α) expected time. α may exceed 1.

Open addressing: all keys sit in the array (α≤1). On a collision, probe a sequence of slots:

Method i-th probe
Linear probing (h(k)+i) mod m
Quadratic probing (h(k)+c1i+c2i2) mod m
Double hashing (h1(k)+i h2(k)) mod m

Linear probing suffers primary clustering: runs of filled slots grow and slow down later inserts. Quadratic probing has milder secondary clustering; double hashing avoids both.

With uniform hashing, an unsuccessful search in open addressing takes at most 11−α expected probes. Deleting from open addressing needs a tombstone marker, otherwise later searches stop early at the emptied slot.

Python's dict and set are hash tables: average O(1) lookup, insert and delete.

012345678919432313273799h(k) = k mod 10, linear probing; 19 collides at 9 and wraps to 0
Inserting 43, 23, 13, 27, 37, 99, 19 with linear probing

Formulas to remember

Maximum nodes of a binary treeHeight h counted in edges
n≤2h+1−1
Minimum height
hmin⁡=⌈log⁡2(n+1)⌉−1
Leaves vs two-child nodesAny non-empty binary tree
n0=n2+1
Number of binary trees / BSTs on n keys
Cn=1n+1(2nn)
Load factor
α=nm
Expected unsuccessful search, open addressingUniform hashing, α<1
≤11−α
Items in a circular queue
(rear−front+n) mod n

Common mistakes

  • Popping postfix operands in the wrong order: the first pop is the right operand, so a b - means a−b.
  • Mixing up height in edges and height in levels; check which one the question defines.
  • Thinking binary search speeds up a sorted linked list; random access is what makes it fast.
  • Forgetting that linear probing wraps around from the last slot to slot 0.
  • Assuming preorder and postorder together fix a unique binary tree; you need the inorder sequence.
  • Using list.pop(0) as a queue in Python, which is O(n) per dequeue.

Worked examples

Try each step yourself, then reveal the working.

Example 1: Evaluating a postfix expression with a stack

numerical

Evaluate the postfix expression 8 2 5 * + 1 3 2 * + 4 - /.

  1. Step 1: Process up to the first +.

    Try it on paper first.

Example 2: Linear probing in a table of size 10

numerical

Insert 43, 23, 13, 27, 37, 99, 19 in that order into an empty table of size 10 with h(k)=k mod 10 and linear probing. Where does each key go, and how many probes does 19 need?

  1. Step 1: Place the keys that hash to 3.

    Try it on paper first.

Example 3: Postorder from preorder and inorder

numerical

A binary tree has preorder P Q S T R U and inorder S Q T P U R. Find its postorder.

  1. Step 1: Find the root and split the inorder list.

    Try it on paper first.

Example 4: BST height and search cost

numerical

Insert 50, 30, 70, 20, 40, 60, 80, 35 into an empty BST. Find the height (in edges) and the number of key comparisons to find 35.

  1. Step 1: Insert the first seven keys.

    Try it on paper first.

Previous year questions

9 official GATE DA questions on this topic, newest first.

Practise these 9 PYQs →

Topic test

10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE DA syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.