The problems that keep showing up in online tests and live rounds: primes, spiral matrix, two sum, linked lists, stacks, binary search and array partitioning, each explained step by step.
Readiness: 0 of 34 nailed
These cards explain the idea and how to talk through it. To write and run the code against tests, use: Problems · Build challenges · Sandbox
How to use this page:1. Read a question2. Type your answer3. Check with AI4. Open the model answer5. Timed drill when you’re 70% ready
A prime has exactly two divisors: 1 and itself. The slow way checks every number against every smaller number. Two tricks make it fast:
You only need to test divisors up to √n: if 36 = 4 × 9, one of them is always ≤ 6.
The Sieve of Eratosthenes: write all numbers, then cross out multiples of 2, of 3, of 5… What’s left are primes.
function isPrime(n) {
if (n < 2) return false;
for (let d = 2; d * d <= n; d++) {
if (n % d === 0) return false;
}
return true;
}
function primesUpTo(n) {
const composite = new Array(n + 1).fill(false);
const primes = [];
for (let i = 2; i <= n; i++) {
if (composite[i]) continue;
primes.push(i);
for (let m = i * i; m <= n; m += i) composite[m] = true;
}
return primes;
}
const between = (a, b) => primesUpTo(b).filter(p => p >= a);
Say it like this in the interview
“For one number I test divisors up to its square root, O(√n). For all primes up to n I use the Sieve of Eratosthenes: mark multiples of each prime starting from its square, O(n log log n) time, O(n) space. For a range I sieve up to b and filter, or use a segmented sieve if b is huge.”
Store the combined information in one variable, then subtract to get each back. Modern languages let you swap directly with destructuring.
let a = 5, b = 9;
// arithmetic
a = a + b; // 14
b = a - b; // 5
a = a - b; // 9
// XOR (integers)
a ^= b; b ^= a; a ^= b;
// modern JS / Python: destructuring
[a, b] = [b, a];
# Python: a, b = b, a
Say it like this in the interview
“With arithmetic, add then subtract, or with XOR for integers. Arithmetic can overflow in fixed-size integers and XOR fails if both refer to the same memory. In real code I’d use destructuring, [a, b] = [b, a], which is clearest.”
If three points make a triangle with zero area, they lie on one line. The cross-product formula calculates that area without any division.
function collinear([x1, y1], [x2, y2], [x3, y3]) {
// twice the triangle's area; zero means no triangle -> same line
return (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1) === 0;
}
collinear([0, 0], [1, 1], [2, 2]); // true
Say it like this in the interview
“I check that the cross product of vectors AB and AC is zero, which means the triangle area is zero. It avoids comparing slopes, which would require division and fails for vertical lines.”
Traps that make people fail
Comparing slopes with division and crashing on vertical lines (division by zero).
Walk through the list once. For each number, ask: “have I already seen the partner I need (target - number)?” Keep a map of number → index for everything seen so far.
function twoSum(nums, target) {
const seen = new Map(); // value -> index
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(nums[i], i);
}
return null;
}
twoSum([2, 7, 11, 15], 9); // [0, 1]
Say it like this in the interview
“Brute force checks every pair in O(n²). With a hash map of values seen so far, I check for the complement in O(1), giving O(n) time and O(n) space. I insert after checking so a number can’t pair with itself.”
Peel the matrix like an onion. Keep four walls: top, bottom, left, right. Walk along the top wall, then down the right wall, back along the bottom, up the left, and move each wall inward after walking it. Stop when the walls cross.
function spiral(matrix) {
const out = [];
let top = 0, bottom = matrix.length - 1;
let left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let c = left; c <= right; c++) out.push(matrix[top][c]);
top++;
for (let r = top; r <= bottom; r++) out.push(matrix[r][right]);
right--;
if (top <= bottom) {
for (let c = right; c >= left; c--) out.push(matrix[bottom][c]);
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) out.push(matrix[r][left]);
left++;
}
}
return out;
}
// [[1,2,3],[4,5,6],[7,8,9]] -> [1,2,3,6,9,8,7,4,5]
Say it like this in the interview
“Four boundaries shrink after each side is traversed. The two if checks prevent re-reading a row or column when the matrix isn’t square. O(rows × cols) time, O(1) extra space besides the output.”
Traps that make people fail
Missing the boundary checks, which duplicates elements for 1-row or 1-column matrices.
Keep a “boundary” marker. Everything left of it is small. Each time you find a small number, swap it to the boundary and move the boundary one step right. This is the heart of quicksort.
function partition(arr, x) {
let boundary = 0; // next slot for a small element
for (let i = 0; i < arr.length; i++) {
if (arr[i] < x) {
[arr[i], arr[boundary]] = [arr[boundary], arr[i]];
boundary++;
}
}
return arr;
}
partition([9, 1, 8, 2, 7, 3], 5); // [1, 2, 3, 9, 7, 8]
Say it like this in the interview
“A single pass with a write pointer, Lomuto-style partitioning: O(n) time, O(1) space. It’s the partition step of quicksort. If the relative order must be kept, I’d use a stable approach with extra space.”
You know what the total of 1 to n should be (formula n(n+1)/2). Add up what you have. The difference is the missing number.
function missing(nums) {
const n = nums.length + 1;
const expected = (n * (n + 1)) / 2;
return expected - nums.reduce((a, b) => a + b, 0);
}
missing([1, 2, 4, 5]); // 3
Say it like this in the interview
“Use the arithmetic series sum and subtract the actual sum: O(n) time, O(1) space. XOR of all indices and values avoids overflow in fixed-size languages.”
Walk along carrying a running total. If the running total becomes a burden (worse than starting fresh at this number), drop it and restart here. Remember the best total you ever had.
function maxSubarray(nums) {
let best = nums[0], current = nums[0];
for (let i = 1; i < nums.length; i++) {
current = Math.max(nums[i], current + nums[i]); // extend or restart
best = Math.max(best, current);
}
return best;
}
maxSubarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]); // 6 (4, -1, 2, 1)
Say it like this in the interview
“Kadane’s algorithm: at each element, either extend the current subarray or start a new one, tracking the maximum. O(n) time, O(1) space. Initialising with the first element handles all-negative arrays.”
Two pointers, one at the start of each array. Take the smaller value, move that pointer forward, repeat. Then add whatever is left.
function mergeSorted(a, b) {
const out = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
return out.concat(a.slice(i), b.slice(j));
}
Say it like this in the interview
“Two-pointer merge in O(n + m), the core step of merge sort.”
A linked list is a chain of boxes, each pointing to the next. To reverse it, walk along and flip each arrow to point backwards. You need three fingers: the previous box, the current box, and the next box (so you don’t lose the rest of the chain when you flip).
function reverse(head) {
let prev = null;
let current = head;
while (current) {
const next = current.next; // remember the rest
current.next = prev; // flip the arrow
prev = current; // step forward
current = next;
}
return prev; // new head
}
// 1 -> 2 -> 3 -> null becomes 3 -> 2 -> 1 -> null
Say it like this in the interview
“Iteratively with three pointers, prev, current and next, flipping each next pointer. O(n) time, O(1) space. Recursively it’s also possible but uses O(n) stack.”
Traps that make people fail
Overwriting current.next before saving it, which loses the rest of the list.
You can’t reach the previous node, so you can’t unlink this one. The trick: become your neighbour. Copy the next node’s value into this node, then skip over the next node.
function deleteNode(node) {
// copy the next node into this one, then skip the next node
node.value = node.next.value;
node.next = node.next.next;
}
Say it like this in the interview
“Copy the next node’s data into the current node and bypass the next node, O(1). It doesn’t work for the tail node, which needs the previous node, and it breaks if other code holds references to the next node.”
Two runners on a track: one runs twice as fast. On a straight road the fast one reaches the end. On a circular track, the fast one eventually laps the slow one and they meet.
function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
Say it like this in the interview
“Floyd’s tortoise and hare: O(n) time, O(1) space. A hash set of visited nodes also works with O(n) space.”
A stack is a pile of plates: last in, first out. Push every opening bracket. When a closing bracket comes, the plate on top must be its partner. At the end the pile must be empty.
function isBalanced(text) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of text) {
if ('([{'.includes(ch)) stack.push(ch);
else if (ch in pairs) {
if (stack.pop() !== pairs[ch]) return false;
}
}
return stack.length === 0;
}
Say it like this in the interview
“A stack: push openers, and on each closer pop and compare. If it mismatches or the stack is empty, it’s invalid; at the end the stack must be empty. O(n) time and space.”
They will probably ask next
“Stack vs queue?” Stack is LIFO (undo, call stack); queue is FIFO (print jobs, BFS, message queues).
Push everything onto an “inbox” stack. To take from the front, if the “outbox” stack is empty, pour the inbox into it (which reverses the order), then pop.
Say it like this in the interview
“Two stacks: enqueue pushes to in; dequeue pops from out, refilling it from in only when empty. Each element moves at most twice, so operations are amortised O(1).”
Guessing a number from 1 to 100: guess 50, they say “higher”, so ignore the bottom half. Each guess halves what’s left, so even a million items takes only about 20 guesses. Only works on sorted data.
function binarySearch(sorted, target) {
let low = 0, high = sorted.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (sorted[mid] === target) return mid;
if (sorted[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
Say it like this in the interview
“Compare with the middle and discard half each step: O(log n). Careful with the loop condition low <= high and with updating to mid + 1 / mid - 1, otherwise it loops forever.”
Sorting works (O(n log n)). Better: keep a min-heap of size k; the smallest in the heap is the answer.
Say it like this in the interview
“Sort and index for simplicity; a size-k min-heap gives O(n log k); quickselect averages O(n). I’d mention the trade-offs and implement the one the interviewer prefers.”
Bubble sort swaps neighbours repeatedly: simple but slow. Merge sort splits the list in half, sorts each half, and merges: always fast. Quicksort picks a pivot and partitions: usually fastest in practice.
Say it like this in the interview
“Bubble sort O(n²). Merge sort O(n log n) always, stable, O(n) extra space. Quicksort O(n log n) average, O(n²) worst with bad pivots, in-place. Built-in sorts use hybrids like Timsort.”
Anagrams use exactly the same letters the same number of times. Count letters in the first word, subtract for the second; everything must end at zero.
function isAnagram(a, b) {
if (a.length !== b.length) return false;
const count = {};
for (const ch of a) count[ch] = (count[ch] || 0) + 1;
for (const ch of b) {
if (!count[ch]) return false;
count[ch]--;
}
return true;
}
Say it like this in the interview
“Count characters with a hash map, O(n). Sorting both strings and comparing also works in O(n log n).”
Anagrams have the same letters, so if you sort each word’s letters, anagrams produce the same key. Group by that key.
function groupAnagrams(words) {
const groups = new Map();
for (const w of words) {
const key = [...w].sort().join('');
groups.set(key, [...(groups.get(key) || []), w]);
}
return [...groups.values()];
}
Say it like this in the interview
“A hash map keyed by the sorted word, or by a 26-letter count signature for O(n·k).”
Each number is the sum of the two before it. The naive recursive version recalculates the same values millions of times; keeping just the last two values makes it fast.
function fib(n) {
let a = 0, b = 1;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
Say it like this in the interview
“Naive recursion is O(2ⁿ). Iterating with two variables is O(n) time, O(1) space. Memoised recursion is also O(n). This is the simplest example of dynamic programming.”
To reach step n you came from step n-1 or step n-2. So ways(n) = ways(n-1) + ways(n-2): it’s Fibonacci in disguise.
Say it like this in the interview
“The recurrence is ways(n) = ways(n-1) + ways(n-2) with ways(1) = 1, ways(2) = 2; computed iteratively in O(n) time and O(1) space. Recognising the recurrence is the key DP skill.”
Build up answers from small amounts: the best way to make amount a is 1 + the best way to make a - coin, for the best coin.
Say it like this in the interview
“Bottom-up DP: dp[0] = 0, and for each amount, dp[a] = min(dp[a - c] + 1) over coins. O(amount × coins). Greedy fails for coin sets like [1, 3, 4] for 6.”
Keep a window of characters with no repeats. Expand to the right; when you hit a repeat, move the left edge past the previous occurrence.
function longestUnique(s) {
const last = new Map();
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
if (last.has(s[right]) && last.get(s[right]) >= left) left = last.get(s[right]) + 1;
last.set(s[right], right);
best = Math.max(best, right - left + 1);
}
return best;
}
Say it like this in the interview
“Sliding window with a map of last-seen indices: when a character repeats inside the window, move left to just after its previous index. O(n).”
BFS explores level by level (all neighbours first), using a queue. DFS goes as deep as possible first, using a stack or recursion.
Say it like this in the interview
“BFS uses a queue and finds shortest paths in unweighted graphs; DFS uses a stack or recursion, good for detecting cycles, topological sort and exploring all paths. Both are O(V + E) with a visited set.”
Every node must be within a range: everything on the left is smaller, everything on the right is bigger, all the way down, not just compared with the direct parent.
function isValidBST(node, min = -Infinity, max = Infinity) {
if (!node) return true;
if (node.val <= min || node.val >= max) return false;
return isValidBST(node.left, min, node.val) && isValidBST(node.right, node.val, max);
}
Say it like this in the interview
“Recursively pass down allowed min and max bounds. Checking only the immediate children is the classic wrong answer. Alternatively, an in-order traversal must be strictly increasing.”
Keep items in order of last use. When it’s full, throw away the least recently used. A JavaScript Map remembers insertion order, so deleting and re-inserting moves an item to the end.
class LRUCache {
constructor(capacity) { this.capacity = capacity; this.map = new Map(); }
get(key) {
if (!this.map.has(key)) return -1;
const value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
return value;
}
put(key, value) {
this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.capacity) this.map.delete(this.map.keys().next().value);
}
}
Say it like this in the interview
“Classic answer: a hash map plus a doubly linked list. In JS, a Map gives the same behaviour: on get, delete and re-set to mark as recent; on put over capacity, evict map.keys().next().value.”