50 Essential Data Structures & Algorithms Coding Questions
A 50-question DSA problem bank covering arrays, strings, linked lists, trees, graphs, dynamic programming, and algorithm paradigms using the codeExample format.
Q1: Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. Use a Hash Map to reduce lookup complexity to O(1).
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]As we iterate through nums, we calculate the complement required to reach target. If the complement exists in our map, we immediately return its stored index and the current index.
Hash Map provides O(n) time complexity by storing complement values during iteration.
Avoids the naive O(n²) nested loop approach.
What is the time and space complexity of the Hash Map solution for Two Sum?
Q2: Valid Parentheses
Given a string containing (), {}, and [], determine if the input string is valid using a Stack data structure.
function isValid(s) {
const stack = [];
const pairs = { ')': '(', '}': '{', ']': '[' };
for (let char of s) {
if (char === '(' || char === '{' || char === '[') {
stack.push(char);
} else {
if (stack.pop() !== pairs[char]) return false;
}
}
return stack.length === 0;
}
console.log(isValid('({[]})')); // trueOpening brackets are pushed onto the stack. When a closing bracket is encountered, we pop the stack and verify that it matches the corresponding opening bracket type.
Stacks enforce Last-In, First-Out (LIFO) tracking for nested structure validations.
The string is invalid if an unexpected closing bracket appears or if brackets remain on the stack at the end.
What condition indicates an unclosed opening bracket after processing the entire string?
Q3: Reverse a Singly Linked List
Reverse a singly linked list in-place by reassigning the next pointers using three iteration references: prev, curr, and next.
function reverseList(head) {
let prev = null;
let curr = head;
while (curr !== null) {
let nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}At each step, we save curr.next, point curr.next backward to prev, advance prev to curr, and move curr to the saved nextTemp pointer.
Reverses pointers in linear O(n) time and O(1) auxiliary space.
Requires storing
curr.nextin a temporary pointer before updating node link.
Which reference becomes the new head of the reversed linked list upon loop completion?
Q4: Merge Two Sorted Lists
Merge two sorted linked lists into one single sorted list by creating a dummy node and chaining smaller node values iteratively.
function mergeTwoLists(l1, l2) {
const dummy = { val: 0, next: null };
let tail = dummy;
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2;
l2 = l2.next;
}
tail = tail.next;
}
tail.next = l1 !== null ? l1 : l2;
return dummy.next;
}Compares front nodes of both lists, attaches the smaller node to tail, and advances that list's pointer. Any remaining nodes are appended at the end.
A dummy head node simplifies boundary edge cases when building the merged list.
Runs in O(n + m) time complexity where n and m are lengths of the lists.
Why is a dummy node used at the start of the algorithm?
Q5: Binary Search
Search for a target value within a sorted array using the divide-and-conquer strategy, reducing the search space by half in each iteration.
function binarySearch(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const mid = Math.floor(left + (right - left) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
console.log(binarySearch([-1, 0, 3, 5, 9, 12], 9)); // 4Calculates mid index safely. If target is larger than nums[mid], discards the left half; otherwise discards the right half.
Requires a sorted array input.
Achieves logarithmic O(log n) time complexity.
Why is Math.floor(left + (right - left) / 2) preferred over Math.floor((left + right) / 2)?
Q6: Maximum Subarray (Kadane's Algorithm)
Find the contiguous subarray with the largest sum within an array of numbers using Kadane's dynamic programming algorithm.
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;
}
console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6 (subarray [4,-1,2,1])currentSum updates to either the current item alone or current item plus previous running sum, whichever is greater, while maxSum tracks global maximum.
Kadane's algorithm runs in linear O(n) time complexity with O(1) space.
At each element, decides whether to extend the current sum or start a new subarray sum.
What is the time complexity of Kadane's Algorithm?
Q7: Linked List Cycle Detection (Floyd's Tortoise and Hare)
Detect whether a linked list contains a cycle using two pointers moving at different speeds (slow moves 1 step, fast moves 2 steps).
function hasCycle(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}Slow moves one node at a time while fast moves two nodes. If there is no cycle, fast reaches null. If a cycle exists, fast meets slow inside the loop.
Floyd's algorithm detects cycles in O(n) time and O(1) space.
If a cycle exists, the fast pointer eventually catches up and equals the slow pointer.
What happens if Floyd's cycle detection is run on a linear list with no cycle?
Q8: Best Time to Buy and Sell Stock
Find the maximum profit possible from buying stock on one day and selling it on a future day given an array of daily stock prices.
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (let price of prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}
console.log(maxProfit([7, 1, 5, 3, 6, 4])); // 5 (Buy at 1, sell at 6)Tracks minPrice encountered up to the current day. Max profit is updated if selling today yields higher profit than previously recorded maximum.
Single pass algorithm maintaining lowest price seen so far.
Achieves O(n) time and O(1) auxiliary space complexity.
What profit is returned if stock prices strictly decrease continuously (e.g. [7, 6, 4, 3, 1])?
Q9: Invert Binary Tree
Invert or mirror a binary tree recursively by swapping left and right child pointers for every node in the tree.
function invertTree(root) {
if (root === null) return null;
const temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}Base case returns null. At each node, its left child receives the inverted right subtree and its right child receives the inverted left subtree.
Uses Depth-First Search (DFS) tree recursion.
Swaps
.leftand.rightpointers at every level.
What is the time complexity of inverting a binary tree with N nodes?
Q10: Valid Anagram
Given two strings s and t, return true if t is an anagram of s (contains exact same character frequencies).
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = {};
for (let char of s) {
count[char] = (count[char] || 0) + 1;
}
for (let char of t) {
if (!count[char]) return false;
count[char]--;
}
return true;
}
console.log(isAnagram('anagram', 'nagaram')); // trueIncrements character counts for string s and decrements for string t. If a character in t has zero count or doesn't exist, strings are not anagrams.
Return false early if string lengths differ.
Use a single frequency map or fixed 26-character array to count frequencies.
What is the space complexity if solving anagram verification using frequency map over ASCII/lowercase letters?
Q11: Maximum Depth of Binary Tree
Calculate the maximum depth (number of nodes along the longest path from root to leaf) of a binary tree recursively.
function maxDepth(root) {
if (root === null) return 0;
const leftDepth = maxDepth(root.left);
const rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}Recursively measures the depth of left and right child subtrees and returns the greater depth plus 1 for the current root node.
Depth equals
1 + max(depth(left), depth(right)).Base case for null nodes returns depth 0.
What is the worst-case space complexity of recursive maxDepth on a completely skewed tree?
Q12: Container With Most Water
Given $n$ non-negative integers representing vertical lines, find two lines that together with the x-axis form a container holding the maximum water.
function maxArea(height) {
let left = 0;
let right = height.length - 1;
let maxWater = 0;
while (left < right) {
const width = right - left;
const h = Math.min(height[left], height[right]);
maxWater = Math.max(maxWater, width * h);
if (height[left] < height[right]) left++;
else right--;
}
return maxWater;
}
console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])); // 49Calculates container area bounded by shorter line. Advances shorter boundary pointer inward since moving the taller pointer could never increase height area.
Two-pointer approach moving inward from left and right edges.
Always advance the pointer holding the shorter height to search for larger area candidates.
Why is the shorter pointer moved inward in each iteration step?
Q13: 3Sum Problem
Find all unique triplets in an array that sum to zero using sorting and two pointers.
function threeSum(nums) {
nums.sort((a, b) => a - b);
const result = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue; // Skip duplicates
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
result.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 result;
}
console.log(threeSum([-1, 0, 1, 2, -1, -4])); // [[-1, -1, 2], [-1, 0, 1]]Fixes item i and solves Two Sum for -nums[i] on the remaining sorted sub-array, skipping duplicate elements to ensure unique triplets.
Sort array first to enable two-pointer traversal and duplicate skipping.
Runs in O(n²) time complexity.
What step prevents returning duplicate triplet sets in the output array?
Q14: Climbing Stairs (Dynamic Programming)
You are climbing a staircase requiring $n$ steps. Each time you can climb 1 or 2 steps. In how many distinct ways can you climb to the top?
function climbStairs(n) {
if (n <= 2) return n;
let prev2 = 1;
let prev1 = 2;
for (let i = 3; i <= n; i++) {
let current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return prev1;
}
console.log(climbStairs(5)); // 8To reach step i, you can arrive from step i-1 or step i-2. Summing these options gives total ways, matching Fibonacci transitions.
Follows Fibonacci sequence progression: $dp[i] = dp[i-1] + dp[i-2]$.
Can be solved in O(n) time and O(1) space using dynamic programming space optimization.
What is the space complexity of the variable-tracking dynamic programming approach above?
Q15: Longest Substring Without Repeating Characters
Find the length of the longest substring without repeating characters using the Sliding Window pattern.
function lengthOfLongestSubstring(s) {
const seen = new Set();
let left = 0;
let maxLength = 0;
for (let right = 0; right < s.length; right++) {
while (seen.has(s[right])) {
seen.delete(s[left]);
left++;
}
seen.add(s[right]);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
console.log(lengthOfLongestSubstring('abcabcbb')); // 3 ('abc')Right pointer expands window. When duplicate character is detected, left pointer contracts window until duplicate is removed from set.
Sliding window uses two pointers (
left,right) and a Set/Map.Achieves O(n) linear time complexity.
What triggers the left window pointer to contract inward?
Q16: Binary Tree Level Order Traversal (BFS)
Perform level-order traversal on a binary tree using a Queue (Breadth-First Search) returning nodes grouped level by level.
function levelOrder(root) {
if (!root) return [];
const result = [];
const 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);
}
result.push(currentLevel);
}
return result;
}Queue processes nodes layer by layer. The inner loop iterates levelSize times to group current level values into a separate output subarray.
Breadth-First Search (BFS) processes nodes level by level using a queue.
Tracks level size (
queue.length) at loop start to process nodes layer by layer.
Which data structure is fundamentally required for Breadth-First Search (BFS)?
Q17: Coin Change (Dynamic Programming)
Find the minimum number of coins needed to make up a given amount using bottom-up 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 (let coin of coins) {
if (i - coin >= 0) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}
console.log(coinChange([1, 2, 5], 11)); // 3 (5 + 5 + 1)dp[i] stores min coins needed for amount i. Iterates through all available coins to find minimum coin combinations step by step.
Dynamic Programming lookup table array initialized to
Infinity.State transition:
dp[i] = min(dp[i], dp[i - coin] + 1).
What value does coinChange return if the target amount cannot be made by any coin combination?
Q18: Validate Binary Search Tree
Determine if a given binary tree is a valid Binary Search Tree (BST) where left subtree values are strictly smaller and right subtree values are strictly larger than root.
function isValidBST(root, min = null, max = null) {
if (root === null) 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);
}Validates node value against allowable min and max constraints. When stepping left, updates max bound to current node value; when stepping right, updates min bound.
Pass lower and upper boundary bounds recursively during DFS traversal.
Checking only immediate child nodes is insufficient; subtrees must satisfy full boundary limits.
Why is checking if root.left.val < root.val and root.right.val > root.val insufficient for verifying a BST?
Q19: Number of Islands (Graph DFS/BFS)
Count the number of distinct islands in a 2D grid of '1's (land) and '0's (water) using Depth-First Search (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'; // Mark as visited by sinking land
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;
}Scans every cell. When encountering land ('1'), increments island count and starts DFS flood-fill to mark all connected land cells as visited ('0').
Treat grid as an undirected graph and sink visited land nodes by mutating
'1'to'0'.Increments island count on finding an unvisited
'1'and triggers flood-fill DFS.
Why does the DFS function mutate grid[r][c] = '0' during flood fill?
Q20: Kth Largest Element in an Array
Find the $k$-th largest element in an unsorted array using QuickSelect partitioning algorithm or Min-Heap.
function findKthLargest(nums, k) {
const targetIndex = nums.length - k;
function quickSelect(left, right) {
const pivot = nums[right];
let p = left;
for (let i = left; i < right; i++) {
if (nums[i] <= pivot) {
[nums[i], nums[p]] = [nums[p], nums[i]];
p++;
}
}
[nums[p], nums[right]] = [nums[right], nums[p]];
if (p === targetIndex) return nums[p];
if (p < targetIndex) return quickSelect(p + 1, right);
return quickSelect(left, p - 1);
}
return quickSelect(0, nums.length - 1);
}
console.log(findKthLargest([3, 2, 1, 5, 6, 4], 2)); // 5Partitions array around pivot. If pivot index equals target position (length - k), returns target value; otherwise selectively recurses into the target partition half.
QuickSelect provides average O(n) time complexity.
Avoids full array sorting which takes O(n log n).
What is the average time complexity of QuickSelect?
Q21: Course Schedule (Topological Sort / Cycle Detection)
Determine if you can finish all courses given prerequisite pairs using Topological Sort / Kahn's Algorithm (In-degree array + BFS).
function canFinish(numCourses, prerequisites) {
const inDegree = new Array(numCourses).fill(0);
const adjList = new Map();
for (let [course, pre] of prerequisites) {
if (!adjList.has(pre)) adjList.set(pre, []);
adjList.get(pre).push(course);
inDegree[course]++;
}
const queue = [];
for (let i = 0; i < numCourses; i++) {
if (inDegree[i] === 0) queue.push(i);
}
let processedCount = 0;
while (queue.length > 0) {
const current = queue.shift();
processedCount++;
const neighbors = adjList.get(current) || [];
for (let neighbor of neighbors) {
inDegree[neighbor]--;
if (inDegree[neighbor] === 0) queue.push(neighbor);
}
}
return processedCount === numCourses;
}
console.log(canFinish(2, [[1, 0]])); // trueCalculates in-degree counts for each node. Courses with 0 prerequisites enter the BFS queue. Decrements in-degrees of dependent courses as completed; returns true if all courses can be processed.
If a directed graph contains a cycle, topological sorting is impossible.
Kahn's algorithm tracks in-degrees of nodes to identify valid task processing order.
What condition indicates that prerequisites contain a cyclic dependency loop?
Q22: Word Search (Backtracking)
Determine if a target word exists in a 2D board of letters by constructing adjacent character paths using Backtracking DFS.
function exist(board, word) {
const rows = board.length;
const cols = board[0].length;
function backtrack(r, c, index) {
if (index === word.length) return true;
if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] !== word[index]) {
return false;
}
const temp = board[r][c];
board[r][c] = '#'; // Mark cell as visited
const found = backtrack(r + 1, c, index + 1) ||
backtrack(r - 1, c, index + 1) ||
backtrack(r, c + 1, index + 1) ||
backtrack(r, c - 1, index + 1);
board[r][c] = temp; // Backtrack / restore state
return found;
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (backtrack(r, c, 0)) return true;
}
}
return false;
}Explores neighbors recursively if character matches word[index]. Restores cell state (board[r][c] = temp) when returning so other path branches can reuse the cell.
Backtracking recursively explores possibilities and reverts choice state upon reaching dead ends.
Temporarily mark board cells (e.g.
'#') during exploration to prevent self-revisiting.
Why must board[r][c] be restored back to its original character value before returning from backtrack()?
Q23: Merge K Sorted Lists
Merge $k$ sorted linked lists into one consolidated sorted list using Divide and Conquer or Min-Heap.
function mergeKLists(lists) {
if (!lists || lists.length === 0) return null;
while (lists.length > 1) {
const mergedLists = [];
for (let i = 0; i < lists.length; i += 2) {
const l1 = lists[i];
const l2 = i + 1 < lists.length ? lists[i + 1] : null;
mergedLists.push(mergeTwoLists(l1, l2));
}
lists = mergedLists;
}
return lists[0];
}
function mergeTwoLists(l1, l2) {
const dummy = { val: 0, next: null };
let tail = dummy;
while (l1 && l2) {
if (l1.val < l2.val) { tail.next = l1; l1 = l1.next; }
else { tail.next = l2; l2 = l2.next; }
tail = tail.next;
}
tail.next = l1 || l2;
return dummy.next;
}Pairs up lists and merges each pair using mergeTwoLists, halving the total number of lists each pass until only one sorted list remains.
Divide and conquer merges pairs of lists iteratively.
Reduces time complexity to O(N log k) where N is total node count across k lists.
What is the time complexity of merging K sorted lists with total N nodes using Divide and Conquer?
Q24: Trapping Rain Water
Calculate how much water an elevation map can trap after raining using Two Pointers.
function trap(height) {
let left = 0;
let right = height.length - 1;
let leftMax = 0;
let rightMax = 0;
let water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) leftMax = height[left];
else water += leftMax - height[left];
left++;
} else {
if (height[right] >= rightMax) rightMax = height[right];
else water += rightMax - height[right];
right--;
}
}
return water;
}
console.log(trap([0,1,0,2,1,0,1,3,2,1,2,1])); // 6Maintains leftMax and rightMax bounds. Advances shorter pointer inward and adds trapped water based on difference between local max bound and bar height.
Water trapped at any position is bounded by $\min(\text{maxLeft}, \text{maxRight}) - \text{height}[i]$.
Two pointers allow tracking boundary bounds in O(n) time and O(1) space.
What determines the water level trapped above height[left] when height[left] < height[right]?
Q25: Median of Two Sorted Arrays
Find the median of two sorted arrays nums1 and nums2 in O(log(min(m, n))) time complexity using Binary Search partitioning.
function findMedianSortedArrays(nums1, nums2) {
if (nums1.length > nums2.length) {
return findMedianSortedArrays(nums2, nums1); // Ensure nums1 is smaller
}
const m = nums1.length;
const n = nums2.length;
let low = 0, high = m;
while (low <= high) {
const partitionA = Math.floor((low + high) / 2);
const partitionB = Math.floor((m + n + 1) / 2) - partitionA;
const maxLeftA = partitionA === 0 ? -Infinity : nums1[partitionA - 1];
const minRightA = partitionA === m ? Infinity : nums1[partitionA];
const maxLeftB = partitionB === 0 ? -Infinity : nums2[partitionB - 1];
const minRightB = partitionB === n ? Infinity : nums2[partitionB];
if (maxLeftA <= minRightB && maxLeftB <= minRightA) {
if ((m + n) % 2 === 0) {
return (Math.max(maxLeftA, maxLeftB) + Math.min(minRightA, minRightB)) / 2;
} else {
return Math.max(maxLeftA, maxLeftB);
}
} else if (maxLeftA > minRightB) {
high = partitionA - 1;
} else {
low = partitionA + 1;
}
}
}
console.log(findMedianSortedArrays([1, 3], [2])); // 2.0Executes binary search on smaller array nums1 to find partition splits where left halves elements are smaller than right halves elements, giving median in O(log(min(m, n))) time.
Applies Binary Search on the smaller array to find a valid partition point.
Valid partition occurs when
maxLeftA <= minRightBandmaxLeftB <= minRightA.
Why is Binary Search performed specifically on the smaller of the two input arrays?
Q26: Merge Intervals
Given an array of intervals where intervals[i] = [start, end], merge all overlapping intervals and return an array of non-overlapping intervals that cover all intervals in the input.
function merge(intervals) {
if (!intervals.length) return [];
intervals.sort((a, b) => a[0] - b[0]);
const merged = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const current = intervals[i];
const lastMerged = merged[merged.length - 1];
if (current[0] <= lastMerged[1]) {
lastMerged[1] = Math.max(lastMerged[1], current[1]);
} else {
merged.push(current);
}
}
return merged;
}
console.log(merge([[1,3],[2,6],[8,10],[15,18]])); // [[1,6],[8,10],[15,18]]After sorting by start time, we iterate through intervals. If the current interval start is <= the previous interval end, we merge by expanding the previous end time; otherwise, we append the interval as a new non-overlapping range.
Sort intervals by start time first to enable linear single-pass merging.
Overlaps occur when the next interval's start time is less than or equal to the current interval's end time.
What is the time complexity of the Merge Intervals algorithm?
Q27: Insert Interval
You are given an array of non-overlapping intervals sorted by start time and a newInterval. Insert newInterval into the intervals such that the list remains sorted and non-overlapping.
function insert(intervals, newInterval) {
const result = [];
let i = 0;
const n = intervals.length;
// Add all intervals that end before newInterval starts
while (i < n && intervals[i][1] < newInterval[0]) {
result.push(intervals[i]);
i++;
}
// Merge all overlapping intervals with newInterval
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
result.push(newInterval);
// Add remaining intervals after newInterval
while (i < n) {
result.push(intervals[i]);
i++;
}
return result;
}
console.log(insert([[1,3],[6,9]], [2,5])); // [[1,5],[6,9]]Splits the process into three distinct phases: collecting left disjoint intervals, iteratively updating the min start and max end of overlapping bounds, and collecting right disjoint intervals.
Process non-overlapping intervals before the new interval, merge all overlapping ones, then append remaining non-overlapping intervals.
Can be solved in a single O(N) linear pass without explicit full re-sorting.
Why is explicit array sorting not required for the Insert Interval algorithm?
Q28: Non-overlapping Intervals
Given an array of intervals intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
function eraseOverlapIntervals(intervals) {
if (!intervals.length) return 0;
intervals.sort((a, b) => a[1] - b[1]); // Sort by end time
let count = 0;
let prevEnd = intervals[0][1];
for (let i = 1; i < intervals.length; i++) {
if (intervals[i][0] < prevEnd) {
count++; // Overlap detected; remove current interval
} else {
prevEnd = intervals[i][1]; // No overlap; update prevEnd
}
}
return count;
}
console.log(eraseOverlapIntervals([[1,2],[2,3],[3,4],[1,3]])); // 1Sorting by end times allows greedily keeping intervals that finish earliest. If the next interval starts before prevEnd, it must be removed to prevent overlap.
Greedy strategy: sort intervals by end time to preserve maximum remaining space.
Always pick the interval with the earliest end time to minimize collisions with future intervals.
Why do we sort by end time rather than start time for greedy interval scheduling?
Q29: Top K Frequent Elements
Given an integer array nums and an integer k, return the $k$ most frequent elements. Solve it in $O(n)$ time using Bucket Sort.
function topKFrequent(nums, k) {
const map = new Map();
for (let num of nums) {
map.set(num, (map.get(num) || 0) + 1);
}
const buckets = Array.from({ length: nums.length + 1 }, () => []);
for (let [num, freq] of map) {
buckets[freq].push(num);
}
const result = [];
for (let i = buckets.length - 1; i >= 0 && result.length < k; i--) {
if (buckets[i].length > 0) {
result.push(...buckets[i]);
}
}
return result.slice(0, k);
}
console.log(topKFrequent([1,1,1,2,2,3], 2)); // [1, 2]Counts occurrences in a Map, uses array indices as frequency buckets, and iterates backward from maximum possible frequency to extract top k items.
Bucket Sort groups elements into array indices matching their exact frequency count.
Achieves $O(n)$ linear time complexity, beating $O(n \log n)$ heap/sorting methods.
What determines the size of the buckets array in this Bucket Sort implementation?
Q30: Encode and Decode Strings
Design an algorithm to encode a list of strings to a single string and decode that single string back to the original list of strings.
function encode(strs) {
return strs.map(s => `${s.length}#${s}`).join('');
}
function decode(str) {
const result = [];
let i = 0;
while (i < str.length) {
let j = i;
while (str[j] !== '#') j++;
const length = parseInt(str.slice(i, j), 10);
i = j + 1;
result.push(str.slice(i, i + length));
i += length;
}
return result;
}
const encoded = encode(['lint', 'code', 'love', 'you']);
console.log(encoded); // '4#lint4#code4#love3#you'
console.log(decode(encoded)); // ['lint', 'code', 'love', 'you']Encoding formats strings as length#string. Decoding locates #, parses integer length, and slices exact character byte segments safely.
Prefix each string with its character length followed by a delimiter (e.g.
4#code).Avoids parsing errors caused by delimiter characters appearing inside original string content.
Why is length-prefixing preferable to simple character delimiting (e.g. comma separation)?