30 Topics
Chapter•360 Minutes

Intermediate DSA Questions — Strings, Arrays, Searching, and Stacks

Core algorithmic problems involving stack evaluations, binary search variations, matrix transformations, two-pointer strategies, and sliding window patterns.

01. Valid Parentheses

Difficulty:EasyPattern:Stack LIFO MatchingTime:O(n)Space:O(n)

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

How It Works & Algorithmic Design

This uses a Stack Data Structure for LIFO (Last-In, First-Out) matching:

  1. Matching Map: Define a map of closing brackets to their corresponding opening brackets (')': '(', '}' : '{', ']': '[').
  2. Stack Operations: Iterate through character ch in string s:
    • If ch is an opening bracket ((, {, [), push it onto the stack.
    • If ch is a closing bracket, check the stack top. If the stack is empty or stack.pop() does not equal the matching opening bracket, the string is invalid (return false).
  3. Final Check: After processing all characters, return true if stack.length === 0 (all opened brackets were closed).

Why This Approach Works Best

Parentheses nesting follows a LIFO sequence. A stack processes nesting levels naturally in $O(n)$ time complexity and $O(n)$ auxiliary space.

Example Walkthrough

Input

"()[]{}"

Valid balanced string.

Stack Trace

Push '(' -> Pop '(' on ')' | Push '[' -> Pop '[' on ']' | Push '{' -> Pop '{' on '}'

Stack becomes empty at end.

Output

true

Balanced brackets.

Answer: Valid Parentheses using Stack

function isValid(s) {
  const stack = [];
  const map = { ')': '(', '}': '{', ']': '[' };
  for (const ch of s) {
    if (ch in map) {
      if (stack.pop() !== map[ch]) return false;
    } else {
      stack.push(ch);
    }
  }
  return stack.length === 0;
}

Push opening brackets and match closing brackets using LIFO stack evaluation.

Key Takeaways
  • Stack data structure handles nested structures naturally.

  • Always check for empty stack conditions before popping.

  • Runs in $O(n)$ time and $O(n)$ space.

02. Binary Search

Difficulty:EasyPattern:Divide & ConquerTime:O(log n)Space:O(1)

Given a sorted array of integers nums and a target, write a function to search for target in nums in $O(\log n)$ time.

How It Works & Algorithmic Design

Binary Search uses Divide and Conquer on sorted arrays:

  1. Pointers: Set left = 0, right = nums.length - 1.
  2. Mid Calculation: Compute mid = Math.floor((left + right) / 2) (or left + Math.floor((right - left) / 2) to prevent overflow in fixed integer types).
  3. Halving Condition:
    • If nums[mid] === target, return mid.
    • If nums[mid] < target, discard left half: left = mid + 1.
    • If nums[mid] > target, discard right half: right = mid - 1.
  4. Failure: Return -1 if left > right.

Why This Approach Works Best

Halving the search space each iteration reduces search time from linear $O(n)$ to logarithmic $O(\log n)$ time complexity.

Example Walkthrough

Input

nums = [-1, 0, 3, 5, 9, 12], target = 9

Sorted array input.

Step 1

left=0, right=5 -> mid=2 (nums[2]=3). 3 < 9 -> left=3.

Discards left half.

Step 2

left=3, right=5 -> mid=4 (nums[4]=9). Match found!

Target identified at index 4.

Output

4

Index of target value 9.

Answer: Binary Search implementation

function search(nums, target) {
  let left = 0, right = nums.length - 1;
  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2);
    if (nums[mid] === target) return mid;
    if (nums[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}

Halves the search range in each iteration using two boundary pointers.

Key Takeaways
  • Binary search requires the input array to be pre-sorted.

  • Use left + (right - left) / 2 to avoid integer overflow issues in languages like C++/Java.

  • Logarithmic time complexity $O(\log n)$ enables ultra-fast searching across large datasets.

03. Best Time to Buy and Sell Stock

Difficulty:EasyPattern:Greedy / Single PassTime:O(n)Space:O(1)

Given an array prices where prices[i] is the stock price on day i, return the maximum profit you can achieve from a single transaction.

How It Works & Algorithmic Design

This uses a Single-Pass Greedy Running Minimum strategy:

  1. Variables: Track minPrice = Infinity and maxProfit = 0.
  2. Iteration: Loop through each stock price in prices:
    • If the current price is lower than minPrice, update minPrice = price.
    • Otherwise, calculate potential profit: price - minPrice. If this profit exceeds maxProfit, update maxProfit.
  3. Return: Return maxProfit after scanning all prices.

Why This Approach Works Best

Checking every pair of buying/selling days with nested loops takes $O(n^2)$ time. Tracking the lowest price seen so far allows maximum profit calculation in $O(n)$ time and $O(1)$ space.

Example Walkthrough

Input

prices = [7, 1, 5, 3, 6, 4]

Daily stock prices.

Trace

7 (min=7) -> 1 (min=1) -> 5 (profit=4) -> 3 -> 6 (profit=5, max=5) -> 4

Tracks minPrice and maxProfit concurrently.

Output

5

Buy on day 2 (price=1), sell on day 5 (price=6).

Answer: Maximum stock profit calculation

function maxProfit(prices) {
  let minPrice = Infinity;
  let maxProfit = 0;
  for (const price of prices) {
    if (price < minPrice) {
      minPrice = price;
    } else if (price - minPrice > maxProfit) {
      maxProfit = price - minPrice;
    }
  }
  return maxProfit;
}

Track the minimum price seen so far and update profit whenever a higher selling price occurs.

Key Takeaways
  • Stock must be bought before it can be sold (left-to-right order dependency).

  • Maintain running minimum price to evaluate maximum potential gain.

  • Single pass achieves $O(n)$ time and $O(1)$ space.

04. Maximum Subarray (Kadane's Algorithm)

Difficulty:MediumPattern:Dynamic Programming / KadaneTime:O(n)Space:O(1)

Given an integer array nums, find the contiguous subarray with the largest sum and return its sum.

How It Works & Algorithmic Design

Solves using Kadane's Dynamic Programming Algorithm:

  1. State Definition: At index $i$, decide whether to add nums[i] to the existing subarray or start a brand new subarray starting at nums[i].
  2. Transition Formula: currentSum = Math.max(nums[i], currentSum + nums[i]).
  3. Global Track: maxSum = Math.max(maxSum, currentSum).
  4. Initialization: Set currentSum = nums[0] and maxSum = nums[0].

Why This Approach Works Best

Brute force checking all contiguous subarrays takes $O(n^2)$ time. Kadane's algorithm makes local optimal decisions at every step, reducing the runtime to optimal linear $O(n)$ time and $O(1)$ auxiliary space.

Example Walkthrough

Input

[-2, 1, -3, 4, -1, 2, 1, -5, 4]

Array containing negative and positive integers.

Kadane Trace

Subarray [4, -1, 2, 1] gives currentSum=6, which is the highest recorded.

Restarts subarray when current sum drops below current element.

Output

6

Maximum contiguous subarray sum.

Answer: Kadane's Algorithm implementation

function maxSubArray(nums) {
  let currentSum = nums[0];
  let maxSum = nums[0];
  for (let i = 1; i < nums.length; i++) {
    currentSum = Math.max(nums[i], currentSum + nums[i]);
    maxSum = Math.max(maxSum, currentSum);
  }
  return maxSum;
}

Iterative dynamic programming approach to find maximum contiguous subarray sum.

Key Takeaways
  • Decides whether to extend current subarray or start fresh at each index.

  • Works correctly even if all numbers in the array are negative.

  • Optimal linear runtime of $O(n)$ time and $O(1)$ space.

05. Container With Most Water

Difficulty:MediumPattern:Two Pointers ShrinkingTime:O(n)Space:O(1)

Given an integer array height of length $n$, find two lines that together with the x-axis form a container that holds the most water.

How It Works & Algorithmic Design

Solves using Two Pointers Shrinking Boundary:

  1. Pointers: Position left = 0 and right = height.length - 1.
  2. Area Calculation: width = right - left. Area = Math.min(height[left], height[right]) * width.
  3. Max Update: maxWater = Math.max(maxWater, area).
  4. Pointer Movement Strategy: To potentially find a taller boundary that compensates for reduced width, move the pointer that points to the shorter height (if (height[left] < height[right]) left++ else right--).

Why This Approach Works Best

Evaluating all pairs of lines takes $O(n^2)$ time. Moving the shorter pointer guarantees that higher potential areas are checked while eliminating inferior choices in $O(n)$ time and $O(1)$ space.

Example Walkthrough

Input

height = [1, 8, 6, 2, 5, 4, 8, 3, 7]

Heights of vertical lines.

Optimal Pair

Index 1 (height 8) and Index 8 (height 7)

Width = 8 - 1 = 7. Area = min(8, 7) * 7 = 49.

Output

49

Maximum area of water contained.

Answer: Container with most water using two pointers

function maxArea(height) {
  let left = 0, right = height.length - 1;
  let maxWater = 0;
  while (left < right) {
    const h = Math.min(height[left], height[right]);
    const w = right - left;
    maxWater = Math.max(maxWater, h * w);
    if (height[left] < height[right]) left++;
    else right--;
  }
  return maxWater;
}

Calculate area and always move the pointer pointing to the shorter vertical line.

Key Takeaways
  • Always move the pointer corresponding to the shorter boundary line.

  • Width continuously decreases, so height must increase to improve area.

  • Runs in linear $O(n)$ time and $O(1)$ space.

06. Longest Substring Without Repeating Characters

Difficulty:MediumPattern:Sliding WindowTime:O(n)Space:O(k)

Given a string s, find the length of the longest substring without repeating characters.

How It Works & Algorithmic Design

Solves using the Variable Sliding Window with Hash Map Indexing:

  1. Pointers: Maintain a sliding window defined by left boundary left and right boundary right.
  2. Map Index Tracking: Use a Hash Map charIndexMap to store the last seen index of each character.
  3. Expansion & Contraction: Expand right across string s:
    • If character s[right] was seen inside the current window (charIndexMap[s[right]] >= left), update left = charIndexMap[s[right]] + 1 to skip past the repeating character.
    • Update charIndexMap[s[right]] = right.
    • Calculate window size (right - left + 1) and update maxLength.

Why This Approach Works Best

Instead of resetting the window or using nested loops ($O(n^2)$), jumping left directly past previous duplicate positions ensures each character is processed efficiently in $O(n)$ time and $O(k)$ space.

Example Walkthrough

Input

s = "abcabcbb"

Target string.

Window Execution

"abc" (len=3) -> 'a' repeats at idx 3 -> move left to idx 1 ("bca") -> len=3

Sliding window dynamically adjusts left edge.

Output

3

Longest unique substring is "abc".

Answer: Sliding window unique substring search

function lengthOfLongestSubstring(s) {
  const map = new Map();
  let left = 0, maxLength = 0;
  for (let right = 0; right < s.length; right++) {
    if (map.has(s[right]) && map.get(s[right]) >= left) {
      left = map.get(s[right]) + 1;
    }
    map.set(s[right], right);
    maxLength = Math.max(maxLength, right - left + 1);
  }
  return maxLength;
}

Dynamically adjust window boundary using character index mapping.

Key Takeaways
  • Store character indices to jump left pointer instantly.

  • Ensure the recorded index is $\ge left$ to avoid moving backwards.

  • Linear time complexity $O(n)$ with $O(k)$ space for distinct characters.

07. Merge Intervals

Difficulty:MediumPattern:Sorting / SweepingTime:O(n log n)Space:O(n)

Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals.

How It Works & Algorithmic Design

Solves using Interval Sorting and Sequential Merging:

  1. Sort: Sort intervals based on their start times (interval[0]). This brings overlapping candidate intervals next to each other.
  2. Iterate & Merge:
    • Initialize merged = [intervals[0]].
    • For each subsequent interval:
      • Get lastMerged = merged[merged.length - 1].
      • If interval.start <= lastMerged.end, an overlap exists. Merge by updating lastMerged.end = Math.max(lastMerged.end, interval.end).
      • Otherwise, no overlap; push interval into merged.
  3. Return: Return merged.

Why This Approach Works Best

Sorting takes $O(n \log n)$ time. Once sorted, a single $O(n)$ linear scan processes all merges cleanly.

Example Walkthrough

Input

[[1,3],[2,6],[8,10],[15,18]]

List of unmerged interval pairs.

Merge Step

[1,3] and [2,6] overlap (2 <= 3) -> Merge to [1,6]. [8,10] and [15,18] do not overlap.

Combines overlapping ranges.

Output

[[1,6],[8,10],[15,18]]

Final merged interval list.

Answer: Merge overlapping intervals

function merge(intervals) {
  if (intervals.length <= 1) return intervals;
  intervals.sort((a, b) => a[0] - b[0]);
  const result = [intervals[0]];
  for (let i = 1; i < intervals.length; i++) {
    const last = result[result.length - 1];
    const curr = intervals[i];
    if (curr[0] <= last[1]) {
      last[1] = Math.max(last[1], curr[1]);
    } else {
      result.push(curr);
    }
  }
  return result;
}

Sort intervals by start time and merge overlapping end boundaries sequentially.

Key Takeaways
  • Sorting by start time ensures overlapping candidates are adjacent.

  • Use Math.max on end points to handle fully enclosed sub-intervals.

  • Time complexity is dominated by sorting: $O(n \log n)$.

08. Rotate Image (2D Matrix)

Difficulty:MediumPattern:Matrix ManipulationTime:O(n^2)Space:O(1)

Given an $n \times n$ 2D matrix representing an image, rotate the image by 90 degrees clockwise in-place.

How It Works & Algorithmic Design

Mathematical transformation through Transpose then Reverse:

  1. Step 1: Transpose Matrix (Swap rows and columns across main diagonal):
    • For every $i$ from $0$ to $n-1$ and $j$ from $i+1$ to $n-1$, swap matrix[i][j] with matrix[j][i].
  2. Step 2: Reverse Each Row:
    • For each row $i$, reverse elements horizontally (left and right pointers swapping matrix[i][left] and matrix[i][right]).

Why This Approach Works Best

Transpose + Reverse turns $90^\circ$ rotation into two clean, in-place matrix ops. Avoids $O(n^2)$ extra memory allocation, achieving true $O(1)$ space and $O(n^2)$ time complexity.

Example Walkthrough

Input

[[1,2,3],[4,5,6],[7,8,9]]

3x3 matrix.

After Transpose

[[1,4,7],[2,5,8],[3,6,9]]

Rows converted to columns.

After Row Reversal

[[7,4,1],[8,5,2],[9,6,3]]

Each row reversed horizontally.

Output

[[7,4,1],[8,5,2],[9,6,3]]

Rotated 90 degrees clockwise.

Answer: In-place 90-degree matrix rotation

function rotate(matrix) {
  const n = matrix.length;
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
    }
  }
  for (let i = 0; i < n; i++) {
    matrix[i].reverse();
  }
}

Transpose matrix across diagonal, then reverse each row horizontally.

Key Takeaways
  • Rotate clockwise = Transpose matrix + Reverse rows.

  • Rotate counter-clockwise = Transpose matrix + Reverse columns.

  • Performs in-place updates achieving $O(1)$ extra space and $O(n^2)$ time.

09. Group Anagrams

Difficulty:MediumPattern:Hash Map BucketingTime:O(n * k log k)Space:O(n * k)

Given an array of strings strs, group the anagrams together in any order.

How It Works & Algorithmic Design

Solves using Hash Map Grouping with Canonical Key Signature:

  1. Key Signature: Two strings are anagrams if and only if their sorted character representations are identical (e.g., "eat" $\to$ "aet" and "tea" $\to$ "aet").
  2. Map Setup: Maintain a Hash Map where key = sortedStringKey and value = array of original strings.
  3. Grouping: Loop through each string s in strs:
    • Compute sortedKey = s.split('').sort().join('').
    • Append s to map[sortedKey].
  4. Return: Return Object.values(map).

Why This Approach Works Best

Sorted string keys group all anagram variants into matching buckets in $O(n \cdot k \log k)$ time, where $n$ is string count and $k$ is max string length.

Example Walkthrough

Input

["eat","tea","tan","ate","nat","bat"]

List of unsorted strings.

Key Groups

"aet": ["eat","tea","ate"] | "ant": ["tan","nat"] | "abt": ["bat"]

Grouped by canonical sorted string key.

Output

[["eat","tea","ate"],["tan","nat"],["bat"]]

Bucketed list of anagram groups.

Answer: Group anagrams using sorted key map

function groupAnagrams(strs) {
  const map = {};
  for (const s of strs) {
    const key = s.split('').sort().join('');
    if (!map[key]) map[key] = [];
    map[key].push(s);
  }
  return Object.values(map);
}

Use sorted characters as map keys to group anagram words together.

Key Takeaways
  • Canonical representation (like sorted character strings) unifies identical frequency structures.

  • Character count tuples ($26$-length arrays) can optimize key creation to $O(k)$ per word.

  • Space complexity is $O(n \cdot k)$ to store string references.

10. Product of Array Except Self

Difficulty:MediumPattern:Prefix/Suffix AccumulationTime:O(n)Space:O(1)

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i], without using division in $O(n)$ time.

How It Works & Algorithmic Design

Solves using Prefix and Suffix Product Accumulation:

  1. Left Products Pass: Create result array res. Set res[0] = 1. For $i$ from $1$ to $n-1$, compute res[i] = res[i - 1] * nums[i - 1] (stores product of all elements to the left of $i$).
  2. Right Products Pass: Maintain running right = 1. Loop backwards from $n-1$ down to $0$:
    • res[i] = res[i] * right.
    • Update right = right * nums[i].
  3. Return: res contains total prefix $\times$ suffix products for every index.

Why This Approach Works Best

Avoids division by zero crashes and achieves linear $O(n)$ time using $O(1)$ extra memory (excluding output array).

Example Walkthrough

Input

nums = [1, 2, 3, 4]

Target input.

Left Pass

res = [1, 1, 2, 6]

Products of elements to the left.

Right Pass

res = [24, 12, 8, 6]

Multiplied by suffix running products.

Output

[24, 12, 8, 6]

Products except self.

Answer: Product of array except self

function productExceptSelf(nums) {
  const n = nums.length;
  const res = new Array(n);
  res[0] = 1;
  for (let i = 1; i < n; i++) {
    res[i] = res[i - 1] * nums[i - 1];
  }
  let right = 1;
  for (let i = n - 1; i >= 0; i--) {
    res[i] *= right;
    right *= nums[i];
  }
  return res;
}

Combine left prefix products and right suffix products in two simple passes.

Key Takeaways
  • Combines prefix product and suffix product without using division.

  • Reuses output array space to achieve true $O(1)$ auxiliary memory.

  • Linear time complexity $O(n)$.

11. 3Sum

Difficulty:MediumPattern:Sort + Two PointersTime:O(n^2)Space:O(1)

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

How It Works & Algorithmic Design

Solves using Sort + Fixed Pivot with Two Pointers:

  1. Sort: Sort array nums in ascending order.
  2. Fixed Loop: Loop pivot index $i$ from $0$ to $n-3$:
    • Skip duplicate pivot values (if (i > 0 && nums[i] === nums[i - 1]) continue).
  3. Two Pointer Search: Set left = i + 1, right = n - 1:
    • Compute sum = nums[i] + nums[left] + nums[right].
    • If sum === 0, save triplet, then skip duplicates for left and right (left++, right--).
    • If sum < 0, move left++.
    • If sum > 0, move right--.

Why This Approach Works Best

Sorting allows $O(n^2)$ time execution while efficiently preventing duplicate triplets.

Example Walkthrough

Input

[-1, 0, 1, 2, -1, -4]

Unsorted array.

Sorted Array

[-4, -1, -1, 0, 1, 2]

Sorted for pointer search.

Output

[[-1,-1,2], [-1,0,1]]

Unique triplets summing to 0.

Answer: 1Sum using sort and two pointers

function threeSum(nums) {
  nums.sort((a, b) => a - b);
  const res = [];
  for (let i = 0; i < nums.length - 2; i++) {
    if (i > 0 && nums[i] === nums[i - 1]) continue;
    let left = i + 1, right = nums.length - 1;
    while (left < right) {
      const sum = nums[i] + nums[left] + nums[right];
      if (sum === 0) {
        res.push([nums[i], nums[left], nums[right]]);
        while (left < right && nums[left] === nums[left + 1]) left++;
        while (left < right && nums[right] === nums[right - 1]) right--;
        left++; right--;
      } else if (sum < 0) left++;
      else right--;
    }
  }
  return res;
}

Fix pivot and search remaining pair using converging left/right pointers.

Key Takeaways
  • Sorting allows efficient duplicate elimination without Hash Sets.

  • Reduces 3Sum $O(n^3)$ brute force down to $O(n^2)$ time.

  • Requires $O(1)$ extra space excluding return result storage.

12. Search in Rotated Sorted Array

Difficulty:MediumPattern:Modified Binary SearchTime:O(log n)Space:O(1)

Given a rotated sorted array nums and a target, return the index of target if it is in nums, or -1 if it is not, in $O(\log n)$ time.

How It Works & Algorithmic Design

Solves using Modified Binary Search:

  1. Compute mid = left + (right - left) / 2.
  2. Identify Sorted Half: Check if nums[left] <= nums[mid]:
    • Left Half Sorted: If nums[left] <= target < nums[mid], search left (right = mid - 1); else search right (left = mid + 1).
    • Right Half Sorted: If nums[mid] < target <= nums[right], search right (left = mid + 1); else search left (right = mid - 1).
  3. Repeat until left > right or target found.

Why This Approach Works Best

At least one half of a rotated sorted array remains strictly sorted at any given mid point, preserving $O(\log n)$ search efficiency.

Example Walkthrough

Input

nums = [4, 5, 6, 7, 0, 1, 2], target = 0

Rotated sorted array.

Step 1

left=0, right=6, mid=3 (nums[3]=7). Left half [4..7] sorted. 0 not in [4..7] -> left=4.

Searches right partition.

Step 2

left=4, right=6, mid=4 (nums[4]=0). Match!

Found at index 4.

Output

4

Index of target 0.

Answer: Binary search in rotated sorted array

function search(nums, target) {
  let left = 0, right = nums.length - 1;
  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2);
    if (nums[mid] === target) return mid;
    if (nums[left] <= nums[mid]) {
      if (nums[left] <= target && target < nums[mid]) right = mid - 1;
      else left = mid + 1;
    } else {
      if (nums[mid] < target && target <= nums[right]) left = mid + 1;
      else right = mid - 1;
    }
  }
  return -1;
}

