Module 1 · Drill 1 · five reps

The two-sum family

Five variations on the same problem. Each one twists a constraint and forces a different optimization. By the end you should be able to recognize the family on sight and pick the right tool in seconds.

1 — Two Sum (classic)

Unsorted array, exactly one pair, return the indices. Hash-map index. O(n) time, O(n) space.

2 — Two Sum II (sorted input)

Same as above, but the array is sorted ascending. Now you can do it in O(1) extra space using two converging pointers. This is the version that comes up at FAANG L5 specifically because the optimal solution is different.

3 — Three Sum

Find all unique triplets (a, b, c) with a + b + c == 0. Sort first; for each i, use two-pointer on the rest. O(n²) time, O(1) space (excluding output). The skip-duplicates step is the part that bites people.

4 — Two Sum — count of pairs

Variation: how many unordered pairs sum to the target? Now you need to use a frequency map and watch out for the special case x == target/2 where you pair within the same value.

5 — Subarray Sum Equals K (hash + prefix-sum)

Different family member. Count contiguous subarrays summing to k. Brute is O(n²); the elegant move is "prefix sums + hash map of seen prefix sums," giving O(n). When you see "subarray sum equals X" — this is the move.

Solutions

1 — Two Sum (classic, hash-map index)

def two_sum(nums, target):
    seen = {}        # value -> index
    for i, x in enumerate(nums):
        comp = target - x
        if comp in seen:
            return [seen[comp], i]
        seen[x] = i
    return []
  
function twoSum(nums, target) {
  const seen = new Map();
  for (let i = 0; i < nums.length; i++) {
    const comp = target - nums[i];
    if (seen.has(comp)) return [seen.get(comp), i];
    seen.set(nums[i], i);
  }
  return [];
}
  
function twoSum(nums: number[], target: number): number[] {
  const seen = new Map<number, number>();
  for (let i = 0; i < nums.length; i++) {
    const comp = target - nums[i];
    if (seen.has(comp)) return [seen.get(comp)!, i];
    seen.set(nums[i], i);
  }
  return [];
}
  
O(n) time, O(n) space. Trade O(n) space for O(1) complement lookup. The "seen" map is built lazily; we look up before inserting so the same element can't pair with itself.

2 — Two Sum II (sorted, two-pointer)

def two_sum_sorted(nums, target):
    i, j = 0, len(nums) - 1
    while i < j:
        s = nums[i] + nums[j]
        if s == target: return [i, j]
        if s < target: i += 1
        else: j -= 1
    return []
  
function twoSumSorted(nums, target) {
  let i = 0, j = nums.length - 1;
  while (i < j) {
    const s = nums[i] + nums[j];
    if (s === target) return [i, j];
    if (s < target) i++; else j--;
  }
  return [];
}
  
function twoSumSorted(nums: number[], target: number): number[] {
  let i = 0, j = nums.length - 1;
  while (i < j) {
    const s = nums[i] + nums[j];
    if (s === target) return [i, j];
    if (s < target) i++; else j--;
  }
  return [];
}
  
O(n) time, O(1) space. The sorted-input version doesn't need a hash map — the structure tells us which pointer to move. This is the version that earns the senior signal in interviews because it knows its constraint and uses it.

3 — Three Sum

def three_sum(nums):
    nums = sorted(nums)
    out = []
    n = len(nums)
    for i in range(n - 2):
        if i > 0 and nums[i] == nums[i-1]: continue   # skip duplicate i
        j, k = i + 1, n - 1
        while j < k:
            s = nums[i] + nums[j] + nums[k]
            if s == 0:
                out.append([nums[i], nums[j], nums[k]])
                j += 1; k -= 1
                while j < k and nums[j] == nums[j-1]: j += 1   # skip dup j
                while j < k and nums[k] == nums[k+1]: k -= 1   # skip dup k
            elif s < 0: j += 1
            else: k -= 1
    return out
  
