Data Structures & Algorithms
डेटा संरचनाएँ
Unit overview: the topics below, with their summaries, are the syllabus for this unit. The comprehensive note further down covers every topic in full — explanations, definitions, worked examples, tables, exam points and practice questions — and the short revision note after it is only a quick recap. Standalone one-topic learning pages are not built yet — every topic on this page is covered in the notes and the practice questions below, and each topic card links to those sections.
Premium chapters for this unit
Arrays, stacks, queues, linked lists → premium chapter · free preview · ~20 min · 4 practice questions
Trees, heaps, graphs & traversal → premium chapter · free preview · ~26 min · 4 practice questions
Sorting, searching & complexity → premium chapter · free preview · ~24 min · 4 practice questions
Topics checklist — with weightage (platform estimate from past-question frequency, not an NTA guarantee)
Arrays, stacks, queues, linked lists
High weightageOperations, complexity, real uses (undo = stack, queue = ticket line).
Trees, heaps, graphs & traversal
High weightageBST, AVL, BFS/DFS, Dijkstra, MST.
Sorting, searching & complexity
High weightageQuick/merge sort, Big-O, divide & conquer, DP basics.
Comprehensive unit note · ~23 min read
Data structures and algorithms form the engineering core of computer science. A data structure is a way of organising data so that operations on it are efficient, and an algorithm is a precise, terminating procedure for solving a problem. The choice of structure decides the cost of every operation that follows: the same search that scans a list in linear time can finish in logarithmic time on a balanced tree, and the same scheduling problem that is awkward with an array becomes natural with a queue or a heap. UGC NET tests this link between structure, algorithm and cost again and again, so memorising names without complexities, invariants and failure cases is not enough. This unit builds that link in four stages. It starts with linear structures, where order is the organising idea: arrays give direct access by index, stacks enforce last-in first-out access, queues enforce first-in first-out access, and linked lists trade direct access for cheap insertion and deletion. It then moves to hierarchical and network structures: trees, heaps and graphs, where traversal order, balance and shortest paths become the central questions. Sorting and searching then show how the same problem can be solved at very different costs, and why stability, in-place behaviour and average versus worst case matter. Finally, asymptotic analysis gives a language for comparing all of these without running a single program: Big-O, Theta and Omega, recurrences and the master theorem. Read this unit as a problem solver, not as a catalogue. For every structure ask four questions: what invariant does it maintain, what does each operation cost and why, what breaks when the invariant is violated, and which real problem makes this structure the natural choice.
Learning objectives
- Compare arrays, stacks, queues and linked lists by operation costs and choose the right linear structure for a given problem.
- Perform and analyse binary search tree, AVL rotation and heap operations, including their time complexities.
- Trace BFS, DFS, Dijkstra, Prim and Kruskal algorithms on small graphs and state their costs and preconditions.
- Compare sorting and searching algorithms by time, space, stability and best, average and worst cases.
- Analyse recurrences with the master theorem and classify growth with Big-O, Theta and Omega notation.
- Explain hash tables, collision resolution and load factor, and outline divide-and-conquer and dynamic-programming ideas.
Overview: Data Structures and Algorithms at a Glance
An abstract data type defines what operations are available, while a data structure defines how they are implemented. A stack, for example, is defined by push, pop and peek; it can be implemented with an array or a linked list, and the implementation changes the cost of overflow handling but not the last-in first-out rule. This distinction matters in examinations because a question may ask about the abstract behaviour, such as the output order of a queue, or about the implementation cost, such as the cost of inserting at the front of an array.
Two costs dominate analysis: time and space. Time is usually counted in elementary operations as a function of input size n, and space counts extra memory beyond the input. An algorithm that is fast but needs a second copy of the data may be rejected where memory is tight, and an in-place sort is therefore valued even when its worst case is worse than a method that needs auxiliary storage. Always check whether a stated complexity is best, average or worst case, and whether it counts comparisons, swaps, or total steps, because the same algorithm can carry different labels under different counting rules.
Arrays, stacks, queues, linked lists
An array stores elements in contiguous memory, so the address of element i is base plus i times element size, and access by index takes constant time. That strength is also its weakness: inserting or deleting in the middle shifts all later elements, which costs linear time, and a fixed-size array can overflow or waste space. A dynamic array grows by allocating a larger block and copying elements, so individual insertions are occasionally expensive but the amortised cost of appending is constant, because expensive doublings are rare. Searching an unsorted array is linear, while a sorted array supports binary search.
A stack allows insertion and deletion only at one end, called the top, giving last-in first-out order. Push adds an element, pop removes the top element, and peek reads it without removing it. Stack overflow occurs when pushing onto a full bounded stack, and underflow when popping from an empty one. Applications follow directly from the order: the call stack saves return addresses and local state, undo operations reverse the most recent action first, and expression evaluation uses stacks to handle operators and parentheses. To evaluate a postfix expression, scan left to right, push operands, and on meeting an operator pop two operands, apply the operator, and push the result. Infix to postfix conversion uses an operator stack together with precedence and associativity rules, with parentheses forcing subexpressions to be completed first.
A queue allows insertion at the rear and deletion at the front, giving first-in first-out order. Enqueue adds at the rear and dequeue removes from the front. A simple array queue wastes the space left by dequeued elements, so a circular queue wraps the rear and front indices around with modulo arithmetic: the next position is computed as (index plus 1) modulo capacity. A circular queue is full when the next rear position equals the front, and empty when front equals rear under the chosen convention, so one slot is often sacrificed or a separate count is kept to distinguish the two states. A deque allows insertion and deletion at both ends, and a priority queue orders removal by priority rather than arrival time, which is normally implemented with a heap. Queues appear in process scheduling, print spooling, buffering between producers and consumers, and breadth-first traversal.
A singly linked list is a chain of nodes, each holding data and a pointer to the next node, with the last node pointing to null. Insertion or deletion at a known node takes constant time once the node is located, because only pointers change, but reaching position i requires walking from the head, which costs linear time. A doubly linked list adds a previous pointer to each node, so deletion of a known node and backward traversal are easy, at the cost of extra memory and more pointer updates. A circular linked list links the last node back to the first, which suits round-robin scheduling. The classic examination traps are losing the rest of the list by overwriting a pointer before saving it, forgetting to update the head on insertion or deletion at the front, and creating a cycle by linking a node to itself.
Trees, heaps, graphs & traversal
A tree is a connected acyclic graph with a root, where every node except the root has exactly one parent and nodes with no children are leaves. The height of a tree is the number of edges on the longest root-to-leaf path, and a binary tree allows at most two children per node, conventionally called left and right. A full binary tree has either zero or two children at every node, a complete binary tree fills levels left to right except possibly the last, and a perfect binary tree has all leaves at the same depth. Traversals define visit order: preorder visits node, left subtree, right subtree; inorder visits left subtree, node, right subtree; postorder visits left subtree, right subtree, node; level order visits level by level using a queue. Inorder traversal of a binary search tree yields keys in sorted order, which is a favourite examination fact.
A binary search tree maintains the invariant that every key in the left subtree is smaller than the node key and every key in the right subtree is larger. Search, insertion and deletion walk down comparing keys, so each costs time proportional to height. In the worst case a degenerate tree that is really a chain costs linear time, while a balanced tree costs logarithmic time. Deleting a leaf removes it directly, deleting a node with one child replaces it by that child, and deleting a node with two children replaces it by its inorder successor or predecessor and then deletes that successor or predecessor. An AVL tree restores balance after insertion or deletion by maintaining a balance factor, the height of the left subtree minus the height of the right subtree, in the range minus one to plus one at every node. When the factor leaves this range, one of four rotations applies: left-left is fixed by a single right rotation, right-right by a single left rotation, left-right by a left rotation on the child followed by a right rotation on the node, and right-left by the mirror image. Rotations preserve the inorder sequence while changing heights, which is why they preserve the search-tree property.
A heap is a complete binary tree with the heap property: in a max-heap every parent is at least as large as its children, so the maximum sits at the root, and in a min-heap every parent is at most as large as its children. Heaps are stored in arrays without pointers: for a node at index i using zero-based indexing, its children are at 2i plus 1 and 2i plus 2, and its parent is at floor of (i minus 1) divided by 2. Insertion places the new element at the end and bubbles it up while it violates the heap property, and deletion of the root replaces the root with the last element and bubbles it down, both in logarithmic time. Building a heap by repeated insertion costs n log n, but the bottom-up heapify method costs linear time because most nodes are near the leaves and move only a short distance. Heap sort repeatedly extracts the root to obtain sorted order. Huffman coding builds an optimal prefix code by repeatedly merging the two least frequent symbols into a new node whose frequency is their sum, so frequent symbols get short codes and no code is a prefix of another, which guarantees unambiguous decoding.
A graph consists of vertices and edges, which may be directed or undirected and may carry weights. It is stored as an adjacency matrix, which answers edge existence in constant time but uses quadratic space, or as adjacency lists, which use space proportional to vertices plus edges and suit sparse graphs. Breadth-first search uses a queue, visits vertices in increasing distance from the source in an unweighted graph, and naturally finds shortest paths in edges. Depth-first search uses a stack or recursion, explores as far as possible along each branch before backtracking, and is the basis for cycle detection, connected components and topological sorting. Dijkstra algorithm finds shortest paths from a source when all edge weights are non-negative: it maintains tentative distances, repeatedly finalises the unfinalised vertex with the smallest tentative distance, and relaxes its outgoing edges. It fails with negative weights because a finalised vertex could later be improved through a negative edge. A minimum spanning tree connects all vertices with minimum total weight: Prim algorithm grows one tree by repeatedly adding the cheapest edge to a vertex outside the tree, while Kruskal sorts all edges and adds them unless they form a cycle, using a disjoint-set structure. Topological sort orders vertices of a directed acyclic graph so that every edge goes from earlier to later, and it is impossible when a cycle exists.
Sorting, searching & complexity
Sorting rearranges elements into order, and the methods differ in cost, extra space and stability. A stable sort preserves the relative order of equal elements, which matters when records are sorted by one key and ties should keep an earlier order. Bubble sort repeatedly compares adjacent pairs and swaps out-of-order pairs, so the largest element bubbles to the end each pass; it costs quadratic time in the worst and average cases and linear time on an already sorted array if an early-exit flag is used. Selection sort repeatedly selects the minimum of the unsorted part and swaps it into place, always costing quadratic comparisons but only linear swaps. Insertion sort inserts each element into its correct place among the earlier sorted elements, costing quadratic time in the worst case but linear time on nearly sorted data, which makes it the method of choice for small or nearly sorted inputs.
Merge sort divides the array into halves, sorts each half recursively, and merges the sorted halves in linear time, giving n log n time in all cases at the cost of linear extra space. Quick sort chooses a pivot, partitions the array so smaller elements go left and larger elements go right, and recurses on both sides; it is fast in practice and in-place, with average n log n time, but degrades to quadratic time when the pivot is repeatedly the smallest or largest element, as on already sorted data with a first-element pivot. Choosing a median-of-three pivot or random pivot reduces that risk. Heap sort builds a heap and repeatedly extracts the root, giving n log n time in all cases with constant extra space, but it is not stable.
Searching mirrors the same trade-offs. Linear search scans in order and costs linear time, but works on unsorted data. Binary search repeatedly halves a sorted interval: compare the middle element, discard the half that cannot contain the target, and repeat, giving logarithmic time. It requires random access and sorted data. A hash table maps keys to bucket indices with a hash function and aims for constant average lookup. Collisions are handled by chaining, where each bucket holds a list of entries, or by open addressing, where probing searches for another slot using linear probing, quadratic probing or double hashing. The load factor is the number of stored elements divided by the number of buckets, and performance degrades as it grows, so tables rehash into a larger table when the load factor passes a threshold. Clustering is the tendency of linear probing to form long runs of occupied slots.
Asymptotic notation describes growth for large n, ignoring constant factors and lower-order terms. Big-O gives an upper bound, Omega gives a lower bound, and Theta gives a tight bound when upper and lower bounds match. A recurrence describes a recursive algorithm in terms of smaller inputs, and the master theorem solves recurrences of the form T of n equals a times T of n divided by b plus f of n, where a subproblems of size n divided by b are solved and f of n is the divide and combine cost. If f of n grows more slowly than n to the power log base b of a, the subproblems dominate; if it grows at the same rate, an extra log factor appears; if it grows faster and satisfies a regularity condition, the divide and combine cost dominates. Divide and conquer splits, solves and combines, as in merge sort and quick sort. Dynamic programming solves overlapping subproblems once and reuses results: the Fibonacci recurrence recomputes the same values exponentially often without memoisation, but becomes linear with a table; the zero-one knapsack and longest common subsequence problems build tables where each cell depends on smaller subproblems, trading space for the avoidance of repeated work.
Key definitions
- Array: A collection of elements of the same type stored in contiguous memory, accessed in constant time by index.
- Stack: A linear structure with last-in first-out access: insertions and deletions occur only at the top.
- Queue: A linear structure with first-in first-out access: insertions occur at the rear and deletions at the front.
- Circular queue: A queue implemented in a fixed array where indices wrap around with modulo arithmetic so freed front space is reused.
- Linked list: A chain of nodes where each node holds data and a pointer to the next node, allowing constant-time insertion or deletion at a known node.
- Binary search tree: A binary tree in which every left-subtree key is smaller than the node key and every right-subtree key is larger.
- AVL tree: A self-balancing binary search tree in which the balance factor of every node stays between minus one and plus one.
- Heap: A complete binary tree satisfying the heap property: in a max-heap each parent is at least as large as its children.
- Huffman coding: An optimal prefix code built by repeatedly merging the two least frequent symbols, giving shorter codes to frequent symbols.
- Graph: A set of vertices joined by edges, which may be directed or undirected and may carry weights.
- Breadth-first search: A queue-based graph traversal that visits vertices in increasing distance from the source in an unweighted graph.
- Depth-first search: A stack or recursion based traversal that explores as far as possible along each branch before backtracking.
- Minimum spanning tree: A tree connecting all vertices of a graph with the smallest possible total edge weight.
- Stable sort: A sorting method that preserves the relative order of elements with equal keys.
- Hash table: A structure mapping keys to bucket indices with a hash function, aiming for constant average-time lookup.
- Load factor: The number of stored elements divided by the number of buckets in a hash table.
- Big-O notation: An asymptotic upper bound on growth: f of n is Big-O of g of n if f is bounded above by a constant multiple of g for large n.
- Theta notation: An asymptotic tight bound: f of n is Theta of g of n when it is bounded both above and below by constant multiples of g for large n.
- Divide and conquer: A design method that splits a problem into subproblems, solves them recursively, and combines their results.
- Dynamic programming: A method that solves overlapping subproblems once, stores their results, and reuses them instead of recomputing them.
Formulas
- Array address: address(i) = base + i x element size.
- Circular queue next index: next = (index + 1) mod capacity.
- Heap indices (zero-based): children of i are 2i + 1 and 2i + 2; parent of i is floor((i - 1) / 2).
- Load factor: alpha = n / m, where n is the number of elements and m is the number of buckets.
- Binary search: T(n) = T(n / 2) + O(1), giving O(log n) time.
- Merge sort: T(n) = 2T(n / 2) + O(n), giving O(n log n) time.
- Master theorem, case 1: if f(n) = O(n to the power (log base b of a minus epsilon)) then T(n) = Theta(n to the power log base b of a).
- Master theorem, case 2: if f(n) = Theta(n to the power log base b of a) then T(n) = Theta(n to the power log base b of a times log n).
- Master theorem, case 3: if f(n) = Omega(n to the power (log base b of a plus epsilon)) and a regularity condition holds, then T(n) = Theta(f(n)).
- Height of a complete binary tree with n nodes is floor(log base 2 of n).
Worked examples
Example 1: Evaluate the postfix expression 5 3 2 * + 4 - using a stack, showing the stack after each token.
Scan left to right. Push 5, stack is 5. Push 3, stack is 5, 3. Push 2, stack is 5, 3, 2. Token * pops 2 and 3, computes 3 times 2 equals 6, pushes 6, stack is 5, 6. Token + pops 6 and 5, computes 5 plus 6 equals 11, pushes 11, stack is 11. Push 4, stack is 11, 4. Token - pops 4 and 11, computes 11 minus 4 equals 7, pushes 7. The final result is 7. Note the order for subtraction: the first popped value is the right operand.
Example 2: Run Dijkstra algorithm from vertex A on this graph: A to B weight 4, A to C weight 2, C to B weight 1, B to D weight 5, C to D weight 8, C to E weight 10, D to E weight 2. Find shortest distances to all vertices.
Initial distances: A 0, others infinity. Finalise A (0). Relax A edges: B becomes 4, C becomes 2. Smallest unfinalised is C (2); finalise C. Relax C edges: B improves from 4 to 2 plus 1 equals 3, D becomes 2 plus 8 equals 10, E becomes 2 plus 10 equals 12. Smallest unfinalised is B (3); finalise B. Relax B edges: D improves from 10 to 3 plus 5 equals 8. Smallest unfinalised is D (8); finalise D. Relax D edges: E improves from 12 to 8 plus 2 equals 10. Finalise E (10). Final distances: A 0, B 3, C 2, D 8, E 10. The path to B via C beats the direct edge, which is why relaxation matters.
Example 3: Trace one partition step of quick sort on the array [5, 2, 9, 1, 7] using the last element 7 as pivot, with the standard Lomuto scheme.
Pivot is 7. Index i starts at minus 1, meaning no element smaller than the pivot has been placed yet. Scan j from 0: element 5 is less than 7, so i becomes 0 and 5 stays at position 0. Element 2 is less than 7, so i becomes 1 and 2 stays at position 1. Element 9 is not less than 7, so i stays 1. Element 1 is less than 7, so i becomes 2 and swap positions 2 and 3, giving [5, 2, 1, 9, 7]. Finally swap the pivot into position i plus 1 equals 3, giving [5, 2, 1, 7, 9]. The pivot 7 is now in its final sorted position, with smaller elements left and larger elements right.
Example 4: Solve T(n) = 2T(n / 2) + O(n) and T(n) = 3T(n / 2) + O(n) with the master theorem.
For the first recurrence, a equals 2 and b equals 2, so log base 2 of 2 equals 1, and n to that power is n. Here f(n) is O(n), the same order as n, so case 2 applies and T(n) equals Theta(n log n), which is merge sort. For the second recurrence, a equals 3 and b equals 2, so log base 2 of 3 is about 1.58, and n to that power grows faster than f(n) equals n. Since f(n) is O(n to the power 1.58 minus epsilon), case 1 applies and T(n) equals Theta(n to the power log base 2 of 3), about Theta(n to the power 1.58). The extra subproblem outweighs the linear combine cost.
Stack versus queue
| Property | Stack | Queue |
|---|---|---|
| Access order | Last-in first-out | First-in first-out |
| Insert operation | Push at top | Enqueue at rear |
| Remove operation | Pop from top | Dequeue from front |
| Typical use | Function calls, undo, expression evaluation | Scheduling, buffering, breadth-first search |
Sorting algorithm comparison
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n squared) | O(n squared) | O(1) | Yes |
| Selection sort | O(n squared) | O(n squared) | O(n squared) | O(1) | No |
| Insertion sort | O(n) | O(n squared) | O(n squared) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick sort | O(n log n) | O(n log n) | O(n squared) | O(log n) stack | No |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
BFS versus DFS
| Property | BFS | DFS |
|---|---|---|
| Data structure | Queue | Stack or recursion |
| Order | Level by level, nearest first | Deep along a branch first |
| Unweighted shortest path | Yes, from the source | No, not in general |
| Typical uses | Shortest path, level order | Cycle detection, topological sort |
Collision resolution methods
| Method | Idea | Drawback |
|---|---|---|
| Chaining | Each bucket holds a list of entries | Extra pointers and memory |
| Linear probing | Probe successive slots | Primary clustering into long runs |
| Quadratic probing | Probe at quadratic offsets | Secondary clustering, table must stay below half full for guarantees |
| Double hashing | Second hash gives the step size | Needs a good second hash function |
Diagrams (described)
Circular queue diagram: an array drawn as a ring, with front and rear arrows advancing clockwise and wrapping from the last slot back to the first, showing how dequeued front space is reused.
AVL rotation diagram: a left-left case drawn as a tall left subtree leaning left, with a right rotation arrow lifting the left child to the root and reattaching the middle subtree, restoring balance without changing inorder order.
Heap array diagram: a binary tree drawn above its array storage, with arrows mapping each tree node to its array index, illustrating the 2i plus 1, 2i plus 2 and parent formulas.
Dijkstra progress diagram: a graph with tentative distances written beside each vertex, finalised vertices shaded, and relaxed edges highlighted at each step until all vertices are finalised.
Quick sort partition diagram: an array divided into three regions by two moving pointers, labelled smaller than pivot, not yet examined, and larger than pivot, with the pivot held aside until its final swap.
Exam points
- Inorder traversal of a binary search tree always yields keys in sorted order; preorder and postorder do not.
- A stack is the natural structure for function calls, expression evaluation, parenthesis matching and backtracking.
- A queue is the natural structure for breadth-first search, scheduling and buffering; BFS gives shortest paths only in unweighted graphs.
- Dijkstra algorithm requires non-negative edge weights; it does not work correctly with negative weights.
- Prim and Kruskal both produce a minimum spanning tree, but Prim grows one tree while Kruskal sorts edges and avoids cycles.
- Quick sort average time is n log n but worst case is quadratic, typically on sorted data with a poor pivot choice.
- Merge sort is stable and n log n in all cases but needs linear extra space; heap sort is n log n and in-place but not stable.
- Hash table average lookup is constant only when the hash function spreads keys well and the load factor is kept low.
- The height of a balanced binary search tree with n nodes is logarithmic, so search costs logarithmic time; a degenerate tree costs linear time.
- Topological sorting is defined only for directed acyclic graphs; a cycle makes it impossible.
Common mistakes
- Mistake: treating Big-O as an exact running time. Correction: Big-O is an asymptotic upper bound for large n that ignores constants and lower-order terms.
- Mistake: assuming binary search works on unsorted data. Correction: binary search requires sorted data and random access; on unsorted data use linear search or sort first.
- Mistake: applying Dijkstra with negative edge weights. Correction: use an algorithm that handles negative weights, such as Bellman-Ford, and check for negative cycles.
- Mistake: confusing a complete binary tree with a full binary tree. Correction: complete means levels filled left to right; full means every node has zero or two children.
- Mistake: thinking heap sort is stable because merge sort is. Correction: heap sort moves elements across large distances during heapify, so equal elements can change relative order.
- Mistake: forgetting that a circular queue full state can look identical to empty. Correction: sacrifice one slot or keep a count to distinguish full from empty.
- Mistake: overwriting a linked-list pointer before saving the next node. Correction: always save the next pointer first, then relink, or the rest of the list is lost.
- Mistake: claiming quick sort is always n log n. Correction: worst case is quadratic; average case is n log n and depends on pivot choice.
Practice questions from this note (original practice — not official PYQs)
Checking login…
Quick revision: Linear structures first: arrays give constant access but linear middle insertion; stacks are last-in first-out and queues are first-in first-out, with circular queues wrapping by modulo arithmetic. Linked lists give cheap insertion at a known node but linear access by position. Trees next: binary search tree inorder is sorted, AVL balance factors stay in minus one to plus one with four rotation cases, and heaps store complete trees in arrays with children at 2i plus 1 and 2i plus 2. Graphs next: BFS uses a queue and gives unweighted shortest paths, DFS uses a stack or recursion, Dijkstra needs non-negative weights, Prim grows one tree and Kruskal sorts edges avoiding cycles, and topological sort needs a directed acyclic graph. Sorting and searching last: merge sort is stable n log n with linear space, quick sort averages n log n but is quadratic in the worst case, heap sort is n log n in-place but unstable, binary search is logarithmic on sorted data, hash tables aim for constant average time with load factor n divided by m, and the master theorem classifies recurrences by comparing f of n with n to the power log base b of a.
Unit revision note (quick recap)
A data structure is a way to organise data so the operations you need are fast. An algorithm’s cost is measured as input grows, not on one small example.
Learning objectives
- Choose structures by operation cost
- Analyse sorting/searching complexity
- Apply graph algorithms
Key concepts
- Stack (LIFO): Last in, first out — like a pile of plates; used for undo, recursion, expression evaluation.
- Queue (FIFO): First in, first out — like a ticket line.
- Big-O: Worst-case growth: O(1), O(log n), O(n), O(n log n), O(n²).
- Dijkstra: Shortest paths from a source with non-negative weights; fails with negative edges (use Bellman-Ford).
- Quicksort worst case: O(n²) with a bad pivot on sorted input; O(n log n) on average.
Formulas
- Quicksort average: O(n log n); worst: O(n²)
- Binary search: O(log n) on sorted data
Worked examples
- Merge sort always O(n log n) but needs extra space; quicksort is in-place on average.
Exam points
- BST search is O(log n) only if balanced; a degenerate BST is O(n).
- BFS uses a queue, DFS uses a stack/recursion.
Common mistakes
- Quoting average-case complexity as if it were worst-case, or forgetting the sorted-input assumption.
Quick revision: Arrays, lists, stacks, queues, trees, heaps, hashing, graphs, sorting, DP basics.
Practice questions from the whole unit bank (28 in the bank)
This unit's practice bank — the note above has its own smaller practice set drawn from the same bank, so a question can appear in both lists. The list below shows the free sample or the full bank depending on your plan.
Checking login…
Related tests
Unit test for this unit (28 bank questions, 34 min) · Full Mock — CS Paper 2 (100 questions) · Combined 150-question mock (180 min). All +2 per correct, no negative marking.
Revision summary
Arrays, lists, stacks, queues, trees, heaps, hashing, graphs, sorting, DP basics.
After revising, take the unit test above, then check your unit-wise report on the Dashboard to find weak topics.