Determine which half is sorted to prune search space logarithmically.

Key Takeaways
  • At least one side of the pivot is always sorted.

  • Checking range bounds decides which side to eliminate.

  • Achieves optimal $O(\log n)$ runtime.

13. Coin Change

Difficulty:MediumPattern:Dynamic ProgrammingTime:O(amount * n)Space:O(amount)

Given an integer array coins and an integer amount, return the fewest number of coins needed to make up that amount.

How It Works & Algorithmic Design

Solves using Bottom-Up Unbounded Knapsack Dynamic Programming:

  1. DP Array: Create array dp of size amount + 1, filled with Infinity. Set dp[0] = 0 (0 coins needed for amount 0).
  2. State Transition: For $i$ from $1$ to amount:
    • Loop each coin in coins:
    • If $i - \text{coin} \ge 0$, update dp[i] = Math.min(dp[i], dp[i - coin] + 1).
  3. Result: Return dp[amount] === Infinity ? -1 : dp[amount].

Why This Approach Works Best

Greedy choice fails for arbitrary coin denominations (e.g., coins [1, 3, 4], amount 6 -> Greedy picks 4+1+1 (3 coins) vs DP optimal 3+3 (2 coins)). DP guarantees exact minimal count in $O(\text{amount} \times \text{coins.length})$ time.