function threeSum(nums) {
  nums = nums.slice().sort((a, b) => a - b);
  const out = [];
  for (let i = 0; i < nums.length - 2; i++) {
    if (i > 0 && nums[i] === nums[i-1]) continue;
    let j = i + 1, k = nums.length - 1;
    while (j < k) {
      const s = nums[i] + nums[j] + nums[k];
      if (s === 0) {
        out.push([nums[i], nums[j], nums[k]]);
        j++; k--;
        while (j < k && nums[j] === nums[j-1]) j++;
        while (j < k && nums[k] === nums[k+1]) k--;
      } else if (s < 0) j++;
      else k--;
    }
  }
  return out;
}
  
function threeSum(nums: number[]): number[][] {
  const a = nums.slice().sort((x, y) => x - y);
  const out: number[][] = [];
  for (let i = 0; i < a.length - 2; i++) {
    if (i > 0 && a[i] === a[i-1]) continue;
    let j = i + 1, k = a.length - 1;
    while (j < k) {
      const s = a[i] + a[j] + a[k];
      if (s === 0) {
        out.push([a[i], a[j], a[k]]);
        j++; k--;
        while (j < k && a[j] === a[j-1]) j++;
        while (j < k && a[k] === a[k+1]) k--;
      } else if (s < 0) j++;
      else k--;
    }
  }
  return out;
}
  
O(n²) time, O(1) extra space (excluding output). Sort first; for each i, two-pointer the rest. The skip-duplicates step on each of i, j, k is what gets the unique-triplets requirement right — it's also where most candidates trip.

4 — Pair count for target

def pair_count(nums, target):
    seen = {}
    count = 0
    for x in nums:
        comp = target - x
        if comp in seen:
            count += seen[comp]
        seen[x] = seen.get(x, 0) + 1
    return count
  
function pairCount(nums, target) {
  const seen = new Map();
  let count = 0;
  for (const x of nums) {
    const comp = target - x;
    if (seen.has(comp)) count += seen.get(comp);
    seen.set(x, (seen.get(x) || 0) + 1);
  }
  return count;
}
  
function pairCount(nums: number[], target: number): number {
  const seen = new Map<number, number>();
  let count = 0;
  for (const x of nums) {
    const comp = target - x;
    if (seen.has(comp)) count += seen.get(comp)!;
    seen.set(x, (seen.get(x) || 0) + 1);
  }
  return count;
}
  
O(n) time, O(n) space. Same family as Two Sum, but tracks counts in the map. A value seen N times before a complement appears contributes N pairs, not 1. The standard trap: the special case where x = target/2 — handled correctly here because we increment seen[x] only after counting, so x can't pair with itself within a single iteration.

5 — Subarray sum equals K

def subarray_sum(nums, k):
    seen = {0: 1}     # prefix sum 0 has been seen once (the empty prefix)
    prefix = 0
    count = 0
    for x in nums:
        prefix += x
        if prefix - k in seen:
            count += seen[prefix - k]
        seen[prefix] = seen.get(prefix, 0) + 1
    return count
  
function subarraySum(nums, k) {
  const seen = new Map([[0, 1]]);
  let prefix = 0, count = 0;
  for (const x of nums) {
    prefix += x;
    if (seen.has(prefix - k)) count += seen.get(prefix - k);
    seen.set(prefix, (seen.get(prefix) || 0) + 1);
  }
  return count;
}
  
function subarraySum(nums: number[], k: number): number {
  const seen = new Map<number, number>([[0, 1]]);
  let prefix = 0, count = 0;
  for (const x of nums) {
    prefix += x;
    if (seen.has(prefix - k)) count += seen.get(prefix - k)!;
    seen.set(prefix, (seen.get(prefix) || 0) + 1);
  }
  return count;
}
  
O(n) time, O(n) space. The elegant move: a subarray nums[i..j] sums to k iff prefix[j+1] - prefix[i] == k, which means prefix[i] == prefix[j+1] - k. So at each j+1, count how many earlier prefixes equal prefix[j+1] - k. Initializing seen[0] = 1 is the trick that handles "subarray starting at index 0."
Notebook prompt — the family

For the five drills, write the family relationship: each row is "input shape → tool of choice → Big-O." If you can recite this table from memory in three months, you've internalized the entire family.