Here is a first answer to 53. Maximum Subarray: to find the run of neighboring numbers with the largest total, try every run and add it up.
// Time O(n^3): every pair (start, end), each summed from scratch. Memory O(1).
export function maxSubArrayCubic(nums: number[]): number {
let best = -Infinity;
for (let start = 0; start < nums.length; start++) {
for (let end = start; end < nums.length; end++) {
let sum = 0;
for (let k = start; k <= end; k++) sum += nums[k];
if (sum > best) best = sum;
}
}
return best;
}
It’s correct, and LeetCode allows up to 10⁵ numbers. In the measurement later on this page, it took 329.63 ms at 1,600 numbers and grew 7.9 times per doubling, so 10⁵ numbers would take about 22 hours. One pass with two variables took 0.10 ms at 10⁵.
This module works six problems where one pass and a few numbers replace a loop inside a loop. Three are greedy, and three work on the bits of an integer. Then it puts Module 1’s nine steps together in one uninterrupted mock interview, followed by a rubric to score your own practice and a plan for after the course.
After this module, you can:
- keep the best answer that ends at each item, and say why one pass is enough (Kadane’s algorithm)
- argue that a greedy rule is safe, and check it against a slower solution on random inputs
- count, clear and combine bits with JavaScript’s 32-bit operators, and say where
>>,>>>and/ 2differ - run a 45-minute mock interview on a problem you haven’t seen, and score it step by step
- keep practicing after the course, alone or with an AI tool that plays the interviewer
The code for this module is in module-12/ of the course repository, and node --test "module-12/**/*.test.ts" from its root runs every test. atlimit.ts in the module folder calls the solutions of 53, 55, 134 and 268 once each on a hard input at the problem’s limit, so its times are rough, and yours will differ. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.
The patterns: one pass with a safe rule, and 32 bits at a time
Module 8 defined a greedy algorithm: it takes the choice that looks best right now and never undoes it. Each greedy problem here is one pass over the input that keeps a short summary of what it has seen. The summary is the best run ending here (53), the farthest index you can reach (55), or the one start that hasn’t failed yet (134).
A greedy rule is only as good as the argument behind it. Module 8 used the exchange argument: a best answer can be changed, one step at a time, into the greedy answer without getting worse. This module adds a second kind. A stays-ahead argument shows that after every step, the greedy summary is at least as good as anything another choice could have kept. Kevin Wayne’s slides for Kleinberg and Tardos, chapter 4 teach both kinds.
DSA Module 9 shows greedy rules that look right and break. So the lab tests every greedy answer against a slower one on hundreds of random small inputs. Passing is evidence, not proof.
The other three problems take or return integers that fit in 32 bits. JavaScript’s bit operators work on the binary digits of a number.
& (AND) keeps a 1 where both sides have one, | (OR) where either has one, and ^ (XOR) where they differ. ~ flips every bit. << shifts the bits left, filling with zeros, and >> and >>> shift them right. Figure 1 shows &, |, ^ and << on 13 and 11.
13 1101
11 1011
13 & 11 1001 9 1 where both are 1
13 | 11 1111 15 1 where either is 1
13 ^ 11 0110 6 1 where they differ
13 << 1 11010 26 every bit one place up: times 2
Figure 1: each operator works on every bit position at once, so one operator does what a loop over 32 positions would do.
Before it works, each operator except >>> converts its operands with ToInt32: the specification drops any fraction and keeps the low 32 bits. Those 32 bits are read in two’s complement: the top bit, the sign bit, counts as −2³¹, so a number with it set is negative. That’s why 1 << 31 is −2,147,483,648. Module 5 met ToUint32, which >>> uses to read the same bits as a number from 0 to 2³² − 1. DSA Module 12 has a longer tour of the operators.
Signs that point to a greedy pass:
- “the largest”, “can you reach”, “which start works”, and the limits want O(n) at n up to 10⁵
- a choice you never need to take back: once a run, a reach or a start is beaten, nothing later revives it
- a summary of the items so far (one or two numbers) decides what to do with the next one
Signs that point to bit operators:
- the input is a 32-bit integer, or the problem talks about its bits
- the problem forbids the obvious tool (“without
+or-“) or asks for O(1) extra memory - every value appears twice except one, or one value of a known range is missing: equal values cancel with XOR
The cost of greedy is the proof: without an argument, a rule that passes your examples can still be wrong. The cost of bits is the 32-bit limit: past 2³¹ − 1 the operators silently change the value.
Rule: If a summary of the items so far decides every later choice, keep it in one pass and say why nothing better was dropped. If the input is a 32-bit integer, treat it as 32 yes-or-no answers that one operator tests, clears or combines.
53. Maximum Subarray
53. Maximum Subarray is rated Medium. You get a list of integers, some of them negative. A subarray is a run of one or more neighboring items. Return the largest total of any subarray.
1 ≤ nums.length ≤ 10⁵−10⁴ ≤ nums[i] ≤ 10⁴- The page’s follow-up: after the O(n) solution, write one that divides the list in halves.
The signature is function maxSubArray(nums: number[]): number. Try it on LeetCode first.
Hint
Look at the best subarray that ends at item i. It either includes the best subarray ending at item i − 1, or it doesn’t. When would you drop that one?
Interviewer: Find the run of neighboring numbers with the largest sum.
Candidate: Can the run be empty, with sum 0? If every number is negative, that matters.
Interviewer: No, at least one number.
The interviewer and the candidate are invented. The problems, limits and timings are real.
Candidate: Then an all-negative list returns its largest number. Do you want the sum or the run itself?
Interviewer: The sum.
Candidate: The largest possible sum is 10⁵ × 10⁴ = 10⁹, far below 2⁵³, so plain numbers are exact. With n up to 10⁵, I’m aiming for O(n log n) or better. Here’s my example, a shop’s daily profit, and three edge cases.
nums expected
[3, -7, 6, -2, 5, -9, 4] 9 the run 6, -2, 5
[-8, -3, -5] -3 all negative: the largest item
[-10000] -10000 one item
[-1, 0, -2] 0 a zero is the best run
Candidate: The first answer is the triple loop at the top of this page, maxSubArrayCubic. It tries every start and end, about n² / 2 runs, and sums each one from scratch in up to n steps. That’s O(n³), around 1.7 × 10¹⁴ additions at 10⁵. Far too slow.
Interviewer: What does it repeat?
Candidate: The sum of start..end is the sum of start..end - 1 plus one number. The inner loop rebuilds it every time. So I keep a running sum for each start.
// Time O(n^2): every start, and the sum grows by one item per end instead of being rebuilt. Memory O(1).
export function maxSubArrayQuadratic(nums: number[]): number {
let best = -Infinity;
for (let start = 0; start < nums.length; start++) {
let sum = 0;
for (let end = start; end < nums.length; end++) {
sum += nums[end];
if (sum > best) best = sum;
}
}
return best;
}
Candidate: That’s O(n²), about 5 × 10⁹ additions at the limit, 50 times the budget.
In atlimit.ts, maxSubArrayQuadratic took 4,355.5 ms on 10⁵ random numbers.
Interviewer: Still too slow. What’s left to remove?
Candidate: Every start walks over the same items again. Turn it around: for each end, I want the best run that ends there. That run either extends the best run ending one item earlier, or starts fresh at this item. I start fresh when the earlier best is negative, because it can only lower the total.
// Kadane: the best run ending here either extends the best run ending at the item before, or starts fresh here.
// Time O(n): one pass. Memory O(1): two numbers.
function maxSubArray(nums: number[]): number {
let endingHere = nums[0];
let best = nums[0];
for (let i = 1; i < nums.length; i++) {
endingHere = Math.max(nums[i], endingHere + nums[i]);
best = Math.max(best, endingHere);
}
return best;
}
export { maxSubArray };
This is the version to paste into LeetCode.
Candidate: Every run ends somewhere. At each end, endingHere holds the best run that ends there, so best, the largest of them, is the answer.
Interviewer: Trace your example.
Pause and predict. At i = 2 the item is 6, and endingHere is −4. What does endingHere become?
Figure 2 shows the two numbers after each item.
i nums[i] endingHere + nums[i] nums[i] endingHere best
0 3 3 3
1 -7 3 + -7 = -4 -7 -4 3
2 6 -4 + 6 = 2 6 6 6 fresh start
3 -2 6 + -2 = 4 -2 4 6
4 5 4 + 5 = 9 5 9 9
5 -9 9 + -9 = 0 -9 0 9
6 4 0 + 4 = 4 4 4 9 returned
Figure 2: at i = 2 the run ending before is negative, so the best run starts fresh at 6; best keeps 9 after the drop to 0.
Candidate: For [-8, -3, -5], both start at −8. At −3, starting fresh beats −11, so endingHere and best become −3. At −5, extending gives −8 and fresh gives −5, so best stays −3.
Interviewer: Final cost?
Candidate: O(n) time, one pass. O(1) memory, two numbers. And no algorithm can do better than O(n), because it has to read every number at least once.
In atlimit.ts, maxSubArray took 0.8 ms on the same 10⁵ numbers.
This one-pass rule is Kadane’s algorithm. Jon Bentley’s 1984 Communications of the ACM column tells its history. Ulf Grenander, at Brown University, posed the problem; Michael Shamos found an O(n log n) algorithm. Then Jay Kadane, a statistician at Carnegie Mellon University, designed the linear one at a seminar in about a minute. The same column makes the point the Candidate made: any algorithm must look at all n inputs.
It’s greedy in this module’s sense. At each item it makes one choice, extend or start fresh, and never revisits it. The argument is the one the Candidate gave: endingHere is always the best run ending at i, so the summary stays ahead of any other run ending there.
Interviewer: The page asks for a version that splits the list in halves. How would that work?
The Candidate’s answer
Candidate: The best run is in the left half, in the right half, or it crosses the middle. A crossing run is the best run that ends at mid plus the best run that starts at mid + 1, and each is one loop outward from the middle. The halves are the same question, smaller.
// Divide and conquer (the page's follow-up): the best run is in the left half, the right half, or crosses the middle.
// Time O(n log n): each of log n levels does O(n) work for the crossing runs. Memory O(log n) for the recursion.
export function maxSubArrayDivide(nums: number[]): number {
const best = (lo: number, hi: number): number => {
if (lo === hi) return nums[lo];
const mid = lo + Math.floor((hi - lo) / 2);
let sum = 0;
let leftBest = -Infinity; // best run that ends at mid
for (let i = mid; i >= lo; i--) {
sum += nums[i];
if (sum > leftBest) leftBest = sum;
}
sum = 0;
let rightBest = -Infinity; // best run that starts at mid + 1
for (let i = mid + 1; i <= hi; i++) {
sum += nums[i];
if (sum > rightBest) rightBest = sum;
}
return Math.max(leftBest + rightBest, best(lo, mid), best(mid + 1, hi));
};
return best(0, nums.length - 1);
}
Candidate: Each level of halving does O(n) work for the crossing runs, and there are log n levels. So it’s O(n log n) time and O(log n) memory for the recursion, which is only about 17 calls deep at 10⁵. It’s slower than the one pass, but the two halves could run on different machines.
This way of splitting a problem into smaller copies of itself and combining their answers is called divide and conquer. In atlimit.ts, maxSubArrayDivide took 6.8 ms at 10⁵, against 0.8 ms for Kadane’s algorithm.
Interviewer: Can you return the run, not only the sum?
The Candidate’s answer
Candidate: Yes. I remember where the current run started, and reset it when I start fresh. When best changes, I save that start and the current index as the answer’s ends. Still O(n) time and O(1) memory.
This version isn’t in the lab.
Interviewer: What if the list is a circle, so a run can wrap from the end to the start?
The Candidate’s answer
Candidate: A wrapping run leaves out a run in the middle. So the best wrapping total is the whole total minus the worst run that doesn’t wrap, which is Kadane’s algorithm with Math.min. The answer is the larger of that and the normal answer. The exception is a list of only negative numbers: then the “worst run” is the whole list, and I return the normal answer.
That’s LeetCode’s 918. Maximum Sum Circular Subarray, which this course doesn’t cover. This version isn’t in the lab.
Two mistakes are common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module that has one.
- Starting
bestat 0. That allows the empty run, as Bentley’s 1984 version does. For[-8, -3, -5]it returns 0 instead of −3. LeetCode asks for at least one number, so start both variables atnums[0]. - Halves that don’t shrink. In the divide version, recursing on
(lo, mid - 1)and(mid, hi)with a midpoint rounded down never reaches its base case. For two items,midislo, so(mid, hi)is the whole range again, and it recurses until the call stack runs out. This one has nomistakes.tsline. Split as(lo, mid)and(mid + 1, hi).
Lab folder: module-12/0053-maximum-subarray/ in the course repository.
55. Jump Game
55. Jump Game is rated Medium. You stand on index 0 of a list. The number at each index is the longest jump you may take from there, and any shorter jump is allowed too. Say whether you can land on the last index.
1 ≤ nums.length ≤ 10⁴0 ≤ nums[i] ≤ 10⁵
The signature is function canJump(nums: number[]): boolean. Try it on LeetCode first.
Hint
If you can reach index 5, can you reach index 3?
Interviewer: Can you get from the first index to the last?
Candidate: Is the number the exact jump length, or the most I can jump?
Interviewer: The most. Any length from 1 up to it.
Candidate: If there’s one item, I’m already on the last index, so that’s true. And a 0 is the only way to get stuck. These are stepping stones; here are my cases.
nums expected
[2, 0, 3, 0, 0, 1] true 0 -> 2, and 3 reaches index 5
[1, 2, 0, 0, 5] false indexes 0 to 3 are reachable, 2 and 3 hold 0
[0] true already on the last index
[0, 1] false stuck at the start
[1, 1, 0] true a 0 on the last index doesn't matter
Candidate: The first answer marks every index I can reach. Index 0 is reachable; from each reachable index i, I mark i + 1 to i + nums[i].
// Mark every index reachable: from each reachable i, mark i + 1 .. i + nums[i].
// Time O(n^2): each index can mark up to n others. Memory O(n): one flag per index.
export function canJumpMarking(nums: number[]): boolean {
const reachable = new Array<boolean>(nums.length).fill(false);
reachable[0] = true;
for (let i = 0; i < nums.length; i++) {
if (!reachable[i]) continue;
const last = Math.min(nums.length - 1, i + nums[i]);
for (let j = i + 1; j <= last; j++) reachable[j] = true;
}
return reachable[nums.length - 1];
}
Candidate: Each index can mark up to n others, so it’s O(n²) time, about 5 × 10⁷ marks at 10⁴. That’s inside the budget. Memory is O(n), one flag per index.
In atlimit.ts, with all 10⁴ values set to 10⁵, so that every index marks every index after it, canJumpMarking took 25.5 ms. It fits LeetCode’s limits.
Interviewer: It fits. What would you change?
Candidate: The marks always form one block. If index 5 is reachable, every index before it is too, because the jumps that got me there passed over them and I could stop on any of them. So I keep only the block’s right end, farthest. If I reach an index past farthest, there’s a gap, and nothing later can be reached.
// Greedy: the reachable indexes are always one block 0..farthest, so keep only its right end.
// Time O(n): one pass. Memory O(1).
function canJump(nums: number[]): boolean {
let farthest = 0;
for (let i = 0; i < nums.length; i++) {
if (i > farthest) return false; // a gap: no index before i can reach i
farthest = Math.max(farthest, i + nums[i]);
if (farthest >= nums.length - 1) return true;
}
return true;
}
export { canJump };
This is the version to paste into LeetCode.
Interviewer: Trace both of your first two examples.
Figure 3 shows farthest after each index, for the list that reaches the end and the list that doesn’t.
[2, 0, 3, 0, 0, 1]
i nums[i] i > farthest? farthest = max(farthest, i + nums[i])
0 2 no max(0, 2) = 2
1 0 no max(2, 1) = 2
2 3 no max(2, 5) = 5 5 >= last index 5: true
[1, 2, 0, 0, 5]
0 1 no max(0, 1) = 1
1 2 no max(1, 3) = 3
2 0 no max(3, 2) = 3
3 0 no max(3, 3) = 3
4 4 > 3: false
Figure 3: the reachable indexes are always the block 0 to farthest; the 5 at index 4 never counts, because index 4 is past the block.
Candidate: For [0], farthest is 0, which is already the last index, so it returns true at i = 0.
Interviewer: Final cost?
Candidate: O(n) time, one pass that can stop early. O(1) memory.
In atlimit.ts, canJump took 0.1 ms on the same input. The two fit the limits, so the reason to prefer the greedy one is the shorter code and O(1) memory, and that it doesn’t slow down if the limits grow.
Interviewer: What if I ask for the fewest jumps to the end?
The Candidate’s answer
Candidate: Then I’d go level by level, like the breadth-first search in Module 9. The first level is index 0. Each next level is every index past the current block that the block can reach, up to its farthest reach. The number of levels until the block covers the last index is the answer, and it’s still one pass, O(n).
That’s LeetCode’s 45. Jump Game II, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: Why is it safe to keep one number?
The Candidate’s answer
Candidate: Because the set of reachable indexes is always a prefix, 0 to farthest. Any index inside it is reachable, and none outside it is. So farthest says everything the marks said. That’s a stays-ahead argument: after each index, farthest is at least as far as any sequence of jumps from the indexes seen so far can get.
Interviewer: How do you know the code matches the argument?
The Candidate’s answer
Candidate: I can’t prove it with a test, but I can check it. The lab compares canJump with canJumpMarking on 500 random lists of up to 10 values from 0 to 3, which hit plenty of zeros and gaps.
One mistake is common here.
- Reaching from an index you never reached. Taking
i + nums[i]for every index, reached or not, returns true for[0, 2, 0]instead of false. Index 1’s 2 would reach the end, but you can never stand on index 1. Return false as soon asi > farthest.
Lab folder: module-12/0055-jump-game/ in the course repository.
134. Gas Station
134. Gas Station is rated Medium. Stations sit on a loop. At station i you take gas[i] fuel, and driving on to the next station burns cost[i]. Starting with an empty tank, return the station from which you can drive the whole loop once, or −1 if none works.
1 ≤ n ≤ 10⁵, where n is the length of both lists0 ≤ gas[i], cost[i] ≤ 10⁴- The inputs are made so that the answer, if there is one, is unique.
The signature is function canCompleteCircuit(gas: number[], cost: number[]): number. Try it on LeetCode first.
Hint
Say you start at station a and the tank goes below 0 on the way out of station b. Could any station between a and b do better?
Interviewer: Find the station where a full loop works.
Candidate: Is there at most one such station? Then the first start that works is the answer.
Interviewer: Yes, it’s unique if it exists.
Candidate: Clockwise only, from i to i + 1 and from the last back to 0? And can the tank be exactly 0 when I arrive?
Interviewer: Clockwise only. Arriving with 0 is fine; going below 0 isn’t.
Candidate: My example is a delivery van with four charging stops. The changes gas - cost are −1, −2, +4, −1, which add up to 0.
gas cost expected
[4, 1, 6, 2] [5, 3, 2, 3] 2 left after each leg: 4, 3, 2, 0
[5] [4] 0 one station, enough
[5] [6] -1 one station, not enough
[3, 1, 1] [1, 2, 2] 0 total exactly 0, the tank ends empty
Candidate: The first answer drives the loop from every start and stops at the first leg that runs dry.
// Try every start and drive the whole loop.
// Time O(n^2): n starts, up to n stations each. Memory O(1).
export function canCompleteCircuitBrute(gas: number[], cost: number[]): number {
const n = gas.length;
for (let start = 0; start < n; start++) {
let tank = 0;
let stations = 0;
while (stations < n) {
const i = (start + stations) % n;
tank += gas[i] - cost[i];
if (tank < 0) break;
stations++;
}
if (stations === n) return start;
}
return -1;
}
Candidate: That’s n starts of up to n legs, O(n²). At 10⁵ stations it can be 5 × 10⁹ legs, too slow.
atlimit.ts builds that case: every station has a change of 0, except a deficit at station n − 2 and a surplus at the last one. Every start before the last drives to n − 2 and fails there. canCompleteCircuitBrute took 10,128.2 ms.
Interviewer: What does it repeat?
Candidate: Say I start at a and the tank first goes below 0 leaving station b. Every station between a and b was reached from a with 0 or more fuel. Starting there instead means arriving at the same point with no more than that, so it fails at b too, or earlier. The brute force tries each of them anyway.
Candidate: So when the tank goes below 0 at b, the next candidate is b + 1, and I never drive those legs again. One more fact: if the total of all changes is negative, no start works, whatever the order.
// One pass. If the total gas is less than the total cost, no start works. Otherwise, when the tank runs dry at i,
// no start from the current start to i can work either, so the next candidate is i + 1.
// Time O(n): one pass. Memory O(1).
function canCompleteCircuit(gas: number[], cost: number[]): number {
let total = 0;
let tank = 0;
let start = 0;
for (let i = 0; i < gas.length; i++) {
total += gas[i] - cost[i];
tank += gas[i] - cost[i];
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return total < 0 ? -1 : start;
}
export { canCompleteCircuit };
This is the version to paste into LeetCode.
Interviewer: Why is the last candidate right when the total isn’t negative?
Candidate: From the last candidate to the end, the tank never went below 0. The stations before it add up to a deficit, and the total says the candidate’s part has at least that much to spare. So wrapping around, it covers them.
Interviewer: Trace your example.
Figure 4 shows total, tank and start after each station.
i gas - cost total tank start
0 4 - 5 = -1 -1 -1 < 0: reset to 0 1
1 1 - 3 = -2 -3 -2 < 0: reset to 0 2
2 6 - 2 = 4 1 4 2
3 2 - 3 = -1 0 3 2
end: total 0 is not negative, return start = 2
Figure 4: stations 0 and 1 fail at once, so the candidate moves to 2; from there the tank never drops below 0, and the total covers the wrap.
Candidate: For [5] and [6], the total is −1, so it returns −1 without looking at start.
Interviewer: Final cost?
Candidate: O(n) time, one pass. O(1) memory, three numbers.
In atlimit.ts, canCompleteCircuit took 0.7 ms on the same 10⁵ stations, against 10,128.2 ms for trying every start.
We found no named source for this one-pass rule. The argument above is the Candidate’s, and the lab checks it against the brute force on 400 random inputs with at most one valid start.
Interviewer: Why is it safe to skip every station from start to i?
The Candidate’s answer
Candidate: Each of them would arrive at station i with no more fuel than the current candidate had there, because the candidate reached each of them with 0 or more. The candidate ran dry at i, so they would too. It’s the same idea as Jump Game: one failure rules out a whole block.
Interviewer: What if several starts could work, and I wanted all of them?
The Candidate’s answer (stretch)
Candidate: The one-pass rule finds only one. A start works when no running total from it ever drops below 0. With prefix sums over the loop written out twice, that’s a question about the smallest prefix sum in the next n positions. A sliding minimum answers it for every start in O(n).
This version isn’t in the lab.
Interviewer: Is this greedy?
The Candidate’s answer
Candidate: Yes. It drops the candidate at the first deficit and never takes it back, and the argument says nothing better was dropped. That’s the same kind of rule as Module 8’s interval problems, with its own reason.
Two mistakes are common here.
- No total check. Returning the last candidate without checking the total gives 1 for gas
[1, 4, 0]and cost[2, 2, 2], instead of −1. For gas[1, 2, 1]and the same cost, it gives 3, an index that doesn’t exist. Return −1 when the total is negative. start = iinstead ofi + 1. The station where the tank went below 0 is itself a failed start. For the Candidate’s example this version returns 1 instead of 2. This one has nomistakes.tsline; a scratch run gave that output.
Lab folder: module-12/0134-gas-station/ in the course repository.
191. Number of 1 Bits
191. Number of 1 Bits is rated Easy. Count how many 1s appear when a positive integer is written in base 2.
1 ≤ n ≤ 2³¹ − 1- The page’s follow-up: if the function is called many times, how would you make it faster?
The signature is function hammingWeight(n: number): number. Try it on LeetCode first.
Hint
Write n and n − 1 in binary, one above the other. Which bits differ?
Interviewer: Count the 1 bits of n.
Candidate: Can n be 0 or negative?
Interviewer: No. It’s from 1 to 2³¹ − 1.
Candidate: So the sign bit is never set, and ToInt32 leaves n unchanged. My example is a set of permission flags, 0b101100.
n binary expected
44 101100 3 three flags set
1 1 1 the smallest
2147483647 31 ones 31 2^31 - 1, the most
1073741824 1 and 30 zeros 1 2^30, one high bit
Candidate: The first answer writes n in base 2 and counts the “1” characters.
// Write the number in base 2 and count the "1" characters.
// Time O(log n): about 31 characters, plus building the string. Memory O(log n) for the string.
export function hammingWeightString(n: number): number {
let count = 0;
for (const digit of n.toString(2)) if (digit === "1") count++;
return count;
}
Candidate: At most 31 characters, so it’s O(log n) time and O(log n) memory for the string. That fits easily.
Interviewer: It fits. Can you do it without building a string?
Candidate: I can read the lowest bit with n & 1 and shift it out. I use >>>, which fills with zeros, so the loop ends even if the top bit were set.
// Look at the lowest bit, then shift it out; stop when nothing is left.
// Time O(log n): one step per bit up to the highest 1, at most 31. Memory O(1).
export function hammingWeightShift(n: number): number {
let count = 0;
while (n !== 0) {
count += n & 1;
n = n >>> 1; // zero-fill shift: also ends for a value with the top bit set
}
return count;
}
Interviewer: That steps over every 0 bit too. Can you skip them?
Candidate: Yes. Subtracting 1 turns the lowest 1 bit into 0 and every 0 below it into 1. So n & (n - 1) is n with its lowest 1 bit cleared, and the loop runs once per 1 bit.
// Kernighan's way: n & (n - 1) clears the lowest 1 bit, so the loop runs once per 1 bit.
// Time O(k) for k one bits, at most 31. Memory O(1).
function hammingWeight(n: number): number {
let count = 0;
while (n !== 0) {
n = n & (n - 1);
count++;
}
return count;
}
export { hammingWeight };
This is the version to paste into LeetCode.
Interviewer: Trace 44.
Figure 5 shows n, n − 1 and their AND in each pass.
n n - 1 n & (n - 1) count
101100 101011 101000 1
101000 100111 100000 2
100000 011111 000000 3 n is 0: return 3
Figure 5: n − 1 flips the lowest 1 and the zeros below it, so the AND clears exactly that one bit; three 1 bits take three passes.
Candidate: For 2³⁰, n − 1 is thirty 1s, so one pass gives 0 and returns 1.
Interviewer: Final cost?
Candidate: O(k) time for k one bits, at most 31. O(1) memory. For these limits all three versions are constant time in Big O; the difference is the number of steps per call.
Sean Eron Anderson’s “Bit Twiddling Hacks” lists this as “Brian Kernighan’s way” of counting set bits, and notes that it runs once per set bit.
Interviewer: The page asks: what if the function is called many times?
The Candidate’s answer
Candidate: I’d count the bits of every byte value once, 256 numbers, and then each call adds four lookups: one per byte of n.
// Follow-up "called many times": count once for every byte value, then add four table lookups.
// Time O(1) per call after a 256-entry table is built once. Memory O(1) (256 small numbers).
const BITS_IN_BYTE = Array.from({ length: 256 }, (_, b) => hammingWeight(b));
export function hammingWeightTable(n: number): number {
return (
BITS_IN_BYTE[n & 0xff] +
BITS_IN_BYTE[(n >>> 8) & 0xff] +
BITS_IN_BYTE[(n >>> 16) & 0xff] +
BITS_IN_BYTE[(n >>> 24) & 0xff]
);
}
Candidate: n & 0xff keeps the lowest 8 bits, and n >>> 8 moves the next byte down. A table of 65,536 entries would need two lookups instead of four.
A precomputed answer like BITS_IN_BYTE is a lookup table. To paste it into LeetCode, paste hammingWeight with it, since the table is built from it. We haven’t timed it against Kernighan’s loop.
Interviewer: What if the input were an unsigned 32-bit value, up to 2³² − 1?
The Candidate’s answer
Candidate: Then the top bit can be set, and ToInt32 reads the value as negative. >>> and Kernighan’s loop still end, because >>> fills with zeros and n & (n - 1) clears one bit per pass. >> would not: it copies the sign bit forever.
Three mistakes are common here.
- Halving with
/ 2.n / 2doesn’t drop the low bit; it makes a fraction. For 44 the count is 1 instead of 3, and the loop ran 1,081 times before n reached 0. Use>>> 1or Kernighan’s step. >>instead of>>>. Outside 191’s limits, a value can have bit 31 set: 2³¹ reads as −2,147,483,648. Thenn >> 1keeps copying the sign bit, and the loop was still running after 100 steps. Use>>>.n & 1 === 1.===binds tighter than&, so this isn & (1 === 1), and it works for the mask 1 by accident. With any other mask it’s wrong:6 & 2 === 2is 0. Write(n & mask) !== 0. This one has nomistakes.tsline; DSA Module 12 prints the same bug.
Lab folder: module-12/0191-number-of-1-bits/ in the course repository.
268. Missing Number
268. Missing Number is rated Easy. A list of n different numbers holds all of 0 to n except one. Return the one that isn’t there.
1 ≤ n ≤ 10⁴, where n is the length of the list0 ≤ nums[i] ≤ n, all different- The page’s follow-up: O(n) time with O(1) extra memory.
The signature is function missingNumber(nums: number[]): number. Try it on LeetCode first.
Hint
You know exactly which numbers should be there. What can you compute about them without looking at the list?
Interviewer: One number from 0 to n is missing. Find it.
Candidate: The values are different and all inside 0 to n, so exactly one is missing. Is the list sorted?
Interviewer: No promise.
Candidate: My example: seats 0 to 5 were handed out and five came back.
nums expected
[4, 0, 5, 1, 3] 2
[1, 2, 3] 0 0 is missing
[0] 1 n itself is missing
[10, 2, 0, 1, 3, 4, 5, 6, 7, 8] 9 two-digit values
Candidate: The first answer asks, for each candidate from 0 to n, whether the list includes it.
// For each candidate 0..n, scan the array for it.
// Time O(n^2): n + 1 candidates, each a scan of n items. Memory O(1).
export function missingNumberScan(nums: number[]): number {
for (let candidate = 0; candidate <= nums.length; candidate++) {
if (!nums.includes(candidate)) return candidate;
}
return -1; // not reached: one value is always missing
}
Candidate: That’s O(n²), up to 10⁸ steps at 10⁴: at the edge of the budget, but includes is a fast native loop.
In atlimit.ts, with n itself missing so that the last scan reads the whole list, missingNumberScan took 9.8 ms. It fits the clock, but not the page’s O(n) follow-up.
Interviewer: The page wants O(n) time and O(1) extra memory.
Candidate: A Set gives O(n) time but O(n) memory, and sorting a copy gives O(n log n). Neither meets both. But I know what the list should add up to: 0 + 1 + … + n is n(n + 1) / 2. The missing number is whatever the list lacks of that.
// 0 + 1 + ... + n is n(n + 1) / 2; what the array lacks of that sum is the missing value.
// Time O(n): one pass. Memory O(1). The largest sum, about 5 * 10^7, is far below 2^53.
export function missingNumberSum(nums: number[]): number {
const n = nums.length;
let sum = 0;
for (const x of nums) sum += x;
return (n * (n + 1)) / 2 - sum;
}
The lab names the other two missingNumberSet and missingNumberSort. In atlimit.ts they took 0.7 ms and 1.5 ms, and the sum took 0.4 ms.
Interviewer: In a language with 32-bit integers, that sum could overflow for a larger n. Can you avoid adding at all?
Candidate: XOR. x ^ x is 0 and x ^ 0 is x, and the order doesn’t matter. If I XOR every index 0 to n with every value, each value that’s present meets its own index and cancels. Only the missing one has no partner.
// XOR every index 0..n with every value: each present value cancels its own index (x ^ x = 0), the missing one stays.
// Time O(n): one pass. Memory O(1). No sum, so no size limit, as long as values fit in 32 bits.
function missingNumber(nums: number[]): number {
let result = nums.length;
for (let i = 0; i < nums.length; i++) result ^= i ^ nums[i];
return result;
}
export { missingNumber };
This is the version to paste into LeetCode.
Candidate: The loop’s indexes go from 0 to n − 1, so result starts at n to mix in the last one.
Interviewer: Trace your example.
Figure 6 shows result after each pass, for [4, 0, 5, 1, 3] and n = 5.
i nums[i] result ^ i ^ nums[i] result
start 5
0 4 5 ^ 0 ^ 4 1
1 0 1 ^ 1 ^ 0 0
2 5 0 ^ 2 ^ 5 7
3 1 7 ^ 3 ^ 1 5
4 3 5 ^ 4 ^ 3 2 returned
Figure 6: the numbers mixed in are 0 to 5 once each and 4, 0, 5, 1, 3 once each; every number but 2 appears twice and cancels.
Candidate: For [0], result starts at 1, and 1 ^ 0 ^ 0 is 1.
Interviewer: Final cost?
Candidate: O(n) time, one pass. O(1) memory, one number. In JavaScript it only works for values that fit in 32 bits, because ^ converts with ToInt32. Here they’re at most 10⁴.
In atlimit.ts, missingNumber took 0.1 ms at 10⁴.
Interviewer: In JavaScript, is the sum version unsafe?
The Candidate’s answer
Candidate: No. A Number holds integers exactly up to 2⁵³, and the largest sum here is about 5 × 10⁷. XOR has no carries, so it’s the safer habit in a language with fixed-size integers.
Interviewer: What if two numbers were missing?
The Candidate’s answer
Candidate: One equation isn’t enough for two unknowns. With the sum and the sum of squares, I get two equations.
Candidate: Or the XOR of everything gives a ^ b, and any 1 bit in it is a bit where a and b differ. So I split all numbers by that bit and XOR each group, which gives a and b separately.
This version isn’t in the lab.
Two mistakes are common here.
sort()without a compare function. It sorts as strings, so[10, 2, 0, 1, 3, 4, 5, 6, 7, 8]sorts to[0, 1, 10, 2, …]. The first index that doesn’t match its value is then 2, instead of 9. Pass(a, b) => a - b(MDN onArray.prototype.sort).- Starting the XOR at 0. Then n is never mixed in. For
[4, 0, 5, 1, 3]it returns 7 (5 ^ 2) instead of 2. This one has nomistakes.tsline; a scratch run gave that output. Start atnums.length.
Lab folder: module-12/0268-missing-number/ in the course repository.
371. Sum of Two Integers
371. Sum of Two Integers is rated Medium. Add two integers without using the + or - operators.
−1000 ≤ a, b ≤ 1000
The signature is function getSum(a: number, b: number): number. Try it on LeetCode first.
Hint
Add 1101 and 1011 by hand, column by column. Which operator gives each column’s digit if you ignore the carry? Which gives the carries?
Interviewer: Add a and b, without + or -.
Candidate: Are +=, ++ and -- out too? They add as well.
Interviewer: Yes, out.
Candidate: And negative numbers are in. The result is between −2000 and 2000, so there’s no overflow to worry about. My example has a carry in almost every column: 13 + 11, 1101 + 1011.
a b expected
13 11 24 1101 + 1011 = 11000
-1 1 0 the carry runs off the top
1000 -1000 0
-1000 -1000 -2000
Candidate: The first answer is how a circuit adds: go through the 32 columns from the right. Each column’s digit is 1 when an odd number of the two bits and the carry are 1. The next carry is 1 when at least two of the three are.
// A ripple-carry adder: walk the 32 bit positions, as a circuit adds one column at a time.
// Time O(32): one step per bit position, whatever the inputs. Memory O(1).
export function getSumBitByBit(a: number, b: number): number {
let result = 0;
let carry = 0;
for (let i = 0; i < 32; i++) {
const x = (a >>> i) & 1;
const y = (b >>> i) & 1;
result |= (x ^ y ^ carry) << i; // the sum bit of this column
carry = (x & y) | (x & carry) | (y & carry); // at least two of the three are 1
}
return result; // | and << work on 32-bit signed values, so bit 31 reads back as the sign
}
Candidate: It always takes 32 steps, O(1) memory. Negative numbers work because the result’s bit 31 reads back as the sign, which is two’s complement.
Interviewer: It always walks all 32 columns. Can it stop sooner?
Candidate: Yes, by doing every column at once. a ^ b is every column’s digit without carries, and (a & b) << 1 is every carry, moved to the column it goes into. Adding those two is the same problem, so I repeat until there’s no carry.
// XOR adds without carries; AND, shifted left, is the carries. Repeat until no carry is left.
// Time O(32): each round the lowest possible carry position moves up by at least one bit, and << drops bit 32.
// Memory O(1).
function getSum(a: number, b: number): number {
while (b !== 0) {
const carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
export { getSum };
This is the version to paste into LeetCode.
Interviewer: Trace 13 + 11.
Figure 7 shows a and b at the start of each round, and what the round computes from them.
round a b a ^ b (a & b) << 1
1 01101 01011 00110 10010
2 00110 10010 10100 00100
3 10100 00100 10000 01000
4 10000 01000 11000 00000 b is 0: return 11000 = 24
Figure 7: each round adds without carries and moves the carries one column left; when no carry is left, a holds the sum.
Pause and predict. How many rounds does getSum(-1, 1) take?
Candidate: −1 is 32 ones. Adding 1 makes a carry that moves up one column per round, through all 32 bits. On the 32nd round << shifts it out of bit 31, it’s dropped, and b becomes 0. So 32 rounds, and the result is 0.
mistakes.ts counts the rounds for every pair in −1000 to 1000. The most is 32, first at −999 + 999, and −1 + 1 takes 32 too.
Interviewer: Final cost?
Candidate: At most 32 rounds, so O(1) for 32-bit integers, or O(w) for w-bit ones. O(1) memory.
The loop ends for negative numbers because of the 32-bit conversion from the pattern section. << keeps only the low 32 bits, so a carry past bit 31 disappears instead of growing forever.
Interviewer: How would you subtract?
The Candidate’s answer
Candidate: In two’s complement, −b is ~b + 1. So a - b is getSum(a, getSum(~b, 1)), with no - anywhere.
This version isn’t in the lab.
Interviewer: Why at most 32 rounds?
The Candidate’s answer
Candidate: After round k, the carries can only sit in column k or higher, because each round shifts them left by one. After 32 rounds the lowest possible carry is past bit 31, and << drops it. So b must be 0 by then.
Interviewer: What about numbers larger than 32 bits?
The Candidate’s answer (stretch)
Candidate: Then I’d use BigInt, which has no 32-bit limit. But a negative BigInt has endless 1 bits on the left, so the carry loop wouldn’t end. I’d wrap each step to a fixed width with BigInt.asIntN(64, …), which does what ToInt32 does here, for 64 bits.
This version isn’t in the lab.
One mistake is common here.
- The carry from the new
a. Writinga = a ^ bfirst and thenb = (a & b) << 1computes the carry from the wrong number. For 13 + 11 it returns 2 instead of 24. Save the carry before you overwritea.
Lab folder: module-12/0371-sum-of-two-integers/ in the course repository.
Measured: Maximum Subarray, every run against one pass
This measurement checks the opening’s claim: summing every run grows with n³, and Kadane’s algorithm grows with n. It also times the two middle solutions, and the end of the script times the mock interview’s problem, below.
// measure.ts: Module 12's measurement. 53. Maximum Subarray, summing every subarray against Kadane's one pass.
// Then a probe for the mock interview (5. Longest Palindromic Substring) at its limit, n = 1,000.
// Run from the repository root: node module-12/measure.ts
import { bench } from "../shared/bench.ts";
import { maxSubArrayCubic, maxSubArrayQuadratic, maxSubArrayDivide, maxSubArray } from "./0053-maximum-subarray/solution.ts";
import { longestPalindromeBrute, longestPalindromeTable, longestPalindrome } from "./0005-longest-palindromic-substring/solution.ts";
let sink = 0;
// n items, each a random whole number in -10^4..10^4 (the page's range).
const randomNums = (n: number) => Array.from({ length: n }, () => Math.floor(Math.random() * 20_001) - 10_000);
const small = [400, 800, 1_600];
bench("every subarray, summed from scratch (maxSubArrayCubic)", small, randomNums, (a) => (sink += maxSubArrayCubic(a)));
bench("every start, running sum (maxSubArrayQuadratic)", small, randomNums, (a) => (sink += maxSubArrayQuadratic(a)));
bench("divide and conquer (maxSubArrayDivide)", small, randomNums, (a) => (sink += maxSubArrayDivide(a)));
bench("Kadane (maxSubArray)", small, randomNums, (a) => (sink += maxSubArray(a)));
const large = [100_000, 1_000_000];
bench("divide and conquer at the limit and above", large, randomNums, (a) => (sink += maxSubArrayDivide(a)));
bench("Kadane at the limit and above", large, randomNums, (a) => (sink += maxSubArray(a)));
// One timed run per size: at 10^5 a single run took about 10 s in a first try, so stop at half the limit.
bench("running sum toward the limit (maxSubArrayQuadratic)", [25_000, 50_000], randomNums, (a) => (sink += maxSubArrayQuadratic(a)), 1);
// Mock interview probe: one letter repeated is the worst case (every substring is a palindrome, every check runs
// to the middle, every center expands to an edge). Random letters are the easy case: most checks stop at once.
const sameLetter = (n: number) => "a".repeat(n - 1) + "ab"[Math.floor(Math.random() * 2)];
const randomLetters = (n: number) => Array.from({ length: n }, () => "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)]).join("");
const sizes5 = [250, 500, 1_000];
bench("5: every substring, one letter (longestPalindromeBrute)", sizes5, sameLetter, (s) => (sink += longestPalindromeBrute(s).length));
bench("5: every substring, random letters (longestPalindromeBrute)", sizes5, randomLetters, (s) => (sink += longestPalindromeBrute(s).length));
bench("5: table, one letter (longestPalindromeTable)", sizes5, sameLetter, (s) => (sink += longestPalindromeTable(s).length));
bench("5: expand around centers, one letter (longestPalindrome)", sizes5, sameLetter, (s) => (sink += longestPalindrome(s).length));
console.log(`\nsink ${sink}`);
bench runs each size once to warm up, then five times on fresh inputs, or once for the running sum toward the limit. It prints the median and how many times slower each size is than the one before. sink adds up the answers, so V8 can’t skip the calls.
Pause and predict. From 800 to 1,600 numbers, how many times slower should the cubic version get? And the one pass?
Here is what node module-12/measure.ts printed:
every subarray, summed from scratch (maxSubArrayCubic)
n median ms x prev
400 5.30
800 41.73 7.9
1,600 329.63 7.9
every start, running sum (maxSubArrayQuadratic)
n median ms x prev
400 0.09
800 0.17 2.0
1,600 0.65 3.8
divide and conquer (maxSubArrayDivide)
n median ms x prev
400 0.07
800 0.04 0.6
1,600 0.09 2.1
Kadane (maxSubArray)
n median ms x prev
400 0.02
800 0.01 0.5
1,600 0.02 2.0
divide and conquer at the limit and above
n median ms x prev
100,000 4.50
1,000,000 46.09 10.2
Kadane at the limit and above
n median ms x prev
100,000 0.10
1,000,000 0.92 9.7
running sum toward the limit (maxSubArrayQuadratic)
n median ms x prev
25,000 157.88
50,000 638.66 4.0
5: every substring, one letter (longestPalindromeBrute)
n median ms x prev
250 5.18
500 40.56 7.8
1,000 321.47 7.9
5: every substring, random letters (longestPalindromeBrute)
n median ms x prev
250 0.11
500 0.39 3.6
1,000 1.57 4.0
5: table, one letter (longestPalindromeTable)
n median ms x prev
250 0.40
500 1.28 3.2
1,000 5.29 4.1
5: expand around centers, one letter (longestPalindrome)
n median ms x prev
250 1.02
500 0.45 0.4
1,000 1.78 4.0
sink 132735059
These numbers come from one run on an Apple M2 laptop with macOS and Node.js 24.22.1. Your numbers will differ, but the ratios should look alike.
The cubic version grew 7.9 times per doubling, close to the 8 that O(n³) predicts. At 10⁵ it would be about (10⁵ / 1,600)³ ≈ 244,000 times its 1,600 time: roughly 22 hours, extrapolated, not run. The running sum grew 3.8 and 4.0 times per doubling, as O(n²) predicts, and took 4,355.5 ms at 10⁵ in atlimit.ts.
At small sizes, divide and conquer and the one pass take under 0.1 ms, and their ratios are noise. At the limit and above they show their shape. Kadane’s algorithm grew 9.7 times for 10 times the numbers, which is linear. Divide and conquer grew 10.2 times, a little over 10, as O(n log n) predicts. At 10⁵, Kadane’s 0.10 ms is over 3,000 times less than the cubic version’s 329.63 ms at only 1,600 numbers.
Underneath: numbers and bits in JavaScript
The greedy solutions keep a few plain Numbers. A Number holds integers exactly up to 2⁵³, and the largest totals here are 10⁹ (53) and about 5 × 10⁷ (268), so there’s no overflow check to write. A language with 32-bit integers would need one.
The bit operators are different. &, |, ^, ~, << and >> convert their operands with ToInt32, through the specification’s NumberBitwiseOp for the first three. >>> converts its left side with ToUint32 and fills with zeros (unsignedRightShift). Every shift takes its count modulo 32 (leftShift), so 1 << 32 is 1.
That one conversion explains this module’s bit behavior. 371’s carry loop ends for negative numbers, because a carry past bit 31 is dropped. >> never reaches 0 on a value with bit 31 set, because it copies the sign bit (-1 >> 1 is −1). 1 << 31 is negative, and (1 << 31) >>> 0 is 2,147,483,648. XOR tricks work only for values that fit in 32 bits.
BigInt has no width limit, but it has no >>>, and it doesn’t mix with Numbers. DSA Module 12 prints each of these cases, and DSA Module 9 covers greedy choices and how to test them.
A full mock interview: 5. Longest Palindromic Substring
This is one interview, from the first question to the last follow-up, with no notes between the lines. The problem is one this course hasn’t shown. It’s on all four lists the course draws from, and it’s free on LeetCode.
5. Longest Palindromic Substring is rated Medium. Given a string, return a longest piece of it, in neighboring characters, that reads the same forwards and backwards. If several pieces have the longest length, any one is accepted.
1 ≤ s.length ≤ 1000sholds only digits and English letters.
The signature is function longestPalindrome(s: string): string. Before you read on, do the interview yourself. Set a timer for 45 minutes, say everything out loud, and write down the minute at which you start each step.
Hint
Every palindrome has a middle. Where can the middle of a palindrome be?
None of the company pages we read gives a length for a coding interview. 45 minutes is this course’s choice, and so is the time for each step in Table 1: they’re our advice, not a company’s rule.
| Minutes | Step |
|---|---|
| 0 to 4 | Restate and clarify |
| 4 to 8 | Examples and edge cases |
| 8 to 13 | The naive solution and its cost |
| 13 to 16 | Find the repeated work |
| 16 to 23 | Optimize |
| 23 to 32 | Code |
| 32 to 38 | Test out loud |
| 38 to 40 | Final cost |
| 40 to 45 | Follow-ups |
Table 1: a 45-minute plan for the nine steps; code and testing get the most time, and the follow-ups get the last five minutes.
Minute 0: restate and clarify.
Interviewer: Given a string, return its longest piece that reads the same in both directions.
Candidate: So a substring, neighboring characters only, not a subsequence that skips some?
Interviewer: A substring.
Candidate: If two different substrings tie for the longest, can I return either one?
Interviewer: Either.
Candidate: Do upper and lower case count as different? And digits are characters like any other?
Interviewer: Case matters. Digits are ordinary characters.
Candidate: And the length is 1 to 1,000. O(n²) is 10⁶ steps, which is easy. O(n³) is 10⁹ on paper, so that’s my upper limit to think about.
Minute 4: examples and edge cases.
Candidate: My example is a log line, "xlevelup". The answer is "level". Here are some edge cases.
s expected
"xlevelup" "level" my example
"q" "q" one character
"abcd" "a" no repeats: any single character
"zzz" "zzz" one letter: the whole string
Interviewer: Fine.
Minute 8: the naive solution.
Candidate: The first answer checks every substring from both ends and keeps the longest that passes.
function isPalindrome(s: string, left: number, right: number): boolean {
while (left < right) {
if (s[left] !== s[right]) return false;
left++;
right--;
}
return true;
}
// Check every substring, keep the longest palindrome.
// Time O(n^3): about n^2 / 2 substrings, each checked in up to n / 2 steps. Memory O(1) besides the answer.
export function longestPalindromeBrute(s: string): string {
let bestStart = 0;
let bestLength = 1;
for (let start = 0; start < s.length; start++) {
for (let end = start; end < s.length; end++) {
if (isPalindrome(s, start, end) && end - start + 1 > bestLength) {
bestStart = start;
bestLength = end - start + 1;
}
}
}
return s.slice(bestStart, bestStart + bestLength);
}
Interviewer: What does it cost?
Candidate: About n² / 2 substrings, each checked in up to n / 2 steps, so O(n³) time and O(1) memory. On random letters most checks stop at the first pair, so it’s much faster. But on one repeated letter every check runs to the middle. At 1,000 that’s about 10⁸ compares, at the edge of the budget. It might pass, but I wouldn’t count on it.
Minute 13: find the repeated work.
Interviewer: Where does it waste time?
Candidate: To check s[i..j], it compares the two ends and then checks s[i+1..j-1]. But s[i+1..j-1] is a shorter substring that it already checked on its own. So each check redoes all the checks inside it.
Minute 16: optimize.
Candidate: I can save those answers. A table isPal[i][j] is true when s[i] equals s[j] and the inside is a palindrome. If I fill it by length, from 1 up, the inside is always filled first. That’s O(n²) time, but also O(n²) memory: 10⁶ flags.
Interviewer: Can you do it without the table?
Candidate: Yes. Each table cell only extends a shorter palindrome by one character on each side. So I can start from the middle of every palindrome and grow it outwards while the two ends match. Every palindrome has a middle character, so I try each character as a center. That’s n centers, each growing up to n / 2 steps: O(n²) time and O(1) memory.
Interviewer: Go ahead.
Minute 23: code.
Candidate: I’ll keep the best start and length. expand takes a left and a right index, moves them outwards while they match, and stops one step past each end. So the length is right - left - 1, and the palindrome starts at left + 1.
function longestPalindrome(s: string): string {
let bestStart = 0;
let bestLength = 1;
const expand = (left: number, right: number): void => {
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--;
right++;
}
const length = right - left - 1; // the loop stopped one step past each end
if (length > bestLength) {
bestStart = left + 1;
bestLength = length;
}
};
for (let center = 0; center < s.length; center++) {
expand(center, center);
}
return s.slice(bestStart, bestStart + bestLength);
}
export { longestPalindrome };
Candidate: The loop calls expand(center, center) for each character. bestLength starts at 1, because any single character is a palindrome and the string isn’t empty.
Minute 32: test out loud.
Interviewer: Walk me through your example.
Candidate: Here’s "xlevelup". Most centers stop at once, because their neighbors differ. Center 3, the v, grows three times.
[x][l][e][v][e][l][u][p]
0 1 2 3 4 5 6 7
^ center 3: left = right = 3
^ ^ e = e
^ ^ l = l
^ ^ x != u: stop, length 6 - 0 - 1 = 5
Figure 8: left and right move out from center 3 while the ends match, and stop one step past "level"; so the length is right - left - 1.
Candidate: So bestStart is 1, bestLength is 5, and it returns "level". For "q", the loop runs once, nothing grows, and it returns "q".
Interviewer: Try a palindrome of even length.
Candidate: Say "afternoony". The answer should be "noon". Center 6 is the first o. Its neighbors are n and o, which differ, so it stops at length 1. Center 7, the second o, has o and n. Also length 1.
Candidate: That’s a bug. "noon" has no middle character: its middle is the gap between the two os. My code never starts there, so it returns "a". Every even-length palindrome is missed, and “every palindrome has a middle character” was only true for odd lengths.
Candidate: The fix is a second center at each gap: expand(center, center + 1) starts with the two neighbors and grows the same way. So there are 2n − 1 centers.
// Expand around each of the 2n - 1 centers: a character (odd length) or the gap between two (even length).
// Time O(n^2): 2n - 1 centers, each expands up to n / 2 steps. Memory O(1) besides the answer.
function longestPalindrome(s: string): string {
let bestStart = 0;
let bestLength = 1;
const expand = (left: number, right: number): void => {
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--;
right++;
}
const length = right - left - 1; // the loop stopped one step past each end
if (length > bestLength) {
bestStart = left + 1;
bestLength = length;
}
};
for (let center = 0; center < s.length; center++) {
expand(center, center); // odd length: "aba"
expand(center, center + 1); // even length: "abba"
}
return s.slice(bestStart, bestStart + bestLength);
}
export { longestPalindrome };
Candidate: Now the gap between 6 and 7 grows twice.
[a][f][t][e][r][n][o][o][n][y]
0 1 2 3 4 5 6 7 8 9
^ ^ gap 6-7: o = o
^ ^ n = n
^ ^ r != y: stop, length 9 - 4 - 1 = 4
Figure 9: an even-length palindrome grows from a gap, so expand(6, 7) finds "noon", which no character center can.
Candidate: That gives bestStart 5 and length 4, so "noon". And "xlevelup" still gives "level": the gap centers only add candidates. When center + 1 is past the end, the loop’s right < s.length check stops it at once.
Minute 38: final cost.
Interviewer: Final cost?
Candidate: 2n − 1 centers, each growing up to n / 2 steps, so O(n²) time. O(1) memory besides the returned string. At 1,000 that’s at most about 10⁶ steps.
Minute 40: follow-ups.
Interviewer: Can you do better than O(n²)?
The Candidate’s answer (stretch)
Candidate: Yes, in O(n), with Manacher’s algorithm. It reuses the mirror image of a palindrome it has already found, so a center inside a long palindrome starts from a known length instead of from 1. I couldn’t write it from memory in five minutes, and I’d say so.
Manacher’s algorithm comes from Glenn Manacher’s 1975 paper in the Journal of the ACM. This course doesn’t teach it, and it isn’t in the lab.
Interviewer: What if I asked for the number of palindromic substrings, not the longest?
The Candidate’s answer
Candidate: The same 2n − 1 centers. Each successful step of expand is one more palindrome, so I count steps instead of keeping the best. Still O(n²) time and O(1) memory.
That’s LeetCode’s 647. Palindromic Substrings, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: Someone suggests reversing the string and finding the longest substring the two have in common. Does that work?
The Candidate’s answer
Candidate: Not always. For "xlevelup" it finds "level". But for "abcxyzcba" the reverse is "abczyxcba", and "abc" appears in both, though it isn’t a palindrome. The common piece also has to sit at mirrored positions, and checking that is more work than expanding around centers.
Interviewer: That’s time. Thank you.
That’s the end of the interview. The Interviewer had to ask for an even-length case. The Candidate found the bug from that case, explained it, and fixed it with one line, which Meta’s full loop guide counts in your favor. But the bug was already in the Candidate’s belief at minute 16, and an even-length case in the list at minute 4 would have caught it without help. "zzzz" instead of "zzz" would have done it: mistakes.ts shows that the first version returns "zzz" for it.
The measurement above timed this problem at its limit. Checking every substring took 321.47 ms on 1,000 copies of one letter and 1.57 ms on random letters, so the brute force’s cubic cost needs long palindromes to show. The table took 5.29 ms and the centers 1.78 ms on the one-letter string. The lab also has the table version, longestPalindromeTable, and its tests check all three against a brute force on 500 random strings.
Three mistakes are common here.
- Character centers only. The mock’s wrong turn.
"afternoony"returns"a"instead of"noon". Expand from each gap too. - Off by one after expanding. The loop stops one step past each end, so the length is
right - left - 1and the start isleft + 1. Usingright - left + 1adds 2 to every length. - Common substring with the reverse. For
"abcxyzcba"it returns"abc", which isn’t a palindrome. Use centers.
Lab folder: module-12/0005-longest-palindromic-substring/ in the course repository. The Candidate’s first version is in first-try.ts there, and mistakes.ts prints its output.
Score your practice with a rubric
Table 2 turns the nine steps into a rubric: for each step, what a weak answer and a strong answer look like. The last column says where each row comes from. Seven rows rest on a hiring company’s own interview page, and the other two are our advice.
| Step | Weak answer | Strong answer | Source |
|---|---|---|---|
| Restate and clarify | Starts coding at once; guesses at unclear points; never asks about the size | Restates in own words; asks two to four questions (empty input, duplicates, negatives, ties, size); says each assumption | Google, Meta, Amazon, Microsoft |
| Examples and edge cases | Uses only the example it was given | Writes an own example and two or three edge cases with expected outputs, before coding | Microsoft, Amazon, Meta; “before coding” is our advice |
| Naive solution | Stays silent waiting for a clever idea, or starts a half-remembered optimal one and can’t finish it | States a correct simple solution and its cost, and says whether it fits the limits | Amazon, Meta |
| Find the repeated work | Asks “can I do better?” with no direction | Names the work the naive solution repeats, or the fact it ignores | Our advice |
| Optimize | Jumps to a pattern without saying why it’s correct | Names the pattern, why it’s correct and its cost, and compares it with the naive one | Meta, Amazon |
| Code | Codes in silence; unclear names | Says the plan first, then explains decisions while coding; clear names | Meta, Amazon, Microsoft |
| Test out loud | Says “done” without running anything | Traces an own example line by line, then an edge case; finds and fixes own bugs | Microsoft, Meta, Amazon |
| Final cost | Gives the time only, or a wrong cost | Gives time and memory in Big O, each with one line on why | Meta, Amazon, Microsoft |
| Follow-ups | Treats the question as an attack, or restarts from scratch | Answers from the working solution: what changes and what it costs | Our advice |
Table 2: each step of the method with a weak and a strong answer; “our advice” marks a row no company page we read supports.
The cells paraphrase the pages listed in Module 1’s sources, read on 2026-11-20. Meta’s two guides are the PDFs linked from the pages above. For the “Follow-ups” row, the closest company line is Google’s: your first answer may need refining and more explanation.
None of these pages publishes a score, a weight per step or a pass mark, so the rubric has none. Use it to find your weakest step. In the mock above, the Candidate’s weak row was “Examples and edge cases”: no even-length case at minute 4.
Practice after the course
The method is the same nine steps, so practice is repeating them under a clock until each step comes without thinking about the order. We don’t know of a study that says how many problems or sessions are enough, so this plan sets no number. It’s a routine for one session, which you can repeat as often as you like.
- Pick a problem. Either one from this course that you last saw at least a week ago, or a new one from the four lists that the course didn’t work. For a new one, find its sign in Figure 10 below; if no row fits, that’s a pattern this course doesn’t cover.
- Start a 45-minute timer and talk. Say every step out loud, even alone, and write the minute at which you start each one. Use Table 1’s minutes as marks. When you pass one, note it and go on, because in an interview the clock doesn’t stop.
- No hints until the timer ends. If you’re stuck, say what you’re stuck on and try the naive solution, as the Candidate does.
- Test it for real. After the timer, turn your step-2 cases into a
solution.test.tslike the lab’s, and runnode --test. In the interview you traced by hand; here you find out whether the trace was right. - Score it. Mark each row of Table 2 weak or strong, and write one sentence on what you’d say instead in the weakest row.
- Put it back. If any row was weak, put the problem back on your list and redo it from a blank file next time.
You can also give an AI tool the Interviewer’s part. Paste this prompt and fill in the first line. It asks the tool to give no hints, to push on the cost and the tests, and to score you with Table 2’s rows.
You are the interviewer in a 45-minute coding interview practice session.
I am the candidate. I write TypeScript and talk through my thinking as I go.
Problem: <a LeetCode problem's number and title, or "choose one for me">
If I wrote "choose one for me", pick a well-known problem that is free on
LeetCode.
Rules for the session:
1. State the problem in your own words in two to four sentences, with its
input limits. Then wait.
2. Answer my clarifying questions briefly. If I start without asking any,
ask me one question about the input.
3. Do not give hints, name a pattern or show code unless I ask for a hint.
4. When I give a solution, ask for its time and memory cost in Big O if I
don't give it.
5. If my solution is too slow for the limits, ask me what work it repeats.
Don't tell me.
6. While I write code, stay quiet unless I ask something.
7. When I say I'm done, ask me to trace one example through the code. If my
code fails on some kind of input, ask me for a test of that kind, without
saying what the bug is.
8. After a working answer, ask two follow-up questions: a larger input, a
stream, less memory or a changed rule.
9. I will write the minutes since the start in brackets, like [12]. At [40],
move to follow-ups. At [45], end the session.
After the session, score me on these nine steps: restate and clarify;
examples and edge cases; the naive solution and its cost; find the repeated
work; optimize; code; test out loud; final cost; follow-ups. For each step,
say "weak" or "strong", quote what I said that shows it, and give one thing
to do differently. Do not give an overall grade, and do not say whether I
would pass.
The tool has costs. It can state wrong limits for a problem or a wrong cost for your code, so check limits on the LeetCode page and run your code yourself. It can’t see a clock, which is why the prompt has you write the minutes. And it may give a hint too early or praise a wrong answer; when that happens, say so and ask it to follow rule 3 or 7.
Course cheat sheet
Start every problem by reading its limits for the target cost (Module 1). Then look for its sign. Figure 10 maps the signs from all twelve modules to the module that works them.
sign in the problem try first module
partner value, "seen before?", group, count Map, Set, counts 1
sorted input, a pair or group with a given sum two pointers 2
longest or shortest run with a rule inside sliding window 3
brackets, nesting; nearest larger or smaller stack, monotonic 4
sorted data; a yes-or-no that flips only once binary search 5
a ListNode; relink in place; a loop, a middle list pointers 6
a TreeNode; a question about every subtree recursion, levels 7
k-th largest, k closest, median; [start, end] heap; sort intervals 8
grid regions, reach; links; prerequisites BFS, DFS, Kahn 9
"list every", small limits; prefixes of words backtracking, trie 10
fewest, most, longest, how many ways dynamic programming 11
one pass with a safe rule; a 32-bit integer greedy, bit operators 12
Figure 10: the limits give the target cost, and the sign gives the first pattern to try; when two rows fit, try the one whose cost meets the target.
Pick a problem from the four lists that this course didn’t work, find its row in Figure 10, and run the practice routine above on it.
Sources
- LeetCode problem pages, checked on 2026-11-20: 53, 55, 134, 191, 268, 371, 5, and 918, 45 and 647 for follow-ups.
- Jon Bentley, “Programming Pearls: Algorithm Design Techniques”, Communications of the ACM 27(9):865–873, September 1984, DOI 10.1145/358234.381162. The history of the maximum subarray problem and Kadane’s linear algorithm.
- Glenn K. Manacher, “A New Linear-Time ‘On-Line’ Algorithm for Finding the Smallest Initial Palindrome of a String”, Journal of the ACM 22(3):346–351, July 1975, DOI 10.1145/321892.321896.
- Kevin Wayne, lecture slides for Kleinberg and Tardos, Algorithm Design, chapter 4 (greedy stays ahead, and the exchange argument).
- Sean Eron Anderson, Bit Twiddling Hacks, Stanford: counting bits set, Brian Kernighan’s way, and by lookup table.
- Interview pages, read on 2026-11-20. Google: Interview tips. Meta: Preparing for your technical screen and Preparing for your full loop interview, with the interview guides linked from each. Amazon: SDE II interview prep. Microsoft: Technical interviewing and Interview tips.
- ECMAScript specification: ToInt32, ToUint32, NumberBitwiseOp, Number::leftShift, Number::unsignedRightShift.
- MDN:
Array.prototype.sort. - Node.js documentation: TypeScript, test runner.