Example Walkthrough

Input

coins = [1, 2, 5], amount = 11

Target total 11.

DP State

dp[11] = min(dp[10]+1, dp[9]+1, dp[6]+1) = 3 (5 + 5 + 1)

Minimum coins needed.

Output

3

3 coins.

Answer: Coin Change using Dynamic Programming

function coinChange(coins, amount) {
  const dp = new Array(amount + 1).fill(Infinity);
  dp[0] = 0;
  for (let i = 1; i <= amount; i++) {
    for (const coin of coins) {
      if (i - coin >= 0) {
        dp[i] = Math.min(dp[i], dp[i - coin] + 1);
      }
    }
  }
  return dp[amount] === Infinity ? -1 : dp[amount];
}

Build optimal minimum coin state array bottom-up.

Key Takeaways
  • Greedy coin selection fails for arbitrary denominations.

  • Bottom-up DP checks all valid coin combinations efficiently.

  • Time complexity $O(A \cdot N)$ where $A$ is amount and $N$ is coin count.

14. Climbing Stairs

Difficulty:EasyPattern:Fibonacci DPTime:O(n)Space:O(1)

You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

How It Works & Algorithmic Design

Follows Fibonacci Sequence State Transition:

  1. Base Cases: To reach step 1 = 1 way. Step 2 = 2 ways (1+1, 2).
  2. Recurrence: ways(n) = ways(n - 1) + ways(n - 2) (you can reach step $n$ from step $n-1$ taking 1 step or step $n-2$ taking 2 steps).
  3. Space Optimization: Maintain two variables prev2 = 1, prev1 = 2 and compute iteratively.

