Data Structures & Algorithms MCQ
Test your Data Structures & Algorithms knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.
How This Practice Test Works
Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.
Curated by Tech Baithak Editorial Team · Last updated: June 2026
1
What is the time complexity of accessing an element in an array by index?
Correct Answer
O(1)
Explanation
Array elements are stored contiguously in memory and accessed directly via base address + index × element size, making it O(1) regardless of array size.
2
Which data structure operates on a Last-In, First-Out (LIFO) principle?
Correct Answer
Stack
Explanation
A stack processes the most recently added element first. Operations are push (insert) and pop (remove), both from the same end (top).
3
What is the time complexity of inserting an element at the beginning of a singly linked list?
Correct Answer
O(1)
Explanation
Inserting at the head only requires creating a new node and updating one pointer, which takes constant time regardless of list length.
4
Which data structure uses FIFO (First-In, First-Out) ordering?
Correct Answer
Queue
Explanation
A queue removes elements in the order they were added. Elements are enqueued at the rear and dequeued from the front.
5
What is a binary search tree (BST)?
Correct Answer
A tree where left child < parent < right child for every node
Explanation
In a BST, all values in a node's left subtree are less than the node's value, and all values in the right subtree are greater. This ordering enables O(log n) average search.
6
What is the worst-case time complexity of binary search?
Correct Answer
O(log n)
Explanation
Binary search halves the search space each step, yielding O(log n) comparisons in the worst case. It requires the array to be sorted.
7
What does a hash table use to map keys to values?
Correct Answer
A hash function
Explanation
A hash function converts a key into an index in an underlying array. With a good hash function, average-case get/put/delete are O(1).
8
What is a graph?
Correct Answer
A set of vertices connected by edges, representing relationships
Explanation
A graph G = (V, E) consists of vertices V and edges E that connect pairs of vertices. Graphs can be directed or undirected, weighted or unweighted.
9
Which traversal visits root, left subtree, right subtree in that order?
Correct Answer
Preorder
Explanation
Preorder traversal visits the current node first, then recursively visits left and right subtrees. Useful for copying or serializing a tree.
10
What is the space complexity of a recursive function that calls itself n times?
Correct Answer
O(n)
Explanation
Each recursive call adds a stack frame, so n recursive calls consume O(n) stack space.
11
What is a min-heap?
Correct Answer
A complete binary tree where every parent is less than or equal to its children
Explanation
A min-heap ensures the minimum element is always at the root. insert and extract-min take O(log n) by bubbling up or down.
12
What is the time complexity of bubble sort in the worst case?
Correct Answer
O(n²)
Explanation
Bubble sort compares adjacent elements and swaps them if out of order, requiring up to n*(n-1)/2 comparisons in the worst case.
13
What does DFS stand for in graph algorithms?
Correct Answer
Depth-First Search
Explanation
Depth-First Search explores as far as possible along a branch before backtracking. It uses a stack (or recursion) and is useful for cycle detection and topological sort.
14
What is a doubly linked list?
Correct Answer
A list where each node has pointers to both the next and previous nodes
Explanation
Each node in a doubly linked list stores a value and two pointers: next and prev. This allows O(1) deletion given a node reference, and bidirectional traversal.
15
Which sorting algorithm has the best average-case time complexity?
Correct Answer
Merge Sort — O(n log n)
Explanation
Merge sort achieves O(n log n) in all cases (best, average, worst). Quicksort also averages O(n log n) but has O(n²) worst case.
16
What is an adjacency matrix?
Correct Answer
A matrix where entry [i][j] is 1 (or weight) if edge (i,j) exists
Explanation
An adjacency matrix uses O(V²) space. Checking if an edge exists is O(1), but iterating all edges is O(V²). Better for dense graphs.
17
What is the height of a balanced binary tree with n nodes?
Correct Answer
O(log n)
Explanation
A balanced binary tree has O(log n) height since each level roughly doubles the node count. This ensures O(log n) operations.
18
Which data structure is best for implementing a priority queue?
Correct Answer
Binary Heap
Explanation
A binary heap allows insert in O(log n) and extract-min/max in O(log n), making it ideal for priority queues.
19
What is an inorder traversal of a BST guaranteed to produce?
Correct Answer
Elements in sorted (ascending) order
Explanation
Inorder traversal (left, root, right) on a BST visits nodes in ascending value order, which is why it's used to check if a tree is a valid BST.
20
What is the average-case time complexity of searching in a hash table?
Correct Answer
O(1)
Explanation
With a good hash function and low load factor, the average case for search, insert, and delete in a hash table is O(1). Collisions can degrade this to O(n).
21
What is a circular queue?
Correct Answer
A queue implemented using a fixed-size array where the rear wraps around to the front
Explanation
A circular queue reuses empty positions at the start of the array by treating the array as circular, avoiding wasted space in linear queue implementations.
22
What is the difference between a tree and a graph?
Correct Answer
A tree is a connected acyclic graph with n-1 edges for n nodes
Explanation
A tree is a special case of a graph: it is connected, has no cycles, and has exactly n-1 edges for n vertices.
23
What operation does a stack use to add an element?
Correct Answer
Push
Explanation
Push adds an element to the top of the stack. Pop removes from the top. Peek views the top without removing.
24
What is the worst-case time complexity of quicksort?
Correct Answer
O(n²)
Explanation
Quicksort degrades to O(n²) when the pivot is always the smallest or largest element (e.g., sorted input with naive pivot selection). Randomized pivot reduces this risk.
25
What is a deque (double-ended queue)?
Correct Answer
A structure allowing insertion and deletion at both ends
Explanation
A deque (pronounced "deck") supports push and pop from both front and back, generalizing both stacks and queues.
26
What is a spanning tree of a graph?
Correct Answer
A subgraph that is a tree and includes all vertices
Explanation
A spanning tree of a connected graph contains all V vertices and exactly V-1 edges, forming a tree (no cycles). A minimum spanning tree minimizes total edge weight.
27
What is the time complexity of merge sort?
Correct Answer
O(n log n)
Explanation
Merge sort divides the array into halves (log n levels) and merges them (O(n) per level), giving O(n log n) in all cases.
28
What is a trie (prefix tree)?
Correct Answer
A tree where each node represents a character and paths represent strings
Explanation
A trie stores strings by sharing common prefixes. Lookup, insert, and delete take O(L) where L is the string length, regardless of how many strings are stored.
29
What is the purpose of BFS (Breadth-First Search)?
Correct Answer
Exploring all nodes level by level, finding shortest paths in unweighted graphs
Explanation
BFS uses a queue to explore all neighbors before going deeper, guaranteeing shortest paths (fewest edges) in unweighted graphs.
30
What is a self-balancing BST?
Correct Answer
A BST that automatically maintains balance after insertions and deletions to guarantee O(log n) operations
Explanation
Self-balancing BSTs (AVL, Red-Black, etc.) perform rotations after insertions/deletions to keep height O(log n), avoiding O(n) worst-case degradation.
31
What does Big O notation describe?
Correct Answer
The upper bound on an algorithm's growth rate as input size grows
Explanation
Big O notation describes the worst-case upper bound on time (or space) complexity, ignoring constant factors and lower-order terms.
32
What is a hash collision?
Correct Answer
When two different keys produce the same hash index
Explanation
Collisions are inevitable (pigeonhole principle). They are resolved using chaining (linked lists at each bucket) or open addressing (probing for an empty slot).
33
What is insertion sort best suited for?
Correct Answer
Nearly sorted or small datasets, running in O(n) best case
Explanation
Insertion sort has O(n) best case on nearly sorted data (few swaps needed) and O(n²) worst case. It's efficient for small n and is used as a subroutine in Timsort.
34
What is the in-degree of a node in a directed graph?
Correct Answer
The number of edges entering the node
Explanation
In-degree counts edges pointing into a node. Out-degree counts edges going out. Both matter in algorithms like topological sort.
35
What does a stack overflow error indicate in recursive algorithms?
Correct Answer
The recursion depth exceeded the call stack limit
Explanation
Every function call pushes a frame onto the call stack. Infinite or excessively deep recursion exhausts the fixed-size stack, causing a stack overflow.
36
What is the primary advantage of a linked list over an array?
Correct Answer
O(1) insertion and deletion at any position given a pointer
Explanation
Linked lists allow O(1) insertion/deletion when you have a pointer to the node, without shifting elements. However, random access is O(n).
37
What is postorder traversal?
Correct Answer
Visit left, right, root
Explanation
Postorder (left, right, root) visits children before parent. Used for deleting trees and evaluating expression trees (process operands before operator).
38
What is amortized time complexity?
Correct Answer
The average time per operation over a sequence of operations
Explanation
Amortized analysis averages cost over a sequence. Dynamic array append is O(1) amortized: most appends are O(1), and occasional O(n) doubling averages out.
39
What is the difference between a complete binary tree and a full binary tree?
Correct Answer
Full: every node has 0 or 2 children; Complete: all levels filled except possibly the last (filled left to right)
Explanation
Full binary tree: every node has 0 or 2 children. Complete binary tree: all levels are full except possibly the last, which is filled from left to right. Heaps use complete binary trees.
40
What is a sentinel node in a linked list?
Correct Answer
A dummy node at the head or tail to simplify edge cases in insert/delete operations
Explanation
Sentinel (dummy) nodes eliminate special cases for empty lists or boundary conditions, simplifying code at the cost of one extra node.
1
What is the time complexity of Dijkstra's algorithm using a binary heap?
Correct Answer
O(E log V)
Explanation
With a binary heap priority queue, each edge relaxation takes O(log V) for the heap update. Total: O((E + V) log V), simplified to O(E log V) for connected graphs.
2
What distinguishes an AVL tree from a standard BST?
Correct Answer
AVL trees maintain a balance factor of at most 1 at every node, performing rotations to restore balance after mutations
Explanation
AVL trees track the balance factor (height difference of left and right subtrees) and perform single or double rotations to keep it within {-1, 0, 1}, guaranteeing O(log n) operations.
3
What is dynamic programming?
Correct Answer
A technique solving problems by breaking them into overlapping subproblems and storing results to avoid redundant computation
Explanation
DP applies to problems with optimal substructure and overlapping subproblems. Results are memoized (top-down) or tabulated (bottom-up) to achieve polynomial complexity instead of exponential.
4
What is topological sorting?
Correct Answer
A linear ordering of vertices in a DAG such that for every edge (u, v), u comes before v
Explanation
Topological sort applies only to DAGs (directed acyclic graphs). It's used for scheduling tasks, build dependency resolution, and course prerequisites.
5
What is the Floyd-Warshall algorithm used for?
Correct Answer
Finding shortest paths between all pairs of vertices in O(V³)
Explanation
Floyd-Warshall computes all-pairs shortest paths using dynamic programming in O(V³) time and O(V²) space. It handles negative edge weights but not negative cycles.
6
What is the difference between Prim's and Kruskal's algorithms?
Correct Answer
Prim's grows the MST from a vertex; Kruskal's adds edges globally in non-decreasing weight order using Union-Find
Explanation
Both find Minimum Spanning Trees. Prim's is vertex-based and faster for dense graphs. Kruskal's is edge-based and faster for sparse graphs using Union-Find.
7
What is a Red-Black tree?
Correct Answer
A self-balancing BST with color properties ensuring O(log n) height by limiting path length differences
Explanation
Red-Black trees maintain five invariants (root is black, red nodes have black children, equal black height on all paths) guaranteeing height ≤ 2 log(n+1).
8
What is the Bellman-Ford algorithm's advantage over Dijkstra's?
Correct Answer
It handles negative edge weights and detects negative cycles
Explanation
Bellman-Ford relaxes all edges V-1 times in O(VE) time. It works with negative weights and detects negative cycles (if relaxation occurs on the V-th pass).
9
What is the Union-Find (Disjoint Set Union) data structure used for?
Correct Answer
Efficiently determining if two elements belong to the same component and merging components
Explanation
Union-Find supports union and find operations. With path compression and union by rank, both operations run in near-O(1) (O(α(n)) amortized). Used in Kruskal's and cycle detection.
10
What is the Knuth-Morris-Pratt (KMP) algorithm used for?
Correct Answer
Efficient string pattern matching in O(n + m) time
Explanation
KMP preprocesses the pattern to build a failure function, avoiding redundant character comparisons, achieving O(n + m) where n is text length and m is pattern length.
11
What is memoization?
Correct Answer
Caching the results of function calls and returning cached results for the same inputs
Explanation
Memoization (top-down DP) stores computed results in a table. Recursive Fibonacci with memoization drops from O(2^n) to O(n) by avoiding recomputation.
12
What is the difference between a B-tree and a B+ tree?
Correct Answer
B+ trees store data only in leaves (linked for sequential access); B-trees store data in all nodes
Explanation
B+ trees keep all keys in leaves with leaf-level linked list, optimizing range queries. B-trees store data in all nodes. Both maintain O(log n) operations. B+ trees are used in databases.
13
What is a segment tree used for?
Correct Answer
Efficient range queries (sum, min, max) and point updates in O(log n)
Explanation
A segment tree is a binary tree built over an array enabling O(log n) range queries and point updates. Each node stores aggregate info for a subarray.
14
What is the time complexity of heapify (build-heap) for n elements?
Correct Answer
O(n)
Explanation
Build-heap runs in O(n) despite n sift-down operations because lower nodes have smaller subtrees. The total work sums to O(n) by geometric series analysis.
15
What is the LRU cache and which data structures implement it efficiently?
Correct Answer
Least Recently Used: implemented with a hash map + doubly linked list for O(1) get and put
Explanation
LRU cache evicts the least recently used item. A hash map gives O(1) lookup by key, and a doubly linked list maintains recency order with O(1) move-to-front on access.
16
What does Kadane's algorithm solve?
Correct Answer
Finding the maximum subarray sum in O(n)
Explanation
Kadane's algorithm uses DP to track the maximum subarray sum ending at each position, updating the global max at each step in a single O(n) pass.
17
What is a skip list?
Correct Answer
A layered linked list with express lanes for O(log n) average search without tree rebalancing
Explanation
A skip list maintains multiple levels of linked lists. Upper levels act as express lanes. Average search is O(log n) with high probability through randomized level assignment.
18
What is the two-pointer technique?
Correct Answer
Using two indices that move toward each other or together to solve array problems in O(n)
Explanation
Two pointers (left/right or slow/fast) solve problems like pair sum, removing duplicates, and finding the longest window in O(n) instead of O(n²) brute force.
19
What is a Fenwick tree (Binary Indexed Tree)?
Correct Answer
A compact data structure for prefix sum queries and point updates in O(log n)
Explanation
A Fenwick tree uses the lowest set bit of an index to determine responsibility ranges, enabling O(log n) prefix sums and updates with minimal code and memory.
20
What is the sliding window technique?
Correct Answer
Maintaining a subarray window that expands/contracts to solve range problems in O(n)
Explanation
Sliding window maintains a contiguous subarray and adjusts it with two pointers. Used for maximum sum subarray of size k, longest substring without repeating characters, etc.
21
What is a cycle in a directed graph, and how is it detected?
Correct Answer
A path from a vertex back to itself; detected using DFS with a recursion stack (gray coloring)
Explanation
In directed graph DFS, a back edge (edge to a node currently on the recursion stack, i.e., gray/in-progress) indicates a cycle. Three-color DFS is the classic approach.
22
What is the master theorem used for?
Correct Answer
Analyzing the time complexity of divide-and-conquer recurrences of the form T(n) = aT(n/b) + f(n)
Explanation
The master theorem gives closed-form solutions for T(n) = aT(n/b) + f(n) based on comparing f(n) with n^(log_b a). Used for merge sort, binary search, and Strassen's algorithm.
23
What is the longest common subsequence (LCS) problem?
Correct Answer
Finding the longest sequence of characters that appears in both strings in order (not necessarily contiguously)
Explanation
LCS finds the longest subsequence (characters in order but not necessarily contiguous) common to two strings. DP solves it in O(m*n) time and space.
24
What is the 0/1 knapsack problem?
Correct Answer
Selecting items with given weights and values to maximize value without exceeding weight capacity, with each item either fully included or excluded
Explanation
0/1 knapsack is an NP-hard optimization problem solved by DP in O(n*W) pseudo-polynomial time. Each item is either taken (1) or not (0).
25
What is the time complexity of Heap Sort?
Correct Answer
O(n log n)
Explanation
Heap sort builds a max-heap in O(n), then extracts the maximum n times (each extraction is O(log n)), giving O(n log n) overall. It sorts in-place.
26
What is a graph's strongly connected component (SCC)?
Correct Answer
A maximal subgraph where every vertex is reachable from every other vertex
Explanation
An SCC is a maximal set of vertices such that there exists a path between any two vertices in both directions. Kosaraju's and Tarjan's algorithms find SCCs in O(V + E).
27
What is the difference between greedy algorithms and dynamic programming?
Correct Answer
Greedy makes locally optimal choices without reconsidering; DP considers all subproblems and builds the globally optimal solution
Explanation
Greedy works when the greedy choice property holds (local optimum leads to global). DP is needed when subproblem solutions overlap and greedy fails (e.g., 0/1 knapsack).
28
What is radix sort and when is it faster than comparison-based sorts?
Correct Answer
A non-comparison sort that processes digits from least to most significant, running in O(d * (n + k)) — faster when d * k is small
Explanation
Radix sort beats O(n log n) comparison sorts when the digit count d is small. For 32-bit integers (d=4 with 8-bit digits, k=256), it runs in O(n).
29
What problem does the A* algorithm solve?
Correct Answer
Finding the shortest path from source to goal using a heuristic to guide search
Explanation
A* uses f(n) = g(n) + h(n) where g is cost from start and h is an admissible heuristic estimate to goal. It finds optimal paths faster than Dijkstra in practice.
30
What is a monotonic stack?
Correct Answer
A stack maintained in strictly increasing or decreasing order, used for next-greater/smaller-element problems in O(n)
Explanation
A monotonic stack processes each element once (O(n) total). It efficiently finds the next greater element, largest rectangle in histogram, and trapping rain water.
31
Why is a hash map preferred over an array for the "two sum" problem when aiming for O(n) time?
Correct Answer
A hash map allows O(1) average lookup of a complement value while scanning once, avoiding the O(n²) nested-loop comparison
Explanation
By storing each visited number's index in a hash map, you can check in O(1) average time whether the complement (target minus current value) has already been seen, reducing the brute-force O(n²) approach to a single O(n) pass.
32
In a min-heap represented as an array (0-indexed), how do you find the parent of the node at index i?
Correct Answer
(i - 1) / 2, using integer division
Explanation
For a 0-indexed binary heap stored in an array, the parent of node i is at index floor((i - 1) / 2), while its children are at 2i + 1 and 2i + 2. This compact mapping avoids storing explicit pointers.
33
What is the key idea behind the "fast and slow pointer" (Floyd's cycle detection) technique on a linked list?
Correct Answer
Two pointers move at different speeds; if the list has a cycle, the faster pointer will eventually meet the slower one inside the loop
Explanation
Floyd's algorithm advances a slow pointer by one node and a fast pointer by two nodes per step. If a cycle exists, the fast pointer laps the slow pointer and they meet inside the loop, detecting the cycle in O(n) time and O(1) space.
34
When choosing between an array-based and a linked-list-based implementation of a stack, what is a key practical tradeoff?
Correct Answer
Arrays offer better cache locality and lower per-element memory overhead, while linked lists avoid resizing costs and support unbounded growth without large reallocations
Explanation
Array-backed stacks store elements contiguously, improving cache performance and reducing per-element overhead, but may need costly resizing. Linked-list-backed stacks grow one node at a time with O(1) push/pop but pay extra memory for pointers and have worse cache behavior.
35
Why does counting sort run in linear time, and what limits its applicability?
Correct Answer
It tallies occurrences of each key value in a count array and then reconstructs the sorted output in O(n + k), but it is only practical when the range of key values k is not much larger than n
Explanation
Counting sort builds a frequency array indexed by key value, computes prefix sums to determine final positions, and places elements accordingly, achieving O(n + k) time. It becomes inefficient in time and space when the key range k is very large relative to n.
36
What is the main advantage of using a hash set to detect duplicates in a collection compared to sorting first?
Correct Answer
A hash set lets you check and record each element in O(1) average time during a single pass, achieving O(n) average time versus the O(n log n) needed to sort first
Explanation
Inserting into a hash set and checking membership both take O(1) average time, so scanning the collection once and tracking seen elements detects duplicates in O(n) average time, which is faster than the O(n log n) cost of sorting the data first.
37
In graph traversal, what is the practical effect of using a stack (DFS) versus a queue (BFS) when searching for a target node?
Correct Answer
A queue (BFS) explores nodes closest to the source first and finds the shortest path in an unweighted graph, while a stack (DFS) dives deep along one branch first and may find a longer path before a shorter one
Explanation
BFS processes nodes level by level using a queue, so the first time it reaches the target it has found a shortest path (in terms of edge count) in an unweighted graph. DFS uses a stack (or recursion) and explores one path fully before backtracking, which can reach the target via a longer route first.
38
Why might quicksort be implemented with random pivot selection or median-of-three pivot selection in practice?
Correct Answer
To reduce the chance of consistently picking the smallest or largest element as pivot on adversarial or already-sorted inputs, lowering the likelihood of hitting the O(n²) worst case
Explanation
Naive pivot choices like always picking the first or last element cause O(n²) behavior on sorted or reverse-sorted input. Randomized or median-of-three pivot selection makes worst-case behavior far less likely in practice, keeping expected performance close to O(n log n), though it does not change the theoretical worst case.
39
When converting a recursive algorithm into an iterative one using an explicit stack, what is being manually managed?
Correct Answer
The state that the call stack would otherwise track automatically — such as which subproblem to process next and what to do after it returns
Explanation
Recursive calls implicitly use the call stack to remember pending work and return points. Replacing recursion with an explicit stack means the programmer pushes and pops that same state manually, which can avoid stack-overflow risk for deep recursion and sometimes improves performance.
40
Why is binary search not directly applicable to a singly linked list even though the list is sorted?
Correct Answer
Binary search needs O(1) random access to jump to the middle element, but a linked list only supports O(n) sequential access, so locating the midpoint repeatedly costs O(n) and erases the logarithmic advantage
Explanation
Binary search relies on jumping directly to the middle index in O(1), which arrays support via index arithmetic. A singly linked list requires walking node by node to reach the middle, making each "jump" O(n) and reducing the overall approach to no better than linear search.
1
What is the amortized time complexity of push/pop for a dynamic array (e.g., ArrayList)?
Correct Answer
O(1) amortized per operation
Explanation
Array doubling: each element is copied at most O(log n) times total. Over n pushes: total work is n + n/2 + n/4 + ... < 2n, so O(1) amortized per push.
2
What is the time complexity of Tarjan's SCC algorithm?
Correct Answer
O(V + E)
Explanation
Tarjan's runs a single DFS pass with a stack, assigning discovery times and low-link values, finding all SCCs in O(V + E) time.
3
What is the significance of the Ω notation compared to O notation?
Correct Answer
Ω gives the lower bound on complexity; O gives the upper bound
Explanation
O notation is an upper bound (worst case). Ω notation is a lower bound (best case). Θ notation is a tight bound (both upper and lower). Proving Ω lower bounds requires adversarial arguments.
4
What is the Aho-Corasick algorithm?
Correct Answer
A multi-pattern string matching algorithm using a trie with failure links, searching for k patterns simultaneously in O(n + m + z)
Explanation
Aho-Corasick builds a trie with KMP-style failure links. It matches all k patterns in text of length n with total pattern length m in O(n + m + z), where z is match count.
5
What is van Emde Boas tree and its advantage?
Correct Answer
A tree for integers in [0, U) supporting insert, delete, successor, predecessor in O(log log U) time
Explanation
Van Emde Boas tree achieves O(log log U) operations by recursively splitting the universe into sqrt(U) clusters, dramatically faster than O(log n) for integer keys with bounded universe U.
6
What does the P vs NP problem ask?
Correct Answer
Whether every problem whose solution can be verified in polynomial time can also be solved in polynomial time
Explanation
P is the class of problems solvable in polynomial time. NP is the class verifiable in polynomial time. The open question is whether P = NP. Most believe P ≠ NP.
7
What is a suffix array and how is it used?
Correct Answer
A sorted array of all suffixes of a string, enabling O(log n) pattern search after O(n log n) or O(n) construction
Explanation
A suffix array combined with an LCP (Longest Common Prefix) array enables efficient string operations: pattern search in O(m log n), LRS in O(n), and is often preferable to suffix trees in practice.
8
What is the concept of cache-oblivious algorithms?
Correct Answer
Algorithms achieving optimal cache usage for any memory hierarchy without knowledge of cache size or block size
Explanation
Cache-oblivious algorithms (Frigo et al.) use recursive divide-and-conquer that automatically adapts to any cache size. Examples: cache-oblivious sorting, matrix multiplication, and merge sort.
9
What is the significance of the lower bound Ω(n log n) for comparison-based sorting?
Correct Answer
Any comparison-based sort must make at least Ω(n log n) comparisons in the worst case — proven by decision tree argument
Explanation
A decision tree for n-element sorting has n! leaves. Its height is ≥ log₂(n!) = Θ(n log n) by Stirling's approximation, proving no comparison sort beats Ω(n log n).
10
What is a treap?
Correct Answer
A BST that simultaneously satisfies heap order on random priorities, achieving O(log n) expected height without explicit rebalancing
Explanation
A treap is a randomized BST: each node has a key (BST order) and a random priority (max-heap order). The random priorities keep height O(log n) with high probability.
11
What is the link-cut tree and what problems does it solve?
Correct Answer
A data structure supporting dynamic tree operations (link, cut, path queries) in O(log n) amortized, enabling dynamic graph algorithms
Explanation
Link-cut trees (Sleator-Tarjan) use auxiliary splay trees to represent paths. They support link, cut, find-root, and path-aggregate operations in O(log n) amortized.
12
What is heavy-light decomposition?
Correct Answer
Decomposing a tree into O(log n) chains, enabling range queries on tree paths using a segment tree in O(log² n)
Explanation
HLD decomposes a tree into chains by always following the child with the largest subtree. Any root-to-leaf path crosses O(log n) chains, enabling efficient path queries with a segment tree.
13
What is the persistent data structure?
Correct Answer
A data structure that preserves all historical versions after modifications, sharing structure for efficiency
Explanation
Persistent data structures keep all versions by path copying (only modified nodes are duplicated). Persistent segment trees enable version queries in O(log n) per operation.
14
What is the Bloom filter?
Correct Answer
A space-efficient probabilistic structure for set membership that allows false positives but no false negatives
Explanation
Bloom filters use k hash functions and a bit array. Membership check is O(k). False positives are possible; false negatives are not. Used in databases (Cassandra), browsers (malware detection).
15
What is the difference between NP-hard and NP-complete?
Correct Answer
NP-hard is at least as hard as NP problems; NP-complete is NP-hard AND in NP (verifiable in polynomial time)
Explanation
NP-hard: at least as hard as hardest NP problems (may not be in NP). NP-complete: NP-hard AND in NP. Halting problem is NP-hard but not NP-complete (undecidable).
16
What is the Fibonacci heap and its advantage over binary heaps?
Correct Answer
It achieves O(1) amortized insert and decrease-key (vs O(log n) for binary heaps), improving Dijkstra's to O(E + V log V)
Explanation
Fibonacci heaps support O(1) amortized insert and decrease-key, O(log n) amortized delete-min. This makes Dijkstra O(E + V log V) with Fibonacci heap vs O(E log V) with binary heap.
17
What is the Z-algorithm for string processing?
Correct Answer
An algorithm computing Z[i] = length of the longest substring starting at i that matches a prefix of the string, enabling O(n) pattern search
Explanation
The Z-array Z[i] gives the length of the longest common prefix between the string and its suffix starting at i. Concatenating pattern + "$" + text and computing Z[i] finds pattern occurrences in O(n + m).
18
What is fractional cascading and when is it applied?
Correct Answer
A technique reducing k searches in k sorted lists from O(k log n) to O(log n + k) by pre-linking lists
Explanation
Fractional cascading augments each list with elements from the next, enabling cascaded search: the first list is searched in O(log n), then O(1) per additional list using embedded pointers.
19
What is the integer sorting lower bound, and why can radix sort break O(n log n)?
Correct Answer
The Ω(n log n) lower bound applies only to comparison-based sorts; radix sort exploits fixed-width integer structure to sort in O(n)
Explanation
The decision-tree lower bound applies only to comparison-based sorting. Radix sort, counting sort, and bucket sort are non-comparison algorithms exploiting integer key structure, achieving linear time.
20
What is the randomized algorithm QuickSelect and its expected time complexity?
Correct Answer
O(n) expected with O(n²) worst case
Explanation
QuickSelect finds the k-th smallest element in O(n) expected time by partitioning like quicksort but recursing only on the relevant partition. Worst case O(n²) for adversarial pivots; Median-of-Medians gives O(n) worst case.