Module 0 · Drill 2 · refactor reps

Optimize the brute

Five working-but-slow solutions. For each: state the brute Big-O, write the optimized version, run the tests, and explain (in your notebook) which trade you made.

How to use this drill

Start with the brute solution running and passing tests. Then rewrite it. The drill is the rewrite — the trade-off you talk yourself into.

1 — Has duplicate?

Given a list, return True if any value appears more than once. Brute is nested loops. Optimal trades space for time with a hash set.

2 — Sum of pairs equal to target

Return the count of unordered pairs (i, j) with i < j and nums[i] + nums[j] == target. Brute is O(n²). Optimal is O(n) with a hash map of value → count.

3 — Max in every window of size k

Given an array and a window size k, return the max of each contiguous window. Brute is O(n × k). Optimal is O(n) using a monotonic deque (we'll go deeper on this in Module 2 — try a Counter or sorted list first to get to O(n log k), and the deque later).

4 — First non-repeating character

Given a string, return the index of the first character that appears exactly once, or -1 if none. Brute is O(n²) — rescan for each character. Optimal is O(n) with a counter of frequencies.

5 — Group anagrams

Group strings that are anagrams of each other. Brute is O(n² · k) (compare every pair sorted). Optimal is O(n · k log k) — sort each word once and bucket by its sorted form.

Solutions

Try first; peek if stuck. Each solution shows Python / JS / TS and explains the optimization.

1 — Has duplicate

def has_dup(arr):
    seen = set()
    for x in arr:
        if x in seen:
            return True
        seen.add(x)
    return False
# Or one-liner: return len(arr) != len(set(arr))
  
function hasDup(arr) {
  const seen = new Set();
  for (const x of arr) {
    if (seen.has(x)) return true;
    seen.add(x);
  }
  return false;
}
// Or: return arr.length !== new Set(arr).size;
  
function hasDup(arr: number[]): boolean {
  const seen = new Set<number>();
  for (const x of arr) {
    if (seen.has(x)) return true;
    seen.add(x);
  }
  return false;
}
  
O(n) time, O(n) space. Traded O(1) extra space for the O(1) membership test that turns the n² nested loop into a single sweep.

2 — Pair count for target

def pair_count(nums, target):
    seen = {}   # value -> count of occurrences seen so far
    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. The "count of complement seen so far" is the right state — handles duplicates correctly without double-counting (each pair (i, j) is recorded exactly once when j is processed).

3 — Sliding window max

from collections import deque

def window_max(nums, k):
    out = []
    dq = deque()    # indices, values strictly decreasing
    for i, x in enumerate(nums):
        # drop indices that have left the window
        while dq and dq[0] <= i - k:
            dq.popleft()
        # maintain monotonic property
        while dq and nums[dq[-1]] < x:
            dq.pop()
        dq.append(i)
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out
  
function windowMax(nums, k) {
  const out = [];
  const dq = [];   // indices, values decreasing
  for (let i = 0; i < nums.length; i++) {
    while (dq.length && dq[0] <= i - k) dq.shift();
    while (dq.length && nums[dq[dq.length - 1]] < nums[i]) dq.pop();
    dq.push(i);
    if (i >= k - 1) out.push(nums[dq[0]]);
  }
  return out;
}
  
function windowMax(nums: number[], k: number): number[] {
  const out: number[] = [];
  const dq: number[] = [];   // indices, values decreasing
  for (let i = 0; i < nums.length; i++) {
    while (dq.length && dq[0] <= i - k) dq.shift();
    while (dq.length && nums[dq[dq.length - 1]] < nums[i]) dq.pop();
    dq.push(i);
    if (i >= k - 1) out.push(nums[dq[0]]);
  }
  return out;
}
  
O(n) time — each index pushed and popped at most once across the entire run. Each window's max is the front of the deque. The monotonic-deque trick collapses the brute force O(n × k) sliding-window scan into a single sweep. Note: dq.shift() in JS is O(n); for production use a real deque, but for interview problems on n < 10⁵ it's acceptable.

4 — First non-repeating character

from collections import Counter

def first_unique(s):
    counts = Counter(s)
    for i, ch in enumerate(s):
        if counts[ch] == 1:
            return i
    return -1
  
function firstUnique(s) {
  const counts = new Map();
  for (const c of s) counts.set(c, (counts.get(c) || 0) + 1);
  for (let i = 0; i < s.length; i++) {
    if (counts.get(s[i]) === 1) return i;
  }
  return -1;
}
  
function firstUnique(s: string): number {
  const counts = new Map<string, number>();
  for (const c of s) counts.set(c, (counts.get(c) || 0) + 1);
  for (let i = 0; i < s.length; i++) {
    if (counts.get(s[i]) === 1) return i;
  }
  return -1;
}
  
O(n) time, O(alphabet) space. Two passes: count, then find. Trade O(1) space for the O(1) lookup that beats the O(n²) "rescan for each i" brute force.

5 — Group anagrams

from collections import defaultdict

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        key = ''.join(sorted(w))
        groups[key].append(w)
    out = list(groups.values())
    for g in out: g.sort()
    out.sort(key=lambda g: g[0])
    return out
  
function groupAnagrams(words) {
  const groups = new Map();
  for (const w of words) {
    const key = w.split('').sort().join('');
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(w);
  }
  const out = [...groups.values()];
  out.forEach(g => g.sort());
  out.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
  return out;
}
  
function groupAnagrams(words: string[]): string[][] {
  const groups = new Map<string, string[]>();
  for (const w of words) {
    const key = w.split('').sort().join('');
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key)!.push(w);
  }
  const out = [...groups.values()];
  out.forEach(g => g.sort());
  out.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
  return out;
}
  
O(n × k log k) time, O(n × k) space where k = max word length. Bucketing on sorted form gives a canonical key per anagram group. Beats the n²-pair-comparison brute force by reusing the sort.
Notebook prompt

For each of the five drills, write the trade-off in one line: "Optimization N: traded ___ for ___ by using ___." When you read these back later, that's the language you'll have ready in interviews.