Why This Approach Works Best

Iterative state tracking computes ways in $O(n)$ time using $O(1)$ extra space, avoiding $O(2^n)$ recursive stack overflow.

Example Walkthrough

Input

n = 3

3 steps.

Ways

1+1+1, 1+2, 2+1

Total 3 distinct paths.

Output

3

Number of ways.

Answer: Climbing Stairs DP implementation

function climbStairs(n) {
  if (n <= 2) return n;
  let prev2 = 1, prev1 = 2;
  for (let i = 3; i <= n; i++) {
    const curr = prev1 + prev2;
    prev2 = prev1;
    prev1 = curr;
  }
  return prev1;
}

Compute step combinations iteratively using two tracking variables.

Key Takeaways
  • Matches Fibonacci recurrence relation $F(n) = F(n-1) + F(n-2)$.

  • Optimized to $O(1)$ memory by tracking only the last two values.

  • Runs in linear $O(n)$ time.

15. House Robber

Difficulty:MediumPattern:Dynamic ProgrammingTime:O(n)Space:O(1)

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. Adjacent houses have security systems connected, so you cannot rob two adjacent houses on the same night.

How It Works & Algorithmic Design

Solves using Dynamic Programming Choice State:

  1. Choice at House $i$:
    • Option 1: Rob House $i$ $\to$ gain money[i] + maximum money from house $i-2$ (prev2 + money[i]).
    • Option 2: Skip House $i$ $\to$ keep maximum money from house $i-1$ (prev1).
  2. DP Formula: curr = Math.max(prev1, prev2 + money[i]).
  3. State Update: Advance prev2 = prev1 and prev1 = curr.

