50 Topics
Chapter•210 Minutes

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

Hash Map Two Sum Solution
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.

Key Takeaways
  • Hash Map provides O(n) time complexity by storing complement values during iteration.

  • Avoids the naive O(n²) nested loop approach.

Knowledge Check

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.

Stack Parentheses Validator
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('({[]})')); // true

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

Key Takeaways
  • 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.

Knowledge Check

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.

Iterative Linked List Reversal
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.

Key Takeaways
  • Reverses pointers in linear O(n) time and O(1) auxiliary space.

  • Requires storing curr.next in a temporary pointer before updating node link.

Knowledge Check

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.

Sorted List Merge
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.

Key Takeaways
  • 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.

Knowledge Check

Why is a dummy node used at the start of the algorithm?

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.

Kadane's Algorithm Solution
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.

Key Takeaways
  • 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.

Knowledge Check

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

Floyd's Cycle Finding Algorithm
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.

Key Takeaways
  • 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.

Knowledge Check

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.

Max Profit Calculator
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.

Key Takeaways
  • Single pass algorithm maintaining lowest price seen so far.

  • Achieves O(n) time and O(1) auxiliary space complexity.

Knowledge Check

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.

Recursive Binary Tree Inversion
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.

Key Takeaways
  • Uses Depth-First Search (DFS) tree recursion.

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

Knowledge Check

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

Frequency Map Anagram Check
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')); // true

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

Key Takeaways
  • Return false early if string lengths differ.

  • Use a single frequency map or fixed 26-character array to count frequencies.

Knowledge Check

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.

Tree Maximum Depth (DFS)
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.

Key Takeaways
  • Depth equals 1 + max(depth(left), depth(right)).

  • Base case for null nodes returns depth 0.

Knowledge Check

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.

Two-Pointer Container Area Maximizer
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])); // 49

Calculates container area bounded by shorter line. Advances shorter boundary pointer inward since moving the taller pointer could never increase height area.

Key Takeaways
  • Two-pointer approach moving inward from left and right edges.

  • Always advance the pointer holding the shorter height to search for larger area candidates.

Knowledge Check

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.

Sorted Two-Pointer 3Sum
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.

Key Takeaways
  • Sort array first to enable two-pointer traversal and duplicate skipping.

  • Runs in O(n²) time complexity.

Knowledge Check

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?

DP Climbing Stairs Solution
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)); // 8

To reach step i, you can arrive from step i-1 or step i-2. Summing these options gives total ways, matching Fibonacci transitions.

Key Takeaways
  • 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.

Knowledge Check

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.

Sliding Window Substring Search
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.

Key Takeaways
  • Sliding window uses two pointers (left, right) and a Set/Map.

  • Achieves O(n) linear time complexity.

Knowledge Check

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.

BFS Level Order Traversal
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.

Key Takeaways
  • 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.

Knowledge Check

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.

Bottom-Up DP Coin Change
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.

Key Takeaways
  • Dynamic Programming lookup table array initialized to Infinity.

  • State transition: dp[i] = min(dp[i], dp[i - coin] + 1).

Knowledge Check

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.

BST Boundary Range Validation
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.

Key Takeaways
  • Pass lower and upper boundary bounds recursively during DFS traversal.

  • Checking only immediate child nodes is insufficient; subtrees must satisfy full boundary limits.

Knowledge Check

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

Grid DFS Flood Fill Island Counter
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').

Key Takeaways
  • 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.

Knowledge Check

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.

QuickSelect Partition Algorithm
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)); // 5

Partitions array around pivot. If pivot index equals target position (length - k), returns target value; otherwise selectively recurses into the target partition half.

Key Takeaways
  • QuickSelect provides average O(n) time complexity.

  • Avoids full array sorting which takes O(n log n).

Knowledge Check

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

Kahn's Algorithm BFS Topological Sort
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]])); // true

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

Key Takeaways
  • 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.

Knowledge Check

What condition indicates that prerequisites contain a cyclic dependency loop?

Q23: Merge K Sorted Lists

Merge $k$ sorted linked lists into one consolidated sorted list using Divide and Conquer or Min-Heap.

Divide and Conquer List Merger
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.

Key Takeaways
  • 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.

Knowledge Check

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.

Two-Pointer Water Trapping
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])); // 6

Maintains leftMax and rightMax bounds. Advances shorter pointer inward and adds trapped water based on difference between local max bound and bar height.

Key Takeaways
  • 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.

Knowledge Check

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.

Binary Search Partition Median Finder
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.0

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

Key Takeaways
  • Applies Binary Search on the smaller array to find a valid partition point.

  • Valid partition occurs when maxLeftA <= minRightB and maxLeftB <= minRightA.

Knowledge Check

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.

Interval Sorting and Merging
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.

Key Takeaways
  • 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.

Knowledge Check

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.

Linear Insert and Merge Interval
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.

Key Takeaways
  • 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.

Knowledge Check

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.

Greedy End-Time Interval Removal
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]])); // 1

Sorting by end times allows greedily keeping intervals that finish earliest. If the next interval starts before prevEnd, it must be removed to prevent overlap.

Key Takeaways
  • 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.

Knowledge Check

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.

Bucket Sort Top K Frequent
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.

Key Takeaways
  • 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.

Knowledge Check

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.

Length-Prefix String Serialization
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.

Key Takeaways
  • 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.

Knowledge Check

Why is length-prefixing preferable to simple character delimiting (e.g. comma separation)?