Data Structures & Algorithms (DSA) Coding Interview Master Bank
Arrays, Two Pointers, Sliding Window, Linked Lists, Trees, Graphs, Dynamic Programming, Heap/Priority Queue, Sorting, and Big-O complexity analysis.
Curriculum Roadmap & Learning Path
11 StagesPart 1: Intro, Approach & Complexity Analysis (1 - 5)
5 QuestionsWhat is the Core Framework for Approaching Data Structures & Algorithms (DSA) Live Coding Interviews?
Data Structures and Algorithms (DSA) form the foundational toolkit of software engineering: Data Structures: Systematic methods of organizing, storing, and referencing data in computer memory (e.g., Arrays, Hash Tables, Linked Lists.
Asymptotic Notation & Amortized Complexity.
Big-O (O): Upper bound / worst-case execution time • Big-\Omega (\Omega): Lower bound / best-case execution time • Big-\Theta (\Theta): Tight bound (upper and lower bounds match within constant factors) • Amortized Analysis: Average time per operation over a long sequence.
The Master Theorem.
Solves divide-and-conquer recurrences of the form T(n) = aT(n/b) + f(n): Compare f(n) against n^{\logb a} • If work at leaves dominates (f(n) n^{\logb a}): T(n) = \Theta(f(n)).
Space Complexity: Call Stack vs Heap.
Call Stack: Used for function recursion • Heap Memory: Used for dynamic data structures (new Map(), new Array(), iterative queues).
Constraint-Based Pattern Recognition.
Use problem constraints (N) to instantly deduce the required time complexity: N \le 20: Backtracking, Bitmask DP (O(2^N) or O(N!)) • N \le 10^3: O(N^2) DP, Nested Loops • N \le 10^5: O(N \log N) Sorting, Binary Search, Heaps, Divide & Conquer • N \le 10^6: O(N) Hash Map, Sliding Window, Two Pointers, Monotonic Stack.
Part 2: Arrays, Strings & Hash Maps (6 - 18)
13 QuestionsTwo Sum.
Iterate through numbers and check if target - current already exists in a Hash Map. If yes, return their indices; otherwise store current -> index.: Time: O(N) Space: O(N).
Longest Consecutive Sequence.
Put all numbers in a Set. Only start counting a sequence if num - 1 does NOT exist in the set (meaning num is the start of a streak). Then increment num + 1 while present in the set.: Time: O(N) Space: O(N).
Group Anagrams.
Sort each word's characters alphabetically to create a canonical key. Group words with the same sorted key together into a Hash Map.: Time: O(N \cdot K \log K) Space: O(N \cdot K).
Product of Array Except Self.
Do two passes without division: first compute running prefix products from left to right; then multiply by running suffix products from right to left.: Time: O(N) Space: O(1) auxiliary.
Maximum Subarray (Kadane’s Algorithm).
Iterate through the array keeping track of currentSum. At each element, decide whether to add it to currentSum or start a new subarray fresh from nums[i].: Time: O(N) Space: O(1).
Subarray Sum Equals K.
Use prefix sums and a Hash Map storing frequency of prefix sums encountered so far. At each step, if currentPrefixSum - k is in the map, add its frequency to total count.: Time: O(N) Space: O(N).
Best Time to Buy and Sell Stock (I & II).
Part I (One Transaction): Track minPrice seen so far and update maxProfit = max(maxProfit, price - minPrice) • Part II (Unlimited Transactions): Accumulate all positive price differences price[i] - price[i-1] greedily • Time: O(N) Space: O(1).
Longest Common Prefix.
Compare characters vertically across all strings at index 0, 1, 2, \dots. The moment any string ends or a character mismatch occurs, return prefix up to that point.: Time: O(N \cdot M) Space: O(1).
String Encode and Decode.
Encode each string by prepending its length followed by a delimiter (e.g. length#string). On decoding, read until # to parse exact chunk size and slice bytes safely.: Time: O(N) Space: O(1) auxiliary.
Rotate Array.
In-place 3-step reversal trick: Reverse the entire array • Reverse the first k elements • Reverse the remaining N - k elements • Time: O(N) Space: O(1).
Next Permutation.
Find rightmost pivot index i where nums[i] nums[i] and swap them • Reverse suffix after i to get lexicographically smallest continuation • Time: O(N) Space: O(1).
Merge Intervals.
Sort intervals by start time. Iterate through: if current interval overlaps with previous (curr[0] <= prev[1]), merge them by setting prev[1] = max(prev[1], curr[1]); else push as new interval.: Time: O(N \log N) Space: O(N).
Insert Interval.
Add all intervals ending before newInterval starts • Merge all overlapping intervals into newInterval by expanding its [min(start), max(end)] • Add merged newInterval and append remaining subsequent intervals • Time: O(N) Space: O(N).
Part 3: Two Pointers & Sliding Window (19 - 28)
10 QuestionsValid Palindrome.
Two pointers moving towards center. Skip non-alphanumeric characters, compare lowercase characters. If any mismatch, return false; else true when pointers cross.: Time: O(N) Space: O(1).
Two Sum II (Input Array Is Sorted).
Left pointer at 0, right pointer at N-1. If nums[l] + nums[r] < target, increment l; if greater, decrement r.: Time: O(N) Space: O(1).
3Sum.
Sort the array. Fix element i (skipping duplicates). Run Two Sum II with two pointers on the remainder to find nums[l] + nums[r] === -nums[i].: Time: O(N^2) Space: O(1) auxiliary.
Container With Most Water.
Two pointers at extremes. Water capacity is bounded by the shorter line: min(h[l], h[r]) * (r - l). Always shift the pointer with the smaller height inward to potentially find taller vertical bars.: Time: O(N) Space: O(1).
Trapping Rain Water.
Maintain maxLeft and maxRight with two pointers. Whichever boundary is lower limits water level: add maxLeft - height[l] and advance l, or maxRight - height[r] and decrement r.: Time: O(N) Space: O(1).
Longest Substring Without Repeating Characters.
Sliding window with right pointer expanding. Store last seen index of each character. If character was seen within current window, jump left pointer to lastSeen[c] + 1.: Time: O(N) Space: O(\min(N, \Sigma)).
Longest Repeating Character Replacement.
Sliding window where window is valid if windowSize - maxFreq <= k (meaning non-majority characters can all be replaced). If invalid, shrink left pointer.: Time: O(N) Space: O(26) = O(1).
Minimum Window Substring.
Count target characters in t. Expand r until all target characters are matched (have === need). Then contract l to minimize window length while still valid.: Time: O(N + M) Space: O(\Sigma).
Permutation in String.
Fixed-size sliding window of length len(s1). Maintain letter frequency matching between s1 and current window in s2.: Time: O(N) Space: O(26) = O(1).
Sliding Window Maximum.
Use a Monotonic Deque storing indices in decreasing value order. Front is always maximum of current window. Pop smaller elements from back before inserting, pop out-of-window elements from front.: Time: O(N) Space: O(K).
Part 4: Stacks, Queues & Monotonic Stacks (29 - 36)
8 QuestionsValid Parentheses.
Push opening brackets onto stack. For closing brackets, check if stack top matches corresponding opening symbol; if not, string is invalid. Return stack.length === 0 at end.: Time: O(N) Space: O(N).
Min Stack.
Maintain a secondary minStack. Every time a value is pushed, push min(val, minStack.top) onto minStack. getMin() then returns top of minStack in strictly O(1) time.: Time: O(1) for all operations Space: O(N).
Evaluate Reverse Polish Notation.
Operands are pushed onto a stack. When an operator is encountered, pop the top two operands, evaluate the expression (b op a), and push result back.: Time: O(N) Space: O(N).
Daily Temperatures.
Monotonic Decreasing Stack storing indices. When today's temperature exceeds temperatures[stack.top], pop and record distance: res[prevIdx] = i - prevIdx.: Time: O(N) Space: O(N).
Largest Rectangle in Histogram.
Monotonic Increasing Stack. When a shorter bar is encountered, pop bars and calculate area with height of popped bar and width between current index and new stack top.: Time: O(N) Space: O(N).
Implement Queue using Stacks.
Use two stacks: inStack for pushes, outStack for pops/peeks. When outStack is empty, transfer all elements from inStack to reverse their order into FIFO.: Time: Amortized O(1) per operation Space: O(N).
Generate Parentheses.
Backtracking with two counters: Add ( if open < n • Add ) if close < open (never allow closing bracket without an open pair) • Time: O(\frac{4^n}{\sqrt{n}}) Catalan Number Space: O(N).
Car Fleet.
Sort cars by starting position descending (closest to target first). Compute time to destination (target - pos) / speed. If a car arrives in \le time of car ahead, it joins the fleet ahead.: Time: O(N \log N) Space: O(N).
Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)
9 QuestionsReverse a Linked List.
Iterate with three pointers: prev = null, curr = head, next. Save curr.next, point curr.next = prev, advance prev = curr, curr = next. Return prev.: Time: O(N) Space: O(1).
Merge Two Sorted Lists.
Use a dummy head node. Compare l1.val and l2.val, splice the smaller node into tail.next, and advance that list. Append remaining non-empty list.: Time: O(N + M) Space: O(1).
Linked List Cycle (Floyd’s Tortoise and Hare).
Slow pointer moves 1 step, fast pointer moves 2 steps. If there is a cycle, fast will eventually lap slow and slow === fast. If fast hits null, no cycle exists.: Time: O(N) Space: O(1).
Remove Nth Node From End of List.
Advance fast pointer by N+1 steps from dummy head. Then move slow and fast together until fast === null. slow.next is now exactly the Nth node from end to delete.: Time: O(N) Space: O(1).
Reorder List.
Find middle with fast & slow pointers • Reverse second half of list • Merge first half and reversed second half alternately • Time: O(N) Space: O(1).
Copy List with Random Pointer.
Two passes with a Hash Map mapping oldNode -> newNode.: Pass 1: Clone all nodes without pointers into the map • Pass 2: Connect map[curr].next = map[curr.next] and map[curr].random = map[curr.random] • Time: O(N) Space: O(N).
Add Two Numbers.
Traverse both lists node by node, summing corresponding digits plus carry. Insert sum % 10 into new node and set carry = Math.floor(sum / 10).: Time: O(\max(N, M)) Space: O(1) auxiliary.
Find the Duplicate Number.
Floyd's Tortoise and Hare Cycle Detection on implicit graph i -> nums[i].: Intersection: slow = nums[slow], fast = nums[nums[fast]] until they meet • Find entrance: Reset slow2 = 0, move slow and slow2 at 1 step/iteration until they collide • Time: O(N) Space: O(1).
Merge K Sorted Lists.
Divide and conquer: Pairwise merge lists using mergeTwoLists. In round 1, merge K lists into K/2; in round 2, K/4, until 1 list remains.: Time: O(N \log K) Space: O(1).
Part 6: Binary Search & Search on Answer (46 - 52)
7 QuestionsBinary Search on Sorted Boundaries.
Standard binary search template: mid = l + Math.floor((r - l) / 2). For lower bound (first element \ge target), keep moving left r = mid - 1 when nums[mid] >= target.: Time: O(\log N) Space: O(1).
Search a 2D Matrix.
Treat M \times N matrix as a single 1D virtual sorted array of size M \cdot N. Coordinate translation: row = Math.floor(mid / N), col = mid % N.: Time: O(\log(M \cdot N)) Space: O(1).
Search in Rotated Sorted Array.
At least one half is always normally sorted: If nums[l] <= nums[mid] (left half sorted): check if target lies between nums[l] and nums[mid] • Else (right half sorted): check if target lies between nums[mid] and nums[r] • Time: O(\log N) Space: O(1).
Find Minimum in Rotated Sorted Array.
Compare nums[mid] against nums[r]. If nums[mid] > nums[r], minimum must be in right half: l = mid + 1. Else minimum is at or left of mid: r = mid. Loop terminates with nums[l].: Time: O(\log N) Space: O(1).
Koko Eating Bananas.
Binary Search on Answer range [1, max(piles)]. For eating rate k, calculate hours required: Math.ceil(p / k). If hours <= h, try slower rate r = k; else l = k + 1.: Time: O(N \log(\max(P))) Space: O(1).
Time Based Key-Value Store.
Hash Map of lists of (timestamp, value). Timestamps are appended in monotonically increasing order. get() runs binary search for greatest timestamp \le target.: Time: set: O(1), get: O(\log N) Space: O(N).
Median of Two Sorted Arrays.
Binary search on the partition of the smaller array. Partition both arrays such that leftPartitionSize === (M + N + 1) / 2. Valid when maxLeft1 <= minRight2 and maxLeft2 <= minRight1.: Time: O(\log(\min(M, N))) Space: O(1).
Part 7: Binary Trees, BSTs & Traversals (53 - 64)
12 QuestionsInvert / Flip Binary Tree.
Recursively swap root.left and root.right at every node from leaves to root (or preorder).: Time: O(N) Space: O(H).
Maximum Depth of Binary Tree.
Height of a tree is 1 + max(depth(left), depth(right)). Base case: empty node returns 0.: Time: O(N) Space: O(H).
Diameter of Binary Tree.
At each node, the longest path passing through it is leftDepth + rightDepth. Update global max diameter while bottom-up recursion returns 1 + max(left, right).: Time: O(N) Space: O(H).
Balanced Binary Tree.
Bottom-up check: return height if balanced, or -1 immediately if any subtree has left - right > 1. Avoids redundant O(N^2) checks.: Time: O(N) Space: O(H).
Same Tree & Symmetric Tree.
Same Tree: p.val === q.val and isSame(p.left, q.left) and isSame(p.right, q.right) • Symmetric Tree: Compare mirror reflections t1.val === t2.val and isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left) • Time: O(N) Space: O(H).
Subtree of Another Tree.
For every node in root, check if tree rooted here is identical to subRoot using isSameTree. If not, recursively test isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot).: Time: O(N \cdot M) Space: O(H).
Lowest Common Ancestor (LCA) of BST & Binary Tree.
BST: If both p and q are greater than root, go right • Binary Tree: If current node matches p or q, return it • Time: O(N) (or O(H) for BST) Space: O(H).
Binary Tree Level Order Traversal.
BFS with a Queue. For each level, record levelSize = queue.length. Pop exactly levelSize nodes, collect their values in a sub-list, and push their non-null children.: Time: O(N) Space: O(W) = O(N).
Binary Tree Right Side View.
BFS level-order traversal. For each level, append the last element in that level to the result array. (Or reverse preorder DFS visit root -> right -> left tracking depth).: Time: O(N) Space: O(W) = O(N).
Validate Binary Search Tree.
Pass valid open interval (minVal, maxVal) recursively down the tree. Every node must satisfy minVal < node.val < maxVal. Left child inherits (minVal, node.val); right child inherits (node.val, maxVal).: Time: O(N) Space: O(H).
Kth Smallest Element in a BST.
In-order traversal (left -> root -> right) of a BST visits elements in strictly sorted ascending order. Stop and return the K-th visited element.: Time: O(H + K) Space: O(H).
Construct Tree from Preorder & Inorder Traversal.
First element of preorder is always root. Find root's position in inorder using a Hash Map: elements to the left form left subtree, elements to the right form right subtree.: Time: O(N) Space: O(N).
Part 8: Heaps, Priority Queues & Tries (65 - 72)
8 QuestionsImplement Trie (Prefix Tree).
N-ary tree where each node has a children map (or array of 26) and a boolean isEndOfWord.: insert: walk or create nodes, mark end • search: walk nodes, verify node.isEndOfWord • startsWith: walk nodes, return true if prefix path exists • Time: O(L) per operation Space: O(N \cdot L).
Kth Largest Element in an Array.
Min-Heap of size K. Add elements; when heap size exceeds K, pop the minimum. At the end, root of the Min-Heap is guaranteed to be the K-th largest element.: Time: O(N \log K) Space: O(K).
Top K Frequent Elements.
Bucket Sort in O(N) time: Count frequencies with Hash Map • Group elements into an array of buckets where index is the frequency: buckets[freq] = [elements] • Iterate buckets backwards from N down to 1 until K elements are collected • Time: O(N) Space: O(N).
Find Median from Data Stream.
Two Heaps balancing: small: Max-Heap for lower half of numbers • large: Min-Heap for upper half • Time: addNum: O(\log N), findMedian: O(1) Space: O(N).
Task Scheduler.
Mathematical formula based on maximum task frequency maxFreq: (maxFreq - 1) * (n + 1) + countOfMaxFreqTasks. Answer is max(len(tasks), formulaResult).: Time: O(N) Space: O(26) = O(1).
Design Twitter.
Post tweet: prepend (timestamp, tweetId) to user's tweet list • Follow/unfollow: update user's followee Set • Get news feed: Merge K sorted lists using Max-Heap of the 10 most recent tweets from followees and self • Time: Post/Follow: O(1), NewsFeed: O(K \log U) Space: O(U + T).
Reorganize String.
Max-Heap by frequency. Always pop the most frequent character, append it, but hold it in prev so it cannot be placed consecutively. Re-insert prev on next step.: Time: O(N \log 26) = O(N) Space: O(26) = O(1).
Minimum Cost to Connect Sticks.
Huffman Coding greedy pattern: Min-Heap of stick lengths. Repeatedly extract the two shortest sticks, sum them, add to total cost, and push sum back into heap.: Time: O(N \log N) Space: O(N).
Part 9: Backtracking & Combinatorial Search (73 - 79)
7 QuestionsSubsets (Power Set).
At each index, make binary decision: either include nums[i] or exclude nums[i]. When index reaches N, snapshot current subset.: Time: O(N \cdot 2^N) Space: O(N).
Combination Sum.
Backtracking with unlimited reuse: at each index i, either choose candidates[i] and recurse at same index i (with target - candidates[i]), or skip to i + 1.: Time: O(2^{\text{target} / \min}) Space: O(\text{target} / \min).
Permutations.
At each level, pick any unused element from nums (track with a visited set or in-place swapping). Recurse until perm size equals N.: Time: O(N!.
Subsets II.
Sort the array first to group identical numbers. In backtracking loop, skip duplicate elements: if i > start && nums[i] === nums[i - 1], continue.: Time: O(N \cdot 2^N) Space: O(N).
Word Search in Grid.
DFS from every matching starting cell in 4 directions. In-place marker: temporarily replace cell with # to mark visited, and restore original character on backtrack.: Time: O(M \cdot N \cdot 4^L) Space: O(L).
Palindrome Partitioning.
At index i, test all substrings s[i...j]. If s[i...j] is a palindrome, add it to currentPartition and recursively solve suffix j + 1.: Time: O(N \cdot 2^N) Space: O(N).
N-Queens.
Place one queen per row. Track attack lines with three sets: cols, posDiag (r + c), and negDiag (r - c). If cell is safe, place queen and advance to row + 1.: Time: O(N!) Space: O(N).
Part 10: Graphs, BFS, DFS & Union-Find (80 - 90)
11 QuestionsNumber of Islands.
Iterate through the 2D grid. When a land cell '1' is found, increment island count and trigger BFS/DFS to sink all connected land cells by flipping them to '0'.: Time: O(M \cdot N) Space: O(M \cdot N).
Clone Graph.
DFS with a Hash Map mapping originalNode -> clonedNode. If node already in map, return clone; else create clone, add to map, and recursively clone each neighbor.: Time: O(V + E) Space: O(V).
Rotting Oranges.
Multi-source BFS. Enqueue all initially rotten oranges 2, count fresh oranges 1. At each minute, infect adjacent fresh oranges. If fresh oranges remain at end, return -1.: Time: O(M \cdot N) Space: O(M \cdot N).
Pacific Atlantic Water Flow.
Work backwards from ocean borders: start from Pacific edges and run DFS inwards uphill (neighborHeight >= currentHeight); repeat from Atlantic edges. Cells visited by both oceans form answer.: Time: O(M \cdot N) Space: O(M \cdot N).
Course Schedule (I & II).
Topological Sort (Kahn's Algorithm): Compute in-degree for each course • Queue all courses with in-degree 0 • Process courses: decrement neighbors' in-degree • Time: O(V + E) Space: O(V + E).
Connected Components & Disjoint Set Union (DSU).
DSU with Path Compression and Union by Rank: find(x): recursively sets parent[x] = find(parent[x]) • union(x, y): attaches smaller tree under larger root, decrements component count if sets were disjoint • Time: O(\alpha(N)) \approx O(1) per operation Space: O(N).
Redundant Connection.
DSU on edge list. For each edge [u, v], check if find(u) === find(v). If both vertices are already in the same connected component, this edge creates a cycle and is the redundant connection!: Time: O(N \cdot \alpha(N)) \approx O(N) Space: O(N).
Word Ladder.
Shortest Path on unweighted graph using BFS: At each word, generate all 1-character wildcard variants (e.g. ot, ht, ho*). Transition to unvisited words matching any pattern. Return steps when reaching endWord.: Time: O(M^2 \cdot N) Space: O(M^2 \cdot N).
Network Delay Time (Dijkstra’s Algorithm).
Dijkstra's Shortest Path with Min-Heap. Store (cost, node). Pop node with minimal cumulative latency, relax edges to neighbors if new travel time is strictly shorter. Answer is max(dist.values()).: Time: O((V + E) \log V) Space: O(V + E).
Cheapest Flights Within K Stops.
Bellman-Ford algorithm executed for K + 1 iterations. Maintain prices array and a temporary copy at each iteration to avoid using more than K stops within the same relaxation pass.: Time: O(K \cdot E) Space: O(V).
Alien Dictionary.
Topological Sort on Directed Acyclic Graph (DAG): Compare adjacent words to find first differing character w1[k] -> w2[k] and add directed edge • In-degree Topological Sort (BFS) or 3-color DFS cycle check • Time: O(C) where C is total chars Space: O(V + E).
Part 11: Dynamic Programming & Knapsack (91 - 100)
10 QuestionsClimbing Stairs.
Fibonacci recurrence: to reach step n, you must come from step n-1 (1 step) or step n-2 (2 steps). Track only last two steps in O(1) space.: Time: O(N) Space: O(1).
Min Cost Climbing Stairs.
Work backwards from step N-3 down to 0: cost[i] += min(cost[i + 1], cost[i + 2]). Answer is min(cost[0], cost[1]).: Time: O(N) Space: O(1).
House Robber (I & II).
House Robber I: rob = max(rob1 + n, rob2) • House Robber II (Circular): First and last houses are neighbors • Time: O(N) Space: O(1).
Coin Change.
Bottom-up DP: dp[a] is min coins to make amount a. For each amount from 1 to amount, test each coin: dp[a] = min(dp[a], 1 + dp[a - coin]).: Time: O(\text{amount} \cdot N) Space: O(\text{amount}).
Longest Increasing Subsequence (LIS).
Patience Sorting with Binary Search (O(N \log N)): Maintain array tails. For each number, binary search for the first element \ge num in tails and overwrite it; if none exists, append num. Length of tails is the answer.: Time: O(N \log N) Space: O(N).
Word Break.
1D DP array of size N + 1 initialized to false, with dp[N] = true. For each index i working backwards, if wordDict contains s[i : i + len(w)] and dp[i + len(w)] is true, set dp[i] = true.: Time: O(N \cdot M \cdot K) Space: O(N).
Unique Paths.
Paths to cell (r, c) equal paths(r - 1, c) + paths(r, c - 1). Optimize to single row of length N: row[c] += row[c - 1].: Time: O(M \cdot N) Space: O(N).
Longest Common Subsequence (LCS).
2D DP: dp[i][j] is LCS length for text1[i:] and text2[j:].: If text1[i] === text2[j]: 1 + dp[i + 1][j + 1] • Else: max(dp[i + 1][j], dp[i][j + 1]) • Time: O(M \cdot N) Space: O(N).
Best Time to Buy and Sell Stock with Cooldown.
State machine DP with three states: holding: either keep holding or buy after resting (rest - price) • sold: sell stock held today (holding + price) • rest: either rest again or rest after selling yesterday (max(rest, sold)) • Time: O(N) Space: O(1).
0/1 Knapsack & Partition Equal Subset Sum.
Target is totalSum / 2. If sum is odd, partition is impossible. Maintain a 1D Boolean DP Set of achievable subset sums: for each number, add n + existingSum into the set. Return target in dp.: Time: O(N \cdot \text{target}) Space: O(\text{target}).