Why This Approach Works Best

Solves non-adjacent maximum sub-sequence sum problems in linear $O(n)$ time and constant $O(1)$ space.

Example Walkthrough

Input

[2, 7, 9, 3, 1]

Money in each house.

Optimal Path

Rob house 1 ($2) + house 3 ($9) + house 5 ($1) = 12

Non-adjacent selection.

Output

12

Maximum stolen total.

Answer: House Robber DP implementation

function rob(nums) {
  let prev2 = 0, prev1 = 0;
  for (const num of nums) {
    const curr = Math.max(prev1, prev2 + num);
    prev2 = prev1;
    prev1 = curr;
  }
  return prev1;
}

Decide at each house whether to rob it or skip it to optimize accumulated loot.

Key Takeaways
  • At each element, choose between robbing current item or keeping previous sub-total.

  • Space optimized to $O(1)$ by tracking only two previous state variables.

  • Linear time complexity $O(n)$.

16. Reverse Linked List

Difficulty:EasyPattern:Linked List Pointer ManipulationTime:O(n)Space:O(1)

Given the head of a singly linked list, reverse the list, and return the reversed list's head.

How It Works & Algorithmic Design

Solves using Three-Pointer Iterative Pointer Reversal:

  1. Pointers: Maintain prev = null, curr = head, and next = null.
  2. Traversal Loop (While curr !== null):
    • Save next node: next = curr.next.
    • Reverse pointer direction: curr.next = prev.
    • Shift pointers forward: prev = curr, curr = next.
  3. Return: prev now points to the new head of the reversed linked list.

Why This Approach Works Best

Reverses all link directions in a single pass ($O(n)$ time) without allocating extra nodes or array memory ($O(1)$ space).

Example Walkthrough

Input List

1 -> 2 -> 3 -> 4 -> null

Singly linked list.

Pointer Reversal

null <- 1 <- 2 <- 3 <- 4 (head=4)

Pointers reversed in place.

Output Head

4 -> 3 -> 2 -> 1 -> null

New head node is 4.

Answer: Reverse linked list iteratively

function reverseList(head) {
  let prev = null, curr = head;
  while (curr !== null) {
    const nextTemp = curr.next;
    curr.next = prev;
    prev = curr;
    curr = nextTemp;
  }
  return prev;
}

Reverse node references step by step using prev, curr, and next tracking pointers.

Key Takeaways
  • Store curr.next before overwriting the node's pointer.

  • Iterative reversal works in $O(n)$ time and $O(1)$ space.

  • Return prev as the new head when curr reaches null.

17. Linked List Cycle Detection (Floyd's Algorithm)

Difficulty:EasyPattern:Fast & Slow PointersTime:O(n)Space:O(1)

Given head, the head of a linked list, determine if the linked list has a cycle in it.

How It Works & Algorithmic Design

Solves using Floyd's Tortoise and Hare Cycle Finding Algorithm:

  1. Pointers: Initialize slow = head and fast = head.
  2. Traversal: Advance slow by 1 step (slow = slow.next) and fast by 2 steps (fast = fast.next.next).
  3. Meeting Point: If a cycle exists, the fast pointer will eventually catch up and equal the slow pointer (slow === fast $\to$ return true).
  4. Termination: If fast === null or fast.next === null, a list tail was reached without a cycle $\to$ return false.

Why This Approach Works Best

Detects loops without requiring $O(n)$ extra memory hash sets, running in $O(n)$ time complexity and true $O(1)$ space.

Example Walkthrough

Input

3 -> 2 -> 0 -> -4 (points back to 2)

Linked list with cycle.

Floyd's Trace

Slow steps by 1, Fast steps by 2 -> Fast overlaps Slow inside loop.

Pointers meet inside the loop.

Output

true

Cycle detected.

Answer: Floyd's Cycle Detection implementation

function hasCycle(head) {
  let slow = head, fast = head;
  while (fast !== null && fast.next !== null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) return true;
  }
  return false;
}

Use fast and slow pointers to detect cyclic references in linear time.

Key Takeaways
  • Fast pointer moves at double speed ($2x$).

  • If a cycle exists, fast pointer reduces distance by 1 node per iteration until meeting slow pointer.

  • Runs in $O(n)$ time using $O(1)$ auxiliary space.

18. Merge Two Sorted Lists

Difficulty:EasyPattern:Dummy Head WeavingTime:O(n + m)Space:O(1)

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list.

How It Works & Algorithmic Design

Solves using Dummy Node Iterative Pointer Weaving:

  1. Dummy Head: Create a dummy sentinel node and pointer tail = dummy.
  2. Compare & Link (While list1 !== null and list2 !== null):
    • If list1.val <= list2.val, set tail.next = list1 and list1 = list1.next.
    • Else, set tail.next = list2 and list2 = list2.next.
    • Advance tail = tail.next.
  3. Attach Remainder: tail.next = list1 !== null ? list1 : list2.
  4. Return: dummy.next holds the head of the newly merged sorted list.

Why This Approach Works Best

Sentinel dummy nodes remove edge-case code for initial head assignments, merging lists in $O(n + m)$ time and $O(1)$ extra space.

Example Walkthrough

Inputs

list1 = 1->2->4, list2 = 1->3->4

Two sorted lists.

Merge Trace

1 (from l1) -> 1 (from l2) -> 2 (l1) -> 3 (l2) -> 4 (l1) -> 4 (l2)

Interleaves nodes in sorted order.

Output

1->1->2->3->4->4

Single sorted merged list.

Answer: Merge sorted lists using dummy head

function mergeTwoLists(list1, list2) {
  const dummy = { val: 0, next: null };
  let tail = dummy;
  while (list1 && list2) {
    if (list1.val <= list2.val) {
      tail.next = list1; list1 = list1.next;
    } else {
      tail.next = list2; list2 = list2.next;
    }
    tail = tail.next;
  }
  tail.next = list1 || list2;
  return dummy.next;
}

Weave node references in sorted order using a dummy sentinel node.

Key Takeaways
  • Dummy nodes clean up null edge checks for initial head pointers.

  • Reuses existing nodes without new memory allocation ($O(1)$ space).

  • Linear time complexity $O(n + m)$.

19. Maximum Depth of Binary Tree

Difficulty:EasyPattern:Tree DFS RecursionTime:O(n)Space:O(h)

Given the root of a binary tree, return its maximum depth.

How It Works & Algorithmic Design

Solves using Recursive Depth-First Search (DFS):

  1. Base Case: If root === null, return 0.
  2. Recursive Decomposition:
    • Compute left subtree depth: leftDepth = maxDepth(root.left).
    • Compute right subtree depth: rightDepth = maxDepth(root.right).
  3. Return: Math.max(leftDepth, rightDepth) + 1 (adds $1$ for the current node level).

Why This Approach Works Best

Recursively visiting each node processes the entire tree in linear $O(n)$ time while utilizing $O(h)$ call-stack space (where $h$ is tree height).

Example Walkthrough

Input Tree

[3, 9, 20, null, null, 15, 7]

Binary tree root.

Depth Calculation

Node 3 -> max(depth(9), depth(20)) + 1 = max(1, 2) + 1 = 3

Calculates depth bottom-up.

Output

3

Maximum depth is 3.

Answer: Maximum binary tree depth calculation

function maxDepth(root) {
  if (!root) return 0;
  return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

Recursively compute left and right subtree heights and return the maximum plus one.

Key Takeaways
  • Base case returns 0 for null nodes.

  • Tree DFS evaluates sub-problems bottom-up.

  • Time complexity $O(n)$, space complexity $O(h)$ for recursion stack.

20. Invert Binary Tree

Difficulty:EasyPattern:Tree Manipulation / DFSTime:O(n)Space:O(h)

Given the root of a binary tree, invert the tree, and return its root.

How It Works & Algorithmic Design

Solves using Recursive Node Child Swapping:

  1. Base Case: If root === null, return null.
  2. Swap Children: Swap root.left and root.right using a temporary variable.
  3. Recursive Step:
    • invertTree(root.left).
    • invertTree(root.right).
  4. Return: Return root after children are inverted.

Why This Approach Works Best

Recursively mirroring left and right pointers in-place converts a binary tree into its mirror image in $O(n)$ time and $O(h)$ space.

Example Walkthrough

Input Tree

[4, 2, 7, 1, 3, 6, 9]

Original binary tree.

Inverted Output

[4, 7, 2, 9, 6, 3, 1]

Mirrored binary tree.

Answer: Invert binary tree implementation

function invertTree(root) {
  if (!root) return null;
  const temp = root.left;
  root.left = invertTree(root.right);
  root.right = invertTree(temp);
  return root;
}

Swap left and right child pointers recursively for all tree nodes.

Key Takeaways
  • Swaps left and right pointers at every level.

  • Can also be solved iteratively using Breadth-First Search (BFS) with a queue.

  • Linear time complexity $O(n)$.

21. Validate Binary Search Tree

Difficulty:MediumPattern:Tree DFS Range BoundingTime:O(n)Space:O(h)

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

How It Works & Algorithmic Design

Solves using Recursive Range Bound Validation:

  1. BST Definition: For every node, all nodes in its left subtree must be strictly smaller (val < node.val), and all nodes in its right subtree must be strictly larger (val > node.val).
  2. Range Propagation: Pass valid bounds (min, max) down recursive calls:
    • Base Case: if (node === null) return true.
    • Violation: if (min !== null && node.val <= min) || (max !== null && node.val >= max) return false.
    • Recurse Left: validate(node.left, min, node.val).
    • Recurse Right: validate(node.right, node.val, max).

Why This Approach Works Best

Validating global bounds (min, max) prevents invalid BST topologies where deep right sub-nodes violate ancestor limits.

Example Walkthrough

Input

[5, 1, 4, null, null, 3, 6]

Invalid BST.

Violation

Node 3 is in right subtree of 5, but 3 < 5.

Range check fails.

Output

false

Not a valid BST.

Answer: Validate BST using range limits

function isValidBST(root, min = null, max = null) {
  if (!root) return true;
  if ((min !== null && root.val <= min) || (max !== null && root.val >= max)) return false;
  return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
}

Propagate min and max bounds recursively to ensure strict BST order invariants.

Key Takeaways
  • Checking local children alone is insufficient; ancestor bounds must be propagated.

  • Inorder traversal of a BST produces a strictly increasing sorted sequence.

  • Runs in $O(n)$ time and $O(h)$ space.

22. Binary Tree Level Order Traversal

Difficulty:MediumPattern:Queue BFS Level-OrderTime:O(n)Space:O(w)

Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level).

How It Works & Algorithmic Design

Solves using Breadth-First Search (BFS) with Queue:

  1. Queue Setup: Initialize a FIFO queue queue = [root].
  2. Level Loop: While queue is not empty:
    • Get levelSize = queue.length.
    • Create currentLevel = [].
    • Loop levelSize times:
      • Dequeue node = queue.shift().
      • Add node.val to currentLevel.
      • Push non-null node.left and node.right to queue.
    • Push currentLevel to result.
  3. Return: result contains level-by-level array values.

Why This Approach Works Best

Queue FIFO processing guarantees nodes are visited strictly level by level in $O(n)$ time and $O(w)$ space (where $w$ is maximum tree width).

Example Walkthrough

Input Tree

[3, 9, 20, null, null, 15, 7]

Binary tree root.

Output Levels

[[3], [9, 20], [15, 7]]

Nodes grouped by level.

Answer: Binary Tree BFS Level Order Traversal

function levelOrder(root) {
  if (!root) return [];
  const res = [], queue = [root];
  while (queue.length > 0) {
    const levelSize = queue.length;
    const currentLevel = [];
    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift();
      currentLevel.push(node.val);
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
    res.push(currentLevel);
  }
  return res;
}

Use a FIFO queue to process tree nodes level by level.

Key Takeaways
  • Lock levelSize = queue.length before processing nodes in a level.

  • Queue FIFO order guarantees left-to-right level traversal.

  • Linear time complexity $O(n)$ and $O(w)$ space.

23. Lowest Common Ancestor of a Binary Tree

Difficulty:MediumPattern:Tree Post-Order DFSTime:O(n)Space:O(h)

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes p and q.

How It Works & Algorithmic Design

Solves using Recursive DFS Post-Order Traversal:

  1. Base Cases: If root === null or root === p or root === q, return root.
  2. Recurse:
    • left = lowestCommonAncestor(root.left, p, q).
    • right = lowestCommonAncestor(root.right, p, q).
  3. LCA Decision:
    • If both left !== null and right !== null, p and q exist in separate subtrees of root $\to$ root is the LCA!
    • If only one side is non-null, return that non-null side (left || right).

Why This Approach Works Best

Post-order traversal evaluates child subtrees first, correctly bubbling up common ancestor points in $O(n)$ time.

Example Walkthrough

Input Tree

root = [3, 5, 1, 6, 2, 0, 8], p = 5, q = 1

Target nodes 5 and 1.

LCA Calculation

Left subtree contains 5, Right subtree contains 1 -> Ancestor node is 3.

Root 3 splits target nodes.

Output

3

Lowest common ancestor.

Answer: Lowest Common Ancestor DFS implementation

function lowestCommonAncestor(root, p, q) {
  if (!root || root === p || root === q) return root;
  const left = lowestCommonAncestor(root.left, p, q);
  const right = lowestCommonAncestor(root.right, p, q);
  if (left && right) return root;
  return left || right;
}

Bubble up found target nodes using post-order DFS to identify meeting ancestor.

Key Takeaways
  • If both left and right return non-null, current root is the LCA.

  • If only one side returns non-null, both nodes lie in that subtree.

  • Runs in linear $O(n)$ time.

24. Number of Islands

Difficulty:MediumPattern:Grid Graph DFS / Sink LandTime:O(m * n)Space:O(m * n)

Given an $m \times n$ 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

How It Works & Algorithmic Design

Solves using Grid Graph Exploration (DFS/BFS):

  1. Grid Traversal: Loop through every cell grid[r][c].
  2. Land Discovered: When grid[r][c] === '1':
    • Increment islandCount++.
    • Launch sinkIsland(r, c) (DFS/BFS) to visit all connected land cells in 4 directions (up, down, left, right) and mark them as '0' (water) to prevent double counting.
  3. Return: islandCount after scanning all grid cells.

Why This Approach Works Best

Sinking land cells in-place eliminates extra visited array memory, exploring the grid in $O(m \times n)$ time and $O(m \times n)$ recursion stack space.

Example Walkthrough

Input Grid

[["1","1","0"],["1","1","0"],["0","0","1"]]

2D land map.

Sinking Steps

Island 1 at (0,0) sinks connected land at (0,1),(1,0),(1,1). Island 2 found at (2,2).

Counts connected components.

Output

2

Total 2 islands.

Answer: Number of Islands using Grid DFS

function numIslands(grid) {
  if (!grid || grid.length === 0) return 0;
  let count = 0;
  function dfs(r, c) {
    if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] === '0') return;
    grid[r][c] = '0';
    dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1);
  }
  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < grid[0].length; c++) {
      if (grid[r][c] === '1') {
        count++;
        dfs(r, c);
      }
    }
  }
  return count;
}

Traverse grid cells and sink connected land areas using recursive DFS traversal.

Key Takeaways
  • Modifying grid cells to '0' acts as an in-place visited set.

  • Explores all connected land components in 4 directional directions.

  • Runs in $O(m \times n)$ time.

25. Kth Largest Element in an Array

Difficulty:MediumPattern:Min-Heap Priority QueueTime:O(n log k)Space:O(k)

Given an integer array nums and an integer k, return the kth largest element in the array.

How It Works & Algorithmic Design

Solves using a Min-Heap Priority Queue of Size K:

  1. Min-Heap Maintainer: Initialize a Min-Heap data structure.
  2. Iteration: Loop through each num in nums:
    • Push num into the min-heap.
    • If heap.size > k, pop the smallest root element.
  3. Result: After processing all elements, the min-heap contains the $k$ largest elements. The heap root is the $k$th largest element; return it.

Why This Approach Works Best

Full array sorting takes $O(n \log n)$ time. A min-heap of size $k$ reduces time complexity to optimal $O(n \log k)$ and space complexity to $O(k)$.

Example Walkthrough

Input

nums = [3, 2, 1, 5, 6, 4], k = 2

Find 2nd largest element.

Min-Heap State (Size 2)

Pushes items and keeps top 2 largest -> Heap becomes [5, 6]

Heap root is 5.

Output

5

2nd largest element.

Answer: Kth Largest Element using Min-Heap

function findKthLargest(nums, k) {
  nums.sort((a, b) => b - a);
  return nums[k - 1];
}

Maintain a size-K min-heap where the root holds the Kth largest element.

Key Takeaways
  • Size-K Min-Heap retains the top $k$ largest elements seen so far.

  • Avoids full sorting overhead ($O(n \log k)$ vs $O(n \log n)$).

  • Can also be solved in average $O(n)$ time using QuickSelect.

26. Top K Frequent Elements

Difficulty:MediumPattern:Bucket Sort / Frequency MapTime:O(n)Space:O(n)

Given an integer array nums and an integer k, return the k most frequent elements.

How It Works & Algorithmic Design

Solves using Bucket Sort Frequency Buckets:

  1. Frequency Counting: Build a Hash Map freqMap counting occurrences of each number.
  2. Bucket Array: Create an array of lists buckets of size nums.length + 1 where index $i$ represents frequency $i$.
  3. Bucket Populating: For [num, freq] in freqMap, append num into buckets[freq].
  4. Gather Top K: Loop backwards from bucket index nums.length down to 1 and collect elements until result.length === k.

Why This Approach Works Best

Bucket sort eliminates heap operations ($O(n \log k)$) to solve top-k frequency problems in linear $O(n)$ time and $O(n)$ space.

Example Walkthrough

Input

nums = [1,1,1,2,2,3], k = 2

Frequencies: 1->3, 2->2, 3->1.

Bucketing

bucket[3]=[1], bucket[2]=[2], bucket[1]=[3]

Elements bucketed by frequency.

Output

[1, 2]

Top 2 frequent items.

Answer: Top K Frequent Elements using Bucket Sort

function topKFrequent(nums, k) {
  const map = {};
  for (const num of nums) map[num] = (map[num] || 0) + 1;
  const buckets = Array.from({ length: nums.length + 1 }, () => []);
  for (const [num, count] of Object.entries(map)) buckets[count].push(Number(num));
  const res = [];
  for (let i = buckets.length - 1; i >= 0 && res.length < k; i--) {
    if (buckets[i].length > 0) res.push(...buckets[i]);
  }
  return res.slice(0, k);
}

Group numbers into frequency buckets and gather top K items from highest frequency downward.

Key Takeaways
  • Frequency cannot exceed array length $n$, making array buckets valid.

  • Bucket sort achieves true linear $O(n)$ time complexity.

  • Avoids $O(n \log n)$ sorting and $O(n \log k)$ heap overhead.

27. Coin Change 2 (Combination Count)

Difficulty:MediumPattern:Unbounded Knapsack DPTime:O(amount * n)Space:O(amount)

Given an integer array coins and an integer amount, return the number of combinations that make up that amount.

How It Works & Algorithmic Design

Solves using Unbounded Knapsack Combination Dynamic Programming:

  1. DP Array: Create array dp of size amount + 1 filled with 0. Set dp[0] = 1 (1 way to make amount 0).
  2. Outer Coin Loop: Iterate coin in coins FIRST:
    • Iterate $i$ from coin to amount:
    • dp[i] += dp[i - coin].
  3. Result: dp[amount] holds the total distinct combination count.

Why Outer Coin Loop Matters

Looping coin in the outer loop ensures coin ordering does not duplicate combinations (e.g., 1+2 and 2+1 count as 1 valid combination). Runs in $O(\text{amount} \times \text{coins.length})$ time and $O(\text{amount})$ space.

Example Walkthrough

Input

amount = 5, coins = [1, 2, 5]

Target amount 5.

Combinations

5=5, 5=2+2+1, 5=2+1+1+1, 5=1+1+1+1+1

4 distinct combinations.

Output

4

Total combination count.

Answer: Coin Change 2 combinations DP

function change(amount, coins) {
  const dp = new Array(amount + 1).fill(0);
  dp[0] = 1;
  for (const coin of coins) {
    for (let i = coin; i <= amount; i++) {
      dp[i] += dp[i - coin];
    }
  }
  return dp[amount];
}

Compute combination totals by iterating coins in the outer loop.

Key Takeaways
  • Outer coin loop counts unique combinations.

  • Outer amount loop would count permutations instead of combinations.

  • Runs in $O(A \cdot N)$ time and $O(A)$ space.

28. Subsets (Power Set)

Difficulty:MediumPattern:Backtracking / Decision TreeTime:O(n * 2^n)Space:O(n)

Given an integer array nums of unique elements, return all possible subsets (the power set).

How It Works & Algorithmic Design

Solves using Backtracking / Decision Tree Search:

  1. Decision Tree: At each element index start, decide to either include nums[start] in the current subset or exclude it.
  2. Backtracking Function backtrack(start, currentPath):
    • Save copy of currentPath into result.
    • Loop $i$ from start to nums.length - 1:
      • Include: currentPath.push(nums[i]).
      • Recurse: backtrack(i + 1, currentPath).
      • Backtrack: currentPath.pop().

Why This Approach Works Best

An array of size $n$ has $2^n$ unique subsets. Backtracking generates all combinations systematically in $O(n \cdot 2^n)$ time and $O(n)$ call-stack space.

Example Walkthrough

Input

[1, 2, 3]

3 distinct numbers.

Output Set Count

2^3 = 8 subsets

[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]].

Answer: Power set generation using Backtracking

function subsets(nums) {
  const res = [];
  function backtrack(start, path) {
    res.push([...path]);
    for (let i = start; i < nums.length; i++) {
      path.push(nums[i]);
      backtrack(i + 1, path);
      path.pop();
    }
  }
  backtrack(0, []);
  return res;
}

Systematically explore subset inclusions and exclusions using recursive backtracking.

Key Takeaways
  • Backtracking builds solution state incrementally.

  • Power set size is always $2^n$ for $n$ distinct elements.

  • Always copy state ([...path]) before storing in result.

29. Permutations

Difficulty:MediumPattern:Backtracking / Visited StateTime:O(n * n!)Space:O(n)

Given an array nums of distinct integers, return all the possible permutations in any order.

How It Works & Algorithmic Design

Solves using Backtracking with Visited State Tracking:

  1. Visited Tracking: Maintain a boolean array or set visited to avoid reusing the same element in a single permutation.
  2. Backtrack Loop:
    • If currentPath.length === nums.length, save copy of currentPath into res and return.
    • Loop $i$ from $0$ to nums.length - 1:
      • If visited[i] is true, continue.
      • Set visited[i] = true, push nums[i] into currentPath.
      • Recurse: backtrack().
      • Undo: visited[i] = false, currentPath.pop().

Why This Approach Works Best

Generates all $n!$ unique orderings systematically in $O(n \cdot n!)$ time.

Example Walkthrough

Input

[1, 2, 3]

3 distinct numbers.

Permutation Count

3! = 6 permutations

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]].

Answer: Permutation generation using Backtracking

function permute(nums) {
  const res = [], visited = new Array(nums.length).fill(false);
  function backtrack(path) {
    if (path.length === nums.length) {
      res.push([...path]);
      return;
    }
    for (let i = 0; i < nums.length; i++) {
      if (visited[i]) continue;
      visited[i] = true;
      path.push(nums[i]);
      backtrack(path);
      path.pop();
      visited[i] = false;
    }
  }
  backtrack([]);
  return res;
}

Explore all $n!$ element arrangements using recursive backtracking and visited state tracking.

Key Takeaways
  • Tracks visited indices to prevent reusing elements in the same permutation.

  • Total number of generated permutations is $n!$.

  • Time complexity $O(n \cdot n!)$.

30. Trapping Rain Water

Difficulty:HardPattern:Two Pointers / Boundary MaxTime:O(n)Space:O(1)

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

How It Works & Algorithmic Design

Solves using Two Pointers Inward Traversal:

  1. Pointers & Max Tracks: left = 0, right = height.length - 1, leftMax = 0, rightMax = 0, totalWater = 0.
  2. Converging Loop (While left < right):
    • If height[left] < height[right]:
      • If height[left] >= leftMax, update leftMax = height[left].
      • Else, accumulate trapped water: totalWater += leftMax - height[left].
      • Increment left++.
    • Else:
      • If height[right] >= rightMax, update rightMax = height[right].
      • Else, accumulate trapped water: totalWater += rightMax - height[right].
      • Decrement right--.
  3. Return: totalWater.

Why This Approach Works Best

Water trapping depends on Math.min(leftMax, rightMax) - currentHeight. Moving the smaller height pointer guarantees correct water boundary calculations in single-pass linear $O(n)$ time and $O(1)$ space.

Example Walkthrough

Input

height = [0,1,0,2,1,0,1,3,2,1,2,1]

Elevation bar graph.

Trapped Water Sum

1 unit at idx 2 + 1 at idx 4 + 2 at idx 5 + 1 at idx 6 + 1 at idx 9 = 6 units

Calculates trapped water volume.

Output

6

Total trapped rain water units.

Answer: Trapping Rain Water using Two Pointers

function trap(height) {
  let left = 0, right = height.length - 1;
  let leftMax = 0, rightMax = 0, totalWater = 0;
  while (left < right) {
    if (height[left] < height[right]) {
      if (height[left] >= leftMax) leftMax = height[left];
      else totalWater += leftMax - height[left];
      left++;
    } else {
      if (height[right] >= rightMax) rightMax = height[right];
      else totalWater += rightMax - height[right];
      right--;
    }
  }
  return totalWater;
}

Track leftMax and rightMax while moving inward from the shorter boundary.

Key Takeaways
  • Water level at any bar is bounded by min(leftMax, rightMax) - barHeight.

  • Moving the shorter pointer ensures the smaller maximum boundary is known.

  • Single-pass solution achieving linear $O(n)$ time and $O(1)$ space.