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
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:
- Matching Map: Define a map of closing brackets to their corresponding opening brackets (
')': '(','}' : '{',']': '['). - Stack Operations: Iterate through character
chin strings:- If
chis an opening bracket ((,{,[), push it onto the stack. - If
chis a closing bracket, check the stack top. If the stack is empty orstack.pop()does not equal the matching opening bracket, the string is invalid (return false).
- If
- Final Check: After processing all characters, return
trueifstack.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
"()[]{}"
Valid balanced string.
Push '(' -> Pop '(' on ')' | Push '[' -> Pop '[' on ']' | Push '{' -> Pop '{' on '}'
Stack becomes empty at end.
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.
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
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:
- Pointers: Set
left = 0,right = nums.length - 1. - Mid Calculation: Compute
mid = Math.floor((left + right) / 2)(orleft + Math.floor((right - left) / 2)to prevent overflow in fixed integer types). - Halving Condition:
- If
nums[mid] === target, returnmid. - If
nums[mid] < target, discard left half:left = mid + 1. - If
nums[mid] > target, discard right half:right = mid - 1.
- If
- Failure: Return
-1ifleft > 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
nums = [-1, 0, 3, 5, 9, 12], target = 9
Sorted array input.
left=0, right=5 -> mid=2 (nums[2]=3). 3 < 9 -> left=3.
Discards left half.
left=3, right=5 -> mid=4 (nums[4]=9). Match found!
Target identified at index 4.
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.
Binary search requires the input array to be pre-sorted.
Use
left + (right - left) / 2to 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
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:
- Variables: Track
minPrice = InfinityandmaxProfit = 0. - Iteration: Loop through each stock price in
prices:- If the current price is lower than
minPrice, updateminPrice = price. - Otherwise, calculate potential profit:
price - minPrice. If this profit exceedsmaxProfit, updatemaxProfit.
- If the current price is lower than
- Return: Return
maxProfitafter 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
prices = [7, 1, 5, 3, 6, 4]
Daily stock prices.
7 (min=7) -> 1 (min=1) -> 5 (profit=4) -> 3 -> 6 (profit=5, max=5) -> 4
Tracks minPrice and maxProfit concurrently.
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.
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)
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:
- State Definition: At index $i$, decide whether to add
nums[i]to the existing subarray or start a brand new subarray starting atnums[i]. - Transition Formula:
currentSum = Math.max(nums[i], currentSum + nums[i]). - Global Track:
maxSum = Math.max(maxSum, currentSum). - Initialization: Set
currentSum = nums[0]andmaxSum = 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
[-2, 1, -3, 4, -1, 2, 1, -5, 4]
Array containing negative and positive integers.
Subarray [4, -1, 2, 1] gives currentSum=6, which is the highest recorded.
Restarts subarray when current sum drops below current element.
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.
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
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:
- Pointers: Position
left = 0andright = height.length - 1. - Area Calculation:
width = right - left. Area =Math.min(height[left], height[right]) * width. - Max Update:
maxWater = Math.max(maxWater, area). - 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
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Heights of vertical lines.
Index 1 (height 8) and Index 8 (height 7)
Width = 8 - 1 = 7. Area = min(8, 7) * 7 = 49.
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.
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
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:
- Pointers: Maintain a sliding window defined by left boundary
leftand right boundaryright. - Map Index Tracking: Use a Hash Map
charIndexMapto store the last seen index of each character. - Expansion & Contraction: Expand
rightacross strings:- If character
s[right]was seen inside the current window (charIndexMap[s[right]] >= left), updateleft = charIndexMap[s[right]] + 1to skip past the repeating character. - Update
charIndexMap[s[right]] = right. - Calculate window size (
right - left + 1) and updatemaxLength.
- If character
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
s = "abcabcbb"
Target string.
"abc" (len=3) -> 'a' repeats at idx 3 -> move left to idx 1 ("bca") -> len=3
Sliding window dynamically adjusts left edge.
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.
Store character indices to jump
leftpointer 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
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:
- Sort: Sort intervals based on their start times (
interval[0]). This brings overlapping candidate intervals next to each other. - 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 updatinglastMerged.end = Math.max(lastMerged.end, interval.end). - Otherwise, no overlap; push
intervalintomerged.
- Get
- Initialize
- 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
[[1,3],[2,6],[8,10],[15,18]]
List of unmerged interval pairs.
[1,3] and [2,6] overlap (2 <= 3) -> Merge to [1,6]. [8,10] and [15,18] do not overlap.
Combines overlapping ranges.
[[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.
Sorting by start time ensures overlapping candidates are adjacent.
Use
Math.maxon end points to handle fully enclosed sub-intervals.Time complexity is dominated by sorting: $O(n \log n)$.
08. Rotate Image (2D Matrix)
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:
- 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]withmatrix[j][i].
- For every $i$ from $0$ to $n-1$ and $j$ from $i+1$ to $n-1$, swap
- Step 2: Reverse Each Row:
- For each row $i$, reverse elements horizontally (
leftandrightpointers swappingmatrix[i][left]andmatrix[i][right]).
- For each row $i$, reverse elements horizontally (
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
[[1,2,3],[4,5,6],[7,8,9]]
3x3 matrix.
[[1,4,7],[2,5,8],[3,6,9]]
Rows converted to columns.
[[7,4,1],[8,5,2],[9,6,3]]
Each row reversed horizontally.
[[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.
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
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:
- 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"). - Map Setup: Maintain a Hash Map where key =
sortedStringKeyand value =array of original strings. - Grouping: Loop through each string
sinstrs:- Compute
sortedKey = s.split('').sort().join(''). - Append
stomap[sortedKey].
- Compute
- 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
["eat","tea","tan","ate","nat","bat"]
List of unsorted strings.
"aet": ["eat","tea","ate"] | "ant": ["tan","nat"] | "abt": ["bat"]
Grouped by canonical sorted string key.
[["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.
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
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:
- Left Products Pass: Create result array
res. Setres[0] = 1. For $i$ from $1$ to $n-1$, computeres[i] = res[i - 1] * nums[i - 1](stores product of all elements to the left of $i$). - 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].
- Return:
rescontains 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
nums = [1, 2, 3, 4]
Target input.
res = [1, 1, 2, 6]
Products of elements to the left.
res = [24, 12, 8, 6]
Multiplied by suffix running products.
[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.
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
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:
- Sort: Sort array
numsin ascending order. - Fixed Loop: Loop pivot index $i$ from $0$ to $n-3$:
- Skip duplicate pivot values (
if (i > 0 && nums[i] === nums[i - 1]) continue).
- Skip duplicate pivot values (
- 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 forleftandright(left++,right--). - If
sum < 0, moveleft++. - If
sum > 0, moveright--.
- Compute
Why This Approach Works Best
Sorting allows $O(n^2)$ time execution while efficiently preventing duplicate triplets.
Example Walkthrough
[-1, 0, 1, 2, -1, -4]
Unsorted array.
[-4, -1, -1, 0, 1, 2]
Sorted for pointer search.
[[-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.
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
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:
- Compute
mid = left + (right - left) / 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).
- Left Half Sorted: If
- Repeat until
left > rightor 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
nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Rotated sorted array.
left=0, right=6, mid=3 (nums[3]=7). Left half [4..7] sorted. 0 not in [4..7] -> left=4.
Searches right partition.
left=4, right=6, mid=4 (nums[4]=0). Match!
Found at index 4.
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.
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
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:
- DP Array: Create array
dpof sizeamount + 1, filled withInfinity. Setdp[0] = 0(0 coins needed for amount 0). - 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).
- Loop each coin in
- 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
coins = [1, 2, 5], amount = 11
Target total 11.
dp[11] = min(dp[10]+1, dp[9]+1, dp[6]+1) = 3 (5 + 5 + 1)
Minimum coins needed.
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.
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
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:
- Base Cases: To reach step 1 = 1 way. Step 2 = 2 ways (1+1, 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). - Space Optimization: Maintain two variables
prev2 = 1,prev1 = 2and 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
n = 3
3 steps.
1+1+1, 1+2, 2+1
Total 3 distinct paths.
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.
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
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:
- 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).
- Option 1: Rob House $i$ $\to$ gain
- DP Formula:
curr = Math.max(prev1, prev2 + money[i]). - State Update: Advance
prev2 = prev1andprev1 = 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
[2, 7, 9, 3, 1]
Money in each house.
Rob house 1 ($2) + house 3 ($9) + house 5 ($1) = 12
Non-adjacent selection.
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.
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
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:
- Pointers: Maintain
prev = null,curr = head, andnext = null. - Traversal Loop (While
curr !== null):- Save next node:
next = curr.next. - Reverse pointer direction:
curr.next = prev. - Shift pointers forward:
prev = curr,curr = next.
- Save next node:
- Return:
prevnow 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
1 -> 2 -> 3 -> 4 -> null
Singly linked list.
null <- 1 <- 2 <- 3 <- 4 (head=4)
Pointers reversed in place.
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.
Store
curr.nextbefore overwriting the node's pointer.Iterative reversal works in $O(n)$ time and $O(1)$ space.
Return
prevas the new head whencurrreachesnull.
17. Linked List Cycle Detection (Floyd's Algorithm)
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:
- Pointers: Initialize
slow = headandfast = head. - Traversal: Advance
slowby 1 step (slow = slow.next) andfastby 2 steps (fast = fast.next.next). - Meeting Point: If a cycle exists, the fast pointer will eventually catch up and equal the slow pointer (
slow === fast$\to$ returntrue). - Termination: If
fast === nullorfast.next === null, a list tail was reached without a cycle $\to$ returnfalse.
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
3 -> 2 -> 0 -> -4 (points back to 2)
Linked list with cycle.
Slow steps by 1, Fast steps by 2 -> Fast overlaps Slow inside loop.
Pointers meet inside the loop.
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.
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
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:
- Dummy Head: Create a
dummysentinel node and pointertail = dummy. - Compare & Link (While
list1 !== nullandlist2 !== null):- If
list1.val <= list2.val, settail.next = list1andlist1 = list1.next. - Else, set
tail.next = list2andlist2 = list2.next. - Advance
tail = tail.next.
- If
- Attach Remainder:
tail.next = list1 !== null ? list1 : list2. - Return:
dummy.nextholds 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
list1 = 1->2->4, list2 = 1->3->4
Two sorted lists.
1 (from l1) -> 1 (from l2) -> 2 (l1) -> 3 (l2) -> 4 (l1) -> 4 (l2)
Interleaves nodes in sorted order.
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.
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
Given the root of a binary tree, return its maximum depth.
How It Works & Algorithmic Design
Solves using Recursive Depth-First Search (DFS):
- Base Case: If
root === null, return0. - Recursive Decomposition:
- Compute left subtree depth:
leftDepth = maxDepth(root.left). - Compute right subtree depth:
rightDepth = maxDepth(root.right).
- Compute left subtree depth:
- 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
[3, 9, 20, null, null, 15, 7]
Binary tree root.
Node 3 -> max(depth(9), depth(20)) + 1 = max(1, 2) + 1 = 3
Calculates depth bottom-up.
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.
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
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:
- Base Case: If
root === null, returnnull. - Swap Children: Swap
root.leftandroot.rightusing a temporary variable. - Recursive Step:
invertTree(root.left).invertTree(root.right).
- Return: Return
rootafter 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
[4, 2, 7, 1, 3, 6, 9]
Original binary tree.
[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.
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
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:
- 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). - 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).
- Base Case:
Why This Approach Works Best
Validating global bounds (min, max) prevents invalid BST topologies where deep right sub-nodes violate ancestor limits.
Example Walkthrough
[5, 1, 4, null, null, 3, 6]
Invalid BST.
Node 3 is in right subtree of 5, but 3 < 5.
Range check fails.
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.
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
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:
- Queue Setup: Initialize a FIFO queue
queue = [root]. - Level Loop: While queue is not empty:
- Get
levelSize = queue.length. - Create
currentLevel = []. - Loop
levelSizetimes:- Dequeue
node = queue.shift(). - Add
node.valtocurrentLevel. - Push non-null
node.leftandnode.rightto queue.
- Dequeue
- Push
currentLeveltoresult.
- Get
- Return:
resultcontains 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
[3, 9, 20, null, null, 15, 7]
Binary tree root.
[[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.
Lock
levelSize = queue.lengthbefore 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
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:
- Base Cases: If
root === nullorroot === porroot === q, returnroot. - Recurse:
left = lowestCommonAncestor(root.left, p, q).right = lowestCommonAncestor(root.right, p, q).
- LCA Decision:
- If both
left !== nullandright !== null,pandqexist in separate subtrees ofroot$\to$rootis the LCA! - If only one side is non-null, return that non-null side (
left || right).
- If both
Why This Approach Works Best
Post-order traversal evaluates child subtrees first, correctly bubbling up common ancestor points in $O(n)$ time.
Example Walkthrough
root = [3, 5, 1, 6, 2, 0, 8], p = 5, q = 1
Target nodes 5 and 1.
Left subtree contains 5, Right subtree contains 1 -> Ancestor node is 3.
Root 3 splits target nodes.
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.
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
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):
- Grid Traversal: Loop through every cell
grid[r][c]. - 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.
- Increment
- Return:
islandCountafter 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
[["1","1","0"],["1","1","0"],["0","0","1"]]
2D land map.
Island 1 at (0,0) sinks connected land at (0,1),(1,0),(1,1). Island 2 found at (2,2).
Counts connected components.
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.
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
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:
- Min-Heap Maintainer: Initialize a Min-Heap data structure.
- Iteration: Loop through each
numinnums:- Push
numinto the min-heap. - If
heap.size > k, pop the smallest root element.
- Push
- 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
nums = [3, 2, 1, 5, 6, 4], k = 2
Find 2nd largest element.
Pushes items and keeps top 2 largest -> Heap becomes [5, 6]
Heap root is 5.
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.
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
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:
- Frequency Counting: Build a Hash Map
freqMapcounting occurrences of each number. - Bucket Array: Create an array of lists
bucketsof sizenums.length + 1where index $i$ represents frequency $i$. - Bucket Populating: For
[num, freq]infreqMap, appendnumintobuckets[freq]. - Gather Top K: Loop backwards from bucket index
nums.lengthdown to1and collect elements untilresult.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
nums = [1,1,1,2,2,3], k = 2
Frequencies: 1->3, 2->2, 3->1.
bucket[3]=[1], bucket[2]=[2], bucket[1]=[3]
Elements bucketed by frequency.
[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.
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)
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:
- DP Array: Create array
dpof sizeamount + 1filled with0. Setdp[0] = 1(1 way to make amount 0). - Outer Coin Loop: Iterate
coinincoinsFIRST:- Iterate $i$ from
cointoamount: dp[i] += dp[i - coin].
- Iterate $i$ from
- 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
amount = 5, coins = [1, 2, 5]
Target amount 5.
5=5, 5=2+2+1, 5=2+1+1+1, 5=1+1+1+1+1
4 distinct combinations.
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.
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)
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:
- Decision Tree: At each element index
start, decide to either includenums[start]in the current subset or exclude it. - Backtracking Function
backtrack(start, currentPath):- Save copy of
currentPathintoresult. - Loop $i$ from
starttonums.length - 1:- Include:
currentPath.push(nums[i]). - Recurse:
backtrack(i + 1, currentPath). - Backtrack:
currentPath.pop().
- Include:
- Save copy of
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
[1, 2, 3]
3 distinct numbers.
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.
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
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:
- Visited Tracking: Maintain a boolean array or set
visitedto avoid reusing the same element in a single permutation. - Backtrack Loop:
- If
currentPath.length === nums.length, save copy ofcurrentPathintoresand return. - Loop $i$ from $0$ to
nums.length - 1:- If
visited[i]is true, continue. - Set
visited[i] = true, pushnums[i]intocurrentPath. - Recurse:
backtrack(). - Undo:
visited[i] = false,currentPath.pop().
- If
- If
Why This Approach Works Best
Generates all $n!$ unique orderings systematically in $O(n \cdot n!)$ time.
Example Walkthrough
[1, 2, 3]
3 distinct numbers.
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.
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
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:
- Pointers & Max Tracks:
left = 0,right = height.length - 1,leftMax = 0,rightMax = 0,totalWater = 0. - Converging Loop (While
left < right):- If
height[left] < height[right]:- If
height[left] >= leftMax, updateleftMax = height[left]. - Else, accumulate trapped water:
totalWater += leftMax - height[left]. - Increment
left++.
- If
- Else:
- If
height[right] >= rightMax, updaterightMax = height[right]. - Else, accumulate trapped water:
totalWater += rightMax - height[right]. - Decrement
right--.
- If
- If
- 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
height = [0,1,0,2,1,0,1,3,2,1,2,1]
Elevation bar graph.
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.
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.
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.