Interview Q&A · questions with model answers
Algorithms Interview Questions
Part of the study plan for: Machine Learning Engineer
Ordered by how often they're asked. Most-asked answers are free to read in full; members see every answer and can rate their confidence on each.
-
Most asked Memoization vs tabulation?
Memo: top-down recursion + cache.
-
Most asked BFS vs DFS on trees—when each?
BFS for level order / shortest depth; DFS for path problems, subtree properties, recursion-friendly shapes.
-
Explain average-case vs worst-case for hash tables.
Average O(1) ops with good hashing/load factor; worst-case O(n) if all keys collide in one bucket.
-
When does binary search apply beyond sorted arrays?
Whenever you can define a monotonic predicate over a search space (answer binary search).
-
Linked list vs array tradeoffs?
Lists: O(1) insert/delete at known node, O(n) access.
-
Balanced BST vs skewed BST complexity?
Balanced ops O(log n); skewed degenerates to O(n) like a linked list.
-
Adjacency list vs matrix?
List: O(V+E) space, good for sparse graphs.
-
When is BFS preferred for shortest path?
Unweighted graphs (or equal weights)—fewest edges.
-
0/1 knapsack vs unbounded knapsack difference?
0/1: each item once (iterate capacity backward or 2D).
-
Greedy vs DP—how do you choose?
Use greedy if a local choice is provably safe; otherwise DP/search when local optima can fail.
-
Difference between Big-O, Big-Theta, and Big-Omega?
O is upper bound, Omega lower bound, Theta tight bound when both apply.
-
When is O(n log n) preferable to O(n²)?
Almost always for large n; n² grows much faster.
-
When is a stack the right tool?
LIFO needs: parentheses matching, DFS, expression eval, undo, monotonic next-greater.
-
Bellman-Ford vs Dijkstra?
Bellman-Ford handles negative edges and detects negative cycles but is slower O(VE); Dijkstra needs ≥0 weights.
-
Merge sort vs quicksort tradeoffs?
Merge: stable O(n log n) worst, O(n) extra space.
-
When is backtracking preferred over DP?
When you need all solutions / combinatorial enumeration, or states don't overlap usefully for caching.
-
What is the lower bound for comparison-based sorting?
Ω(n log n) in the comparison model (decision tree argument).
-
Chaining vs open addressing?
Chaining stores collisions in bucket lists; open addressing probes other slots in the table.
-
When can you sort in O(n)?
When keys allow counting/radix/bucket sort (limited integer range or digit structure)—not general comparisons.