Module 0 · Drill 2 · refactor reps
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.
Start with the brute solution running and passing tests. Then rewrite it. The drill is the rewrite — the trade-off you talk yourself into.
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.
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.
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).
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.
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.
Try first; peek if stuck. Each solution shows Python / JS / TS and explains the optimization.
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;
}
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;
}
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;
}
dq.shift() in JS is O(n); for production use a real deque, but for interview problems on n < 10⁵ it's acceptable.
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;
}
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;
}
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.