Skip to main content
InterviewHubPRO
HomeTracksSection 63: Data Structures & Algorithms (100 Qs)
Section 63 of 64100 Questions (1 Per Page)

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 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.11 Connected Milestones
100 of 100 Qs

Part 1: Intro, Approach & Complexity Analysis (1 - 5)

5 Questions
1
JuniorCode#dsa#Intro

What 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.

2
JuniorCode#dsa#Intro

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.

3
SeniorCode#dsa#Intro

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)).

4
JuniorCode#Event Loop#Memory Management

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).

5
JuniorCode#dsa#Intro

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 Questions
6
Most AskedMidCode#Data Structures

Two 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).

7
MidCode#Data Structures

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).

8
MidCode#Data Structures

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).

9
MidCode#Data Structures

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.

10
MidCode#Data Structures

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).

11
MidCode#Data Structures

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).

12
MidCode#Data Structures

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).

13
MidCode#Data Structures

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).

14
MidCode#Data Structures

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.

15
MidCode#Data Structures

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).

16
MidCode#GraphQL#Data Structures

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).

17
MidCode#Data Structures

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).

18
MidCode#Data Structures

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 Questions
19
MidCode#Algorithms

Valid 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).

20
Most AskedMidCode#Algorithms#Data Structures

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).

21
Most AskedMidCode#Algorithms

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.

22
MidCode#Docker & Containers#Algorithms

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).

23
MidCode#Algorithms

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).

24
Most AskedMidCode#Algorithms

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)).

25
MidCode#Algorithms

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).

26
MidCode#Algorithms

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).

27
MidCode#GraphQL#Algorithms

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).

28
MidCode#Algorithms

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 Questions
29
Most AskedMidCode#Memory Management#Data Structures

Valid 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).

30
MidCode#Memory Management#Data Structures

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).

31
MidCode#Memory Management#Data Structures

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).

32
MidCode#Memory Management#Data Structures

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).

33
MidCode#Memory Management#Data Structures

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).

34
MidCode#Memory Management#Data Structures

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).

35
MidCode#Memory Management#Data Structures

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).

36
MidCode#Memory Management#Data Structures

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 Questions
37
Most AskedSeniorCode#Data Structures

Reverse 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).

38
Most AskedSeniorCode#Data Structures

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).

39
Most AskedSeniorCode#Data Structures

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).

40
Most AskedSeniorCode#Data Structures

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).

41
Most AskedSeniorCode#Data Structures

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).

42
Most AskedSeniorCode#Data Structures

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).

43
Most AskedSeniorCode#Data Structures

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.

44
Most AskedSeniorCode#Data Structures

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).

45
Most AskedSeniorCode#Data Structures

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 Questions
46
Most AskedMidCode#Algorithms

Binary 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).

47
Most AskedMidCode#Algorithms

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).

48
Most AskedMidCode#Algorithms#Data Structures

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).

49
Most AskedMidCode#Algorithms#Data Structures

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).

50
Most AskedMidCode#Algorithms

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).

51
Most AskedMidCode#Algorithms

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).

52
Most AskedMidCode#Algorithms#Data Structures

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 Questions
53
Most AskedMidCode#Data Structures

Invert / 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).

54
Most AskedMidCode#Data Structures

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).

55
MidCode#Data Structures

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).

56
MidCode#Data Structures

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).

57
MidCode#Data Structures

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).

58
MidCode#Data Structures

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).

59
Most AskedMidCode#Data Structures

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).

60
MidCode#Data Structures

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).

61
MidCode#Data Structures

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).

62
Most AskedMidCode#Algorithms#Data Structures

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).

63
MidCode#Data Structures

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).

64
MidCode#Data Structures

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 Questions
65
Most AskedMidCode#Memory Management#Data Structures

Implement 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).

66
MidCode#Memory Management#Data Structures

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).

67
MidCode#Memory Management#Data Structures

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).

68
MidCode#Memory Management#Data Structures

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).

69
MidCode#Memory Management#Data Structures

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).

70
MidCode#Memory Management#Data Structures

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).

71
MidCode#Memory Management#Data Structures

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).

72
MidCode#Memory Management#Data Structures

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 Questions
73
Most AskedMidCode#dsa#Backtracking

Subsets (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).

74
MidCode#dsa#Backtracking

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).

75
MidCode#GraphQL

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!.

76
MidCode#dsa#Backtracking

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).

77
Most AskedMidCode#dsa#Backtracking

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).

78
MidCode#dsa#Backtracking

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).

79
MidCode#dsa#Backtracking

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 Questions
80
Most AskedMidCode#Algorithms#Data Structures

Number 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).

81
Most AskedMidCode#Algorithms#Data Structures

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).

82
MidCode#Algorithms#Data Structures

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).

83
MidCode#Algorithms#Data Structures

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).

84
Most AskedMidCode#Algorithms#Data Structures

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).

85
MidCode#Components#Algorithms

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).

86
MidCode#Algorithms#Data Structures

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).

87
MidCode#Algorithms#Data Structures

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).

88
MidCode#Algorithms#Data Structures

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).

89
MidCode#Memory Management#Algorithms

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).

90
MidCode#Algorithms#Data Structures

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 Questions
91
Most AskedMidCode#CLI#Algorithms

Climbing 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).

92
MidCode#CLI#Algorithms

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).

93
Most AskedMidCode#Algorithms

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).

94
Most AskedMidCode#Algorithms

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}).

95
MidCode#Algorithms

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).

96
MidCode#Algorithms

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).

97
MidCode#Algorithms

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).

98
MidCode#Algorithms

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).

99
MidCode#Algorithms

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).

100
MidCode#Algorithms

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}).