Here is a first answer to 15. 3Sum: try every group of three positions, and keep each zero-sum group once.
// O(n^3) time, O(k) memory for k distinct triplets: tries every triple of indexes, about n^3 / 6 of them.
export function threeSumBrute(nums: number[]): number[][] {
const seen = new Set<string>();
const result: number[][] = [];
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
for (let k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] !== 0) continue;
const triplet = [nums[i], nums[j], nums[k]].sort((a, b) => a - b);
const key = triplet.join(",");
if (!seen.has(key)) {
seen.add(key);
result.push(triplet);
}
}
}
}
return result;
}
LeetCode allows up to 3,000 numbers, which is about 4.5 × 10⁹ triples, 45 times the budget from Module 1. In one run these loops took 1,733.90 ms at 1,600 numbers and grew 8 times per doubling, so 3,000 numbers would take about 11 seconds (an estimate from that growth). Sorting first and walking two pointers took 11.46 ms at 3,000.
This module works five problems where two indexes moving toward each other replace a nested loop. Each one follows the nine steps from Module 1, from the naive solution to the optimal one.
After this module, you can:
- spot when two indexes that move inward can replace a nested loop, and say why each move is safe
- use sorted input to rule out a whole row of pairs with one comparison, in O(1) extra memory
- fix one value to turn 3Sum into Two Sum II, and skip repeated answers without a set
- turn a rescan at every position into running maximums, and then into two pointers with O(1) memory
The code for this module is in module-02/ of the course repository, and node --test "module-02/**/*.test.ts" from its root runs every test. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.
The pattern: two pointers that move toward each other
In Module 1, two pointers were a middle step for Two Sum. Here they’re the whole answer. Two pointers are two indexes into the same array that each move in one direction only, so together they make at most n moves. DSA Module 2 teaches them, with the other shapes they come in.
Every problem in this module starts one pointer at each end. Each step looks at the two items under the pointers and drops one of them for good, so the loop runs at most n – 1 times. A fact about the input makes the drop safe: the array is sorted, the dropped wall is the shorter one, or the dropped side has the smaller maximum.
Signs that point to this pattern:
- a sorted array and a question about a pair or a group: a sum, “closest to”
- comparing a sequence from both ends
- an answer set by the two ends you pick and the distance between them
- each position limited by the largest value on each side of it
The cost is that every move needs a reason. If you can’t say why the dropped item can’t be in a better answer, the pointers give wrong answers. And when the input isn’t sorted, sorting it first costs O(n log n) time and loses the original positions.
Rule: If one comparison proves that the item at one end can’t be in a better answer, drop it and move that pointer inward.
125. Valid Palindrome
125. Valid Palindrome is rated Easy. A palindrome reads the same from both ends. You get a string, keep only its letters and digits, treat uppercase and lowercase as the same, and return whether what is left is a palindrome. A string with no letters or digits counts as one.
1 ≤ s.length ≤ 2 × 10^5sholds only printable ASCII characters
The signature is function isPalindrome(s: string): boolean. Try it on LeetCode first.
Hint
You need to compare the first kept character with the last one, then the second with the second to last. Can you do that on the original string, without building a new one?
Interviewer: First problem. Is this string a palindrome?
Candidate: I keep only letters and digits, ignore case, and check that the rest reads the same both ways. Which characters count as letters and digits?
Interviewer: ASCII letters and digits. The string holds only printable ASCII.
Candidate: So spaces, punctuation and the underscore are skipped. And A equals a?
Interviewer: Yes, case doesn’t matter.
Candidate: Can the string hold nothing but punctuation?
Interviewer: It has at least one character, but all of them can be punctuation.
Candidate: Then nothing is left to compare, and I return true.
The interviewer and the candidate are invented. The problems, limits and timings are real.
Candidate: Here’s my example, and three edge cases.
s expected
"Top spot!" true keeps "topspot"
".,!?" true nothing left after skipping
"0P" false a digit never equals a letter
"a_" true "_" is not a letter or a digit
Candidate: The obvious solution builds the cleaned string, reverses it and compares. I’ll write two helpers on character codes first, so I don’t need a regex.
function isAlphanumeric(code: number): boolean {
return (
(code >= 48 && code <= 57) || // 0-9
(code >= 65 && code <= 90) || // A-Z
(code >= 97 && code <= 122) // a-z
);
}
function toLower(code: number): number {
return code >= 65 && code <= 90 ? code + 32 : code;
}
// O(n) time, O(n) memory: builds a cleaned copy and its reverse, each up to n characters.
export function isPalindromeCleaned(s: string): boolean {
let cleaned = "";
for (const ch of s) {
if (isAlphanumeric(ch.charCodeAt(0))) cleaned += ch.toLowerCase();
}
const reversed = cleaned.split("").reverse().join("");
return cleaned === reversed;
}
Candidate: That’s O(n) time, one pass to clean, one to reverse and one to compare. It’s also O(n) memory for the two copies. With n up to 2 × 10⁵, it’s far inside the budget, so it passes.
atlimit.ts in the module folder times one call of each naive and final solution at LeetCode’s limit. One call is a rough number, and yours will differ. At 200,000 characters, isPalindromeCleaned took 10.8 ms.
Interviewer: It’s fast enough. Can you do it without the copies?
Candidate: The copies are the waste. I build two new strings only to read each one once. I can read the original from both ends instead.
Candidate: left starts at 0 and right at the last index. If the character under either pointer isn’t a letter or digit, I skip it. Otherwise I compare the two in lowercase, return false on a mismatch, and move both inward.
// O(n) time, O(1) memory: each pointer moves only inward, so each character is read at most once.
function isPalindrome(s: string): boolean {
let left = 0;
let right = s.length - 1;
while (left < right) {
if (!isAlphanumeric(s.charCodeAt(left))) {
left++;
} else if (!isAlphanumeric(s.charCodeAt(right))) {
right--;
} else {
if (toLower(s.charCodeAt(left)) !== toLower(s.charCodeAt(right))) return false;
left++;
right--;
}
}
return true;
}
export { isPalindrome };
Candidate: toLower adds 32 to an uppercase code, because A is 65 and a is 97.
Interviewer: Walk me through your example.
Figure 1 shows each step of the Candidate’s trace on "Top spot!".
s [T] [o] [p] [ ] [s] [p] [o] [t] [!]
0 1 2 3 4 5 6 7 8
step left right what happens
1 0 T 8 ! "!" is not a letter or digit: right--
2 0 T 7 t t equals t: left++, right--
3 1 o 6 o o equals o: left++, right--
4 2 p 5 p p equals p: left++, right--
5 3 4 s " " is not a letter or digit: left++
4 4 left is not < right: return true
Figure 1: each step moves at least one pointer inward, so the loop ends after at most n steps.
Candidate: For "0P", both are kept, and the codes of 0 and p differ, so it returns false. For ".,!?", left skips every character until it meets right, and the answer is true.
Interviewer: Final cost?
Candidate: O(n) time, because each step moves a pointer inward and they meet after at most n moves. O(1) memory: two indexes, and no new strings.
At 200,000 characters, isPalindrome took 2.4 ms. Both versions pass, so the interviewer’s push here was memory, not time.
Interviewer: What if the string can hold any Unicode text?
The Candidate’s answer (stretch)
Candidate: Then my helpers are wrong in two ways. A code point above 0xFFFF takes two UTF-16 code units, so "\u{1F600}ok".length is 4 although it holds three characters. My pointers would have to step over both code units of such a character.
Candidate: And “letter or digit” needs Unicode’s own categories. In JavaScript the regex /[\p{L}\p{N}]/u matches any letter or number, so it accepts é and rejects _.
In one run on Node.js 24.22.1, /[\p{L}\p{N}]/u.test("é") printed true and "É".toLowerCase() printed "é". MDN lists the categories \p{…} accepts.
Interviewer: What if you may delete at most one character?
The Candidate’s answer
Candidate: I run the same pointers. At the first mismatch, I try skipping the left character, then the right one, and check the rest with the same loop. That’s still O(n) time and O(1) memory. LeetCode has it as problem 680, which this course doesn’t cover.
Three mistakes are common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module.
- Removing
\W.\wcounts_as a word character, sos.replace(/\W/g, "")keeps it. For"a_", that version returnsfalseinstead oftrue. Use/[^a-z0-9]/gi, or the code ranges. - Forgetting to lowercase. For
"Aa", that version returnsfalseinstead oftrue. Lowercase both sides before you compare. - Keeping only letters. A version that removes
[^a-z]drops digits too. For"0P"it keeps onlypand returnstrueinstead offalse. Keep digits.
Lab folder: module-02/0125-valid-palindrome/ in the course repository.
167. Two Sum II – Input Array Is Sorted
167. Two Sum II – Input Array Is Sorted is rated Medium. You get a list of integers sorted from smallest to largest, and a target. Exactly two different positions hold numbers that add up to the target. You return those positions counted from 1, smaller first, using only a fixed amount of extra memory.
2 ≤ n ≤ 3 × 10^4-1000 ≤ numbers[i] ≤ 1000and-1000 ≤ target ≤ 1000numbersis sorted in non-decreasing order- exactly one answer exists
- the statement requires constant extra memory
The signature is function twoSum(numbers: number[], target: number): number[]. Try it on LeetCode first.
Hint
Add the smallest and the largest number. If the sum is too small, can the smallest number be in the pair at all?
Interviewer: This one is Two Sum again, but the array is sorted.
Candidate: So I return the two positions whose numbers add up to the target. Are the positions counted from 0 or from 1?
Interviewer: From 1, and the smaller one first.
Candidate: Can values repeat? For example [2, 2, 5] with a target of 4.
Interviewer: Yes. That answer is [1, 2]. You can’t use one position twice.
Candidate: Is there always an answer? And is there a memory limit?
Interviewer: There’s always exactly one answer. And yes, use only constant extra memory.
Candidate: Here are my cases.
numbers target expected
[-3, 1, 4, 6, 9, 12] 15 [4, 5] 6 + 9
[2, 2, 5] 4 [1, 2] equal values at two positions
[-8, -3, 0] -11 [1, 2] a negative target
[0, 1000] 1000 [1, 2] only two numbers
Candidate: The naive solution tries every pair.
// O(n^2) time, O(1) memory: tries every pair, about n^2 / 2 of them.
export function twoSumBrute(numbers: number[], target: number): number[] {
for (let i = 0; i < numbers.length; i++) {
for (let j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] === target) return [i + 1, j + 1];
}
}
return [];
}
Candidate: That’s O(n²) time and O(1) memory. With n up to 3 × 10⁴, it’s about 4.5 × 10⁸ pairs, 4.5 times the budget.
On paper that’s too slow, but at the limit, with the pair at the very end, one call took 460.6 ms. So it may pass. What it does wrong is ignore the order.
Candidate: Module 1’s map would make it O(n) time. But it holds up to n numbers, and you asked for constant memory.
Interviewer: Right. What else can you use?
Candidate: The order. For each number, I know the exact partner I need, target - numbers[i]. In a sorted array I can find it by binary search instead of a scan.
Binary search finds a value in a sorted range by checking the middle and dropping the half that can’t hold it, so it takes O(log n) steps. Module 5 works binary search problems, and DSA Module 9 teaches it. JavaScript arrays have no built-in binary search, so the Candidate writes one.
// O(n log n) time, O(1) memory: for each number, one binary search for its partner to the right.
export function twoSumBinarySearch(numbers: number[], target: number): number[] {
for (let i = 0; i < numbers.length; i++) {
const wanted = target - numbers[i];
let lo = i + 1;
let hi = numbers.length - 1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (numbers[mid] === wanted) return [i + 1, mid + 1];
if (numbers[mid] < wanted) lo = mid + 1;
else hi = mid - 1;
}
}
return [];
}
Candidate: The search starts at i + 1, so a number can’t pair with itself. That’s n searches of O(log n) each, O(n log n) time, and O(1) memory: about 4.5 × 10⁵ steps at the limit.
Interviewer: Can you use the order better than that?
Candidate: I’ll put left on the smallest number and right on the largest, and look at their sum.
Pause and predict. In the Candidate’s example, left is on -3 and right is on 12, and the sum is 9, less than 15. Which pointer should move? And why can’t -3 be in the answer?
Candidate: left moves. 12 is the largest number, so -3 + 12 is the largest sum -3 can make. If even that is too small, -3 pairs with nothing, and I drop it.
Candidate: It’s the same on the other side. If the sum is too large, the number under right is too large even with the smallest number left, so I drop it.
// O(n) time, O(1) memory: each step moves one pointer inward, so at most n - 1 steps.
function twoSum(numbers: number[], target: number): number[] {
let left = 0;
let right = numbers.length - 1;
while (left < right) {
const sum = numbers[left] + numbers[right];
if (sum === target) return [left + 1, right + 1];
if (sum < target) left++;
else right--;
}
return [];
}
export { twoSum };
Interviewer: Show me it works.
Figure 2 traces the Candidate’s example.
numbers [-3] [1] [4] [6] [9] [12] target 15
0 1 2 3 4 5
step left right sum move
1 0 5 -3 + 12 = 9 too small: left++
2 1 5 1 + 12 = 13 too small: left++
3 2 5 4 + 12 = 16 too large: right--
4 2 4 4 + 9 = 13 too small: left++
5 3 4 6 + 9 = 15 found: return [4, 5]
at step 5:
numbers [-3] [1] [4] [6] [9] [12]
^left
^right
Figure 2: each step drops one number that can’t be in the pair, so the pointers reach the answer after at most n – 1 steps.
Candidate: Now [2, 2, 5] with target 4. The first sum is 2 + 5 = 7, too large, so right moves to the second 2. Then 2 + 2 = 4, and I return [1, 2], two different positions.
Interviewer: And the cost?
Candidate: O(n) time: each step moves one pointer inward, so there are at most n – 1 steps. O(1) memory: two indexes.
At the limit, twoSum took 0.3 ms, against 460.6 ms for every pair.
Interviewer: What if the array isn’t sorted?
The Candidate’s answer
Candidate: Then Module 1’s map is the answer, with O(n) time and O(n) memory. Or I sort pairs of value and position, and walk the pointers over them. That’s O(n log n) time and O(n) memory for the pairs.
Interviewer: What if I want every pair of values that adds up to the target?
The Candidate’s answer
Candidate: I keep the same loop and don’t stop at a match. After a match I move both pointers inward, and I skip repeats of a value so each pair is listed once. That loop is the inside of the next problem, 3Sum.
Two mistakes are common here:
- Indexes from 0. A version that returns
[left, right]gives[ 3, 4 ]for the Candidate’s example instead of[ 4, 5 ]. Add 1 to each. - A search that starts at 0. If the binary search covers the whole array, a number can find itself. For
[3, 3]and target 6, that version returns[ 1, 1 ]instead of[ 1, 2 ]. Start the search ati + 1.
Lab folder: module-02/0167-two-sum-ii-input-array-is-sorted/ in the course repository.
15. 3Sum
15. 3Sum is rated Medium. You get a list of integers and list every group of three values, from three different positions, that adds up to zero. Two groups with the same three values count once, whatever positions they came from. The groups, and the values inside each, can be in any order.
3 ≤ n ≤ 3000-10^5 ≤ nums[i] ≤ 10^5
The signature is function threeSum(nums: number[]): number[][]. Try it on LeetCode first.
Hint
Sort the array and fix the first value of the group. What problem is left for the other two?
Interviewer: Find every group of three numbers that adds up to zero.
Candidate: So I return each group of values once, even if it appears at different positions. Can values repeat?
Interviewer: Yes, and [-1, 0, 1] from two different sets of positions is still one answer.
Candidate: Does the order of the groups matter, or the order inside one?
Interviewer: Neither.
Candidate: May I sort the input in place? And what do I return when there’s no group?
Interviewer: You can change the array. With no group, return an empty list.
Candidate: Here are my cases.
nums expected
[-2, 0, 1, 1, 2, -1] [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]
[0, 0, 0, 0, 0] [0, 0, 0] once, not ten times
[1, 2, 3] [] all positive
[-2, -2, -2, 1, 1, 1, 4, 4] [-2, -2, 4], [-2, 1, 1] repeats everywhere
Candidate: The naive solution tries every three positions. When a group sums to zero, I sort its three values and keep it only if I haven’t seen that group before.
The Candidate writes threeSumBrute, the function at the top of this page.
Candidate: That’s about n³/6 groups, so O(n³) time. At 3,000 numbers that’s 4.5 × 10⁹, 45 times the budget, so it’s too slow. Memory is O(k) for the k distinct groups in the set.
Interviewer: Where is the waste?
Candidate: For each pair at i and j, the third value is fixed: it must be -(nums[i] + nums[j]). The inner loop scans the whole rest of the array for one value.
Candidate: Module 1 answers “is this value here?” with a set. If I sort first, equal values sit next to each other, so I can also skip a repeated first value and a repeated last value without a set of groups.
// O(n^2) time, O(n) memory: sort, then for each first value one pass with a set of values seen so far.
export function threeSumHash(nums: number[]): number[][] {
nums.sort((a, b) => a - b);
const result: number[][] = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue; // same first value: same triplets
const seen = new Set<number>();
for (let j = i + 1; j < nums.length; j++) {
const third = -nums[i] - nums[j];
if (seen.has(third)) {
result.push([nums[i], third, nums[j]]);
while (j + 1 < nums.length && nums[j + 1] === nums[j]) j++; // same last value: same triplet
}
seen.add(nums[j]);
}
}
return result;
}
Candidate: For each first value, one pass with a set, so O(n²) time on average. At 3,000 numbers that’s about 4.5 × 10⁶ steps, so it fits. Memory is O(n) for the set.
Interviewer: The array is sorted now. Do you still need the set?
Candidate: No. Once I fix the first value, I need two numbers in the rest of the array that add up to -nums[i]. The rest is sorted, so that’s Two Sum II, with two pointers and no set.
Candidate: Two more details. If the first value is above 0, all three are positive and can’t sum to 0, so I stop. And after a match, I skip copies of the middle value, so the same group isn’t recorded twice.
// O(n^2) time, O(1) extra memory besides the sort and the output: for each first value,
// one two-pointer pass over the rest, and each pass moves its pointers at most n times in total.
function threeSum(nums: number[]): number[][] {
nums.sort((a, b) => a - b);
const result: number[][] = [];
for (let i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) break; // three positive numbers never sum to 0
if (i > 0 && nums[i] === nums[i - 1]) continue; // same first value: same triplets
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
} else {
result.push([nums[i], nums[left], nums[right]]);
left++;
right--;
while (left < right && nums[left] === nums[left - 1]) left++; // skip repeats of the middle value
}
}
}
return result;
}
export { threeSum };
Candidate: Skipping the middle value is enough. With the first and middle values fixed, the third one is fixed too.
Interviewer: Run your example.
Figure 3 traces threeSum on the Candidate’s example, after the sort.
sorted [-2] [-1] [0] [1] [1] [2]
0 1 2 3 4 5
i nums[i] left right sum what happens
0 -2 1 5 -1 too small: left++
2 5 0 record [-2, 0, 2]; left++, right--
3 4 0 record [-2, 1, 1]; left++, right--
4 3 left is not < right: next i
1 -1 2 5 1 too large: right--
2 4 0 record [-1, 0, 1]; left++, right--
3 3 next i
2 0 3 5 3 too large: right--
3 4 2 too large: right--
3 3 next i
3 1 nums[i] > 0: stop
Figure 3: for each first value, the search for the other two is Two Sum II on the rest of the sorted array.
Candidate: For [0, 0, 0, 0, 0], i = 0 records [0, 0, 0]. Then left skips the zeros until it meets right. Every later i has the same first value, 0, so it’s skipped, and the group is listed once.
Interviewer: What does it cost?
Candidate: O(n²) time: n first values, each with a pointer pass of O(n). The sort’s O(n log n) is smaller. Memory is O(1) besides the output and whatever the sort uses.
V8 sorts with TimSort, a merge sort that takes advantage of runs that are already in order. Its temporary buffer never exceeds n/2 elements, so strictly, the memory inside sort is O(n).
Interviewer: Can you do better than O(n²)?
The Candidate’s answer (stretch)
Candidate: Not by much. Grønlund and Pettie (2014) gave an algorithm that beats n² only by a factor that grows more slowly than log n. In an interview, O(n²) is the answer to give.
The paper is “Threesomes, Degenerates, and Love Triangles”. This course doesn’t teach it.
Interviewer: What if you may not change the input?
The Candidate’s answer
Candidate: I sort a copy first. That costs O(n) more memory, and the rest is the same.
Interviewer: What about four numbers that add up to a target?
The Candidate’s answer
Candidate: I fix one more value: two loops for the first two values, then two pointers for the last two. That’s O(n³). For k numbers, each extra fixed value adds a factor of n, so it’s O(n^(k-1)). LeetCode has 4Sum as problem 18, which this course doesn’t cover.
Three mistakes are common here:
- Not skipping a repeated first value. For
[-1, -1, 0, 1], that version returns[ [ -1, 0, 1 ], [ -1, 0, 1 ] ]instead of[ [ -1, 0, 1 ] ]. Skipnums[i]when it equalsnums[i - 1]. - Not skipping a repeated middle value. For
[-2, 0, 0, 2, 2], that version returns[ [ -2, 0, 2 ], [ -2, 0, 2 ] ]instead of[ [ -2, 0, 2 ] ]. After a match, moveleftpast every copy. - Sorting without a comparator.
sort()with no comparator compares numbers as text, so[-4, 1, 3, 10, -6]becomes[ -4, -6, 1, 10, 3 ]. The pointers then return[ [ -4, 1, 3 ] ]instead of[ [ -6, -4, 10 ], [ -4, 1, 3 ] ]. Pass(a, b) => a - b. The Candidate’s example happens to come out right with the text sort, so it can’t catch this bug.
Lab folder: module-02/0015-3sum/ in the course repository.
11. Container With Most Water
11. Container With Most Water is rated Medium. A row of vertical walls stands one unit apart, and a list gives their heights. The water between two walls is the shorter height times the distance between them, and the walls in between don’t matter. You return the most water any two walls can hold.
2 ≤ n ≤ 10^50 ≤ height[i] ≤ 10^4
The signature is function maxArea(height: number[]): number. Try it on LeetCode first.
Hint
Start with the two outer walls, the widest pair. The shorter of the two has met its best partner already. Why?
Interviewer: Pick two walls that hold the most water.
Candidate: The water is the shorter wall’s height times the distance between them. Do the walls between the two I pick matter?
Interviewer: No. Only the two walls and their distance.
Candidate: Is the distance j - i, or j - i + 1?
Interviewer: j - i. Walls at positions 2 and 5 are 3 apart.
Candidate: Can a height be 0? And how large can the answer get?
Interviewer: Heights go from 0 to 10,000.
Candidate: Then the answer is below 10⁴ × 10⁵ = 10⁹, an exact integer in a JavaScript number. Here are my cases.
height expected
[2, 5, 3, 1, 4] 12 the walls at 1 and 4: min(5, 4) × 3
[0, 0] 0 two walls of height 0
[4, 4, 4, 4] 12 equal heights: the outer pair
[1, 2, 3, 4, 5] 6 rising heights
Candidate: The naive solution tries every pair.
// O(n^2) time, O(1) memory: tries every pair of lines, about n^2 / 2 of them.
export function maxAreaBrute(height: number[]): number {
let best = 0;
for (let i = 0; i < height.length; i++) {
for (let j = i + 1; j < height.length; j++) {
best = Math.max(best, Math.min(height[i], height[j]) * (j - i));
}
}
return best;
}
Candidate: That’s O(n²) time and O(1) memory. At 10⁵ walls, about 5 × 10⁹ pairs, 50 times the budget, so it’s too slow.
At the limit, maxAreaBrute took 12,550.2 ms in one call.
Interviewer: Which pairs don’t you need to try?
Pause and predict. In the Candidate’s example, the outer pair is the walls of height 2 and 4, which hold min(2, 4) × 4 = 8. Which of the two walls can you drop for good?
Candidate: The shorter one, the 2. Every other pair that uses it is narrower, and its water is still at most 2 high. So no other pair with the 2 can hold more than 8, and I’ve already counted 8.
Candidate: So I start with the widest pair, record its water, and move the pointer at the shorter wall inward. On a tie, I can move either one.
There’s no useful middle step here, because sorting the heights would lose the positions that set the width.
// O(n) time, O(1) memory: each step drops the shorter line for good, so at most n - 1 steps.
function maxArea(height: number[]): number {
let left = 0;
let right = height.length - 1;
let best = 0;
while (left < right) {
best = Math.max(best, Math.min(height[left], height[right]) * (right - left));
// The shorter line can hold no more water with any closer partner, so drop it.
if (height[left] < height[right]) left++;
else right--;
}
return best;
}
export { maxArea };
Interviewer: Trace it.
Figure 4 shows every step on the Candidate’s example.
height [2] [5] [3] [1] [4]
0 1 2 3 4
left right water best move
0 4 min(2, 4) × 4 = 8 8 2 is shorter: left++
1 4 min(5, 4) × 3 = 12 12 4 is shorter: right--
1 3 min(5, 1) × 2 = 2 12 1 is shorter: right--
1 2 min(5, 3) × 1 = 3 12 3 is shorter: right--
1 1 left is not < right: return 12
Figure 4: each step drops the shorter wall, which has already met its widest partner, so n – 1 steps check every pair that could win.
Candidate: For [4, 4, 4, 4], every step is a tie, so right moves. The first pair gives 4 × 3 = 12, and the narrower pairs give 8 and 4. The answer is 12.
Interviewer: Final cost?
Candidate: O(n) time: each step drops one wall, so n – 1 steps. O(1) memory: two indexes and the best so far.
At the limit, maxArea took 1.2 ms.
Interviewer: On equal heights, can you move both pointers?
The Candidate’s answer
Candidate: Yes. With equal heights, each of the two walls is with its widest partner, and every narrower pair with either one is no taller. So neither can do better, and I can drop both.
Interviewer: How is this different from water trapped between all the walls?
The Candidate’s answer
Candidate: Here I pick one container, and the walls in between don’t count. If every wall counts and the water adds up over all positions, that’s Trapping Rain Water, the next problem.
Three mistakes are common here, each shown on the Candidate’s example, where the answer is 12:
- Moving the taller wall. That version drops the wall that could still do better, and returns
8. Move the shorter one. - Width as
right - left + 1. That version counts the walls, not the gaps between them, and returns16. Useright - left. - The taller wall’s height. With
Math.maxinstead ofMath.min, the water rises above the shorter wall, and the result is16. Water stops at the shorter wall.
Lab folder: module-02/0011-container-with-most-water/ in the course repository.
42. Trapping Rain Water
42. Trapping Rain Water is rated Hard. A list gives the heights of bars, each one unit wide, standing side by side. After rain, the water above a bar rises to the lower of two heights: the tallest bar on its left and the tallest bar on its right. You return the total water held.
1 ≤ n ≤ 2 × 10^40 ≤ height[i] ≤ 10^5
The signature is function trap(height: number[]): number. Try it on LeetCode first.
Hint
The water above one bar depends on the tallest bar on each side. Do you need both numbers, or only the smaller one?
Interviewer: Last one. How much rain stays between these bars?
Candidate: Above each bar, the water rises to the lower of the tallest bar on its left and the tallest bar on its right. Then I add it up. Do the two end bars hold water?
Interviewer: No. Water at the ends runs off the side.
Candidate: Can a height be 0, and can there be one bar?
Interviewer: Yes to both.
Candidate: How large can the total get?
Interviewer: 20,000 bars, each up to 100,000 high.
Candidate: Then it’s below 2 × 10⁹, still an exact integer. Here are my cases.
height expected
[3, 0, 2, 0, 4] 7 3 + 1 + 3 above positions 1, 2 and 3
[5] 0 one bar
[3, 2, 1] 0 the water runs off the right side
[2, 0, 2] 2 one gap
Figure 5 draws the Candidate’s example, with # for a bar and ~ for water.
level 4 #
level 3 # ~ ~ ~ #
level 2 # ~ # ~ #
level 1 # ~ # ~ #
height 3 0 2 0 4
position 0 1 2 3 4
Figure 5: the water above each bar stops at the 3 on the left, the lower of the two tallest bars around it.
Candidate: Every solution uses one rule. The water above bar i is the smaller of the tallest bar at or left of i and the tallest bar at or right of i, minus height[i]. Including the bar itself means the result is never negative.
Candidate: The naive solution scans both sides for every bar.
// O(n^2) time, O(1) memory: for every bar, scans the whole array again for the two tallest bars.
export function trapBrute(height: number[]): number {
let water = 0;
for (let i = 0; i < height.length; i++) {
let leftMax = 0;
for (let j = 0; j <= i; j++) leftMax = Math.max(leftMax, height[j]);
let rightMax = 0;
for (let j = i; j < height.length; j++) rightMax = Math.max(rightMax, height[j]);
water += Math.min(leftMax, rightMax) - height[i];
}
return water;
}
Candidate: That’s n bars times a scan of n, so O(n²) time and O(1) memory. At 2 × 10⁴ bars, about 4 × 10⁸ steps, 4 times the budget.
On paper that’s too slow. But the loop body is two comparisons, and at the limit one call took 194.1 ms, so it may pass.
Interviewer: It may pass. What does it repeat?
Candidate: Each scan finds a maximum the scan before it almost knew. The tallest bar left of i is the tallest bar left of i - 1, or bar i itself.
Candidate: So I keep a running maximum, the largest value seen so far, updated with one Math.max per step. It’s Module 1’s prefix product with a maximum in place of the product. I fill one array from the left, one from the right, then add up the water.
DSA Module 2 builds the same idea with sums, as prefix sums.
// O(n) time, O(n) memory: two passes fill the running maximum from each side, a third adds up the water.
export function trapPrefixMax(height: number[]): number {
const n = height.length;
const leftMax: number[] = new Array(n);
const rightMax: number[] = new Array(n);
leftMax[0] = height[0];
for (let i = 1; i < n; i++) leftMax[i] = Math.max(leftMax[i - 1], height[i]);
rightMax[n - 1] = height[n - 1];
for (let i = n - 2; i >= 0; i--) rightMax[i] = Math.max(rightMax[i + 1], height[i]);
let water = 0;
for (let i = 0; i < n; i++) water += Math.min(leftMax[i], rightMax[i]) - height[i];
return water;
}
Candidate: Three passes, so O(n) time, and O(n) memory for the two arrays.
Interviewer: Can you do it in O(1) memory?
Candidate: Only the smaller of the two maximums matters. So I start a pointer at each end and keep leftMax and rightMax, the tallest bars each pointer has seen.
Candidate: If leftMax is smaller, the bar at left is settled. Its real right maximum is at least rightMax, which is already taller than leftMax. So its water is leftMax - height[left], and I move left. Otherwise I settle the bar at right the same way.
// O(n) time, O(1) memory: each step settles one bar and moves one pointer inward.
function trap(height: number[]): number {
let left = 0;
let right = height.length - 1;
let leftMax = 0;
let rightMax = 0;
let water = 0;
while (left <= right) {
leftMax = Math.max(leftMax, height[left]);
rightMax = Math.max(rightMax, height[right]);
// The lower side's maximum is the limit: the other side already has a taller bar.
if (leftMax < rightMax) {
water += leftMax - height[left];
left++;
} else {
water += rightMax - height[right];
right--;
}
}
return water;
}
export { trap };
Candidate: The loop runs while left <= right, so every bar is settled exactly once, including the last one.
Interviewer: Show me on your example.
Figure 6 traces trap on [3, 0, 2, 0, 4].
height [3] [0] [2] [0] [4]
0 1 2 3 4
left right leftMax rightMax settles water
0 4 3 4 bar 0: 3 - 3 = 0 0
1 4 3 4 bar 1: 3 - 0 = 3 3
2 4 3 4 bar 2: 3 - 2 = 1 4
3 4 3 4 bar 3: 3 - 0 = 3 7
4 4 4 4 bar 4: 4 - 4 = 0 7
left > right: return 7
Figure 6: while leftMax is the smaller maximum, it decides the water on the left, so each step settles the bar under one pointer.
Candidate: For [2, 0, 2], both maximums are 2 from the start, so the else branch settles the right side. Bar 2 adds 0, bar 1 adds 2 – 0 = 2, and bar 0 adds 0. The total is 2.
Interviewer: Final cost?
Candidate: O(n) time, because each step settles one bar. O(1) memory: two pointers and two maximums.
At the limit, trap took 0.5 ms, against 194.1 ms for the naive scan.
Interviewer: Is there another O(n) way?
The Candidate’s answer (stretch)
Candidate: A monotonic stack keeps positions whose heights only go down from bottom to top. When a taller bar arrives, it pops the lower bars and adds the water above them, one layer at a time. That’s O(n) time and O(n) memory.
Module 4 teaches monotonic stacks. This version isn’t in the lab.
Interviewer: What if the heights are a 2D map, and water can run off in four directions?
The Candidate’s answer (stretch)
Candidate: Then two pointers aren’t enough. I’d start from the border and always grow inward from the lowest cell reached so far, using a min-heap. That’s LeetCode 407, which this course doesn’t cover.
Module 1 named the min-heap as a stretch idea, and Module 8 works heap problems.
Two mistakes are common here:
- The tallest bar overall on both sides. That version fills every bar up to the tallest bar in the array. For the Candidate’s example it returns
11instead of7. Use the tallest bar on each side. - Only the left maximum. For
[4, 0, 2], that version returns6instead of2, because the right side is only 2 high. The Candidate’s example can’t catch this bug: its tallest bar is on the right, so the left maximum is always the smaller one, and the version returns the right 7.
Lab folder: module-02/0042-trapping-rain-water/ in the course repository.
Measured: 3Sum, three loops against sort and two pointers
3Sum is the problem this module measures, with bench.ts from DSA Module 1. Both solutions run at 400, 800 and 1,600 numbers. Then threeSum runs alone at LeetCode’s limit of 3,000 and beyond, because three loops at 3,000 would take about a minute per table row (six calls of about 11 seconds).
// Module 2 measurement: 3Sum with three nested loops against sort + two pointers.
// Run from the repository root: node module-02/measure.ts
import { bench } from "../shared/bench.ts";
import { threeSumBrute, threeSum } from "./0015-3sum/solution.ts";
// n random integers in LeetCode's range, -10^5 to 10^5.
function randomNums(n: number): number[] {
return Array.from({ length: n }, () => Math.floor(Math.random() * 200_001) - 100_000);
}
let sink = 0; // the timed functions add to it, so their work cannot be skipped
bench("threeSumBrute (three nested loops)", [400, 800, 1600], randomNums, (nums) => {
sink += threeSumBrute(nums).length;
});
bench("threeSum (sort + two pointers)", [400, 800, 1600], randomNums, (nums) => {
sink += threeSum(nums).length;
});
bench("threeSum at LeetCode's limit and beyond", [3_000, 6_000, 12_000], randomNums, (nums) => {
sink += threeSum(nums).length;
});
console.log(`\nsink ${sink}`);
bench runs each size once to warm up, then five times on fresh inputs, and prints the median and how many times slower each size is than the one before.
Pause and predict. When n doubles, how many times longer should threeSumBrute take? And threeSum?
Here is what node module-02/measure.ts printed:
threeSumBrute (three nested loops)
n median ms x prev
400 27.23
800 216.57 8.0
1,600 1733.90 8.0
threeSum (sort + two pointers)
n median ms x prev
400 0.36
800 0.85 2.4
1,600 3.31 3.9
threeSum at LeetCode's limit and beyond
n median ms x prev
3,000 11.46
6,000 46.75 4.1
12,000 209.11 4.5
sink 6821861
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.
Three loops grew 8.0 times per doubling, which is O(n³): twice the input makes 2³ = 8 times the triples. Sort and two pointers grew 4.1 and 4.5 times per doubling from 3,000 up, which is O(n²), and the sort’s O(n log n) doesn’t show next to it. Its first step, 2.4, is too small to show the trend, since the times are under 1 ms. At 1,600 numbers, the two-pointer version was about 520 times faster.
Part of the 4.5 at 12,000 may be the output itself. With values spread over 200,001 integers, the number of zero-sum groups grows with n, so building the result costs more at each size. We didn’t measure that part separately. sink is the total number of groups returned by every timed call.
Underneath: how V8 stores the arrays and strings the pointers read
Every solution here reads a plain array or a string by index and keeps a few integer variables, so its speed depends on how V8 stores them. V8 gives each array an elements kind, a label for what its elements are and how they’re stored.
An array of small integers built from a literal or with push is PACKED_SMI_ELEMENTS. A Smi is a small integer stored in the slot itself and read without a type check. One non-integer such as 4.5 or -0 moves the array to doubles, and the kind never moves back.
A string is a list of UTF-16 code units, and s.charCodeAt(i) reads one in O(1). But a string built with +=, like cleaned in Valid Palindrome, is often a cons string, a tree of the joined pieces. Its first character read flattens it into one block, in O(length). The two-pointer palindrome builds no string, so it never pays that cost.
DSA Module 2 shows both with V8’s own debugging functions, on Node.js 26. We reran its two scripts on Node.js 24.22.1 and got the same output. In one more run, an array of small integers stayed Smi after a numeric sort.
Cheat sheet
Figure 7 maps each problem in this module to the sign that pointed to its solution.
sign in the problem problem one step drops cost
compare a sequence from both ends 125 a skipped or O(n)
matched character
a pair with a given sum, sorted input 167 the end that's too O(n)
small or too large
groups of three with a given sum 15 fix one value, O(n^2)
then 167 on the rest
two ends and the distance between them 11 the shorter wall O(n)
each position limited by the tallest 42 the side with the O(n)
bar on each side smaller maximum
Figure 7: when one comparison proves that the item at one end can’t be in a better answer, two pointers moving inward replace the nested loop.
- Pattern: start a pointer at each end; each step drops one item for good, so at most n – 1 steps.
- Each move needs a reason: sorted order (167, 15), the shorter wall (11), the smaller maximum (42).
- Repeats in sorted input: skip a value equal to the one before it, with no set.
- Running maximum: the largest value so far, one
Math.maxper step, like a prefix sum. - Final costs: 125, 167, 11 and 42 in O(n) time and O(1) memory; 15 in O(n²) time, O(1) memory besides the sort and the output.
- Next: Module 3 moves both pointers the same way, so the run between them, a sliding window, holds the answer.
Sources
- LeetCode problem pages, checked on 2026-11-20: 125, 167, 15, 11, 42.
- V8 blog: Mathias Bynens, Elements kinds in V8 (2017), and Simon Zünd, Getting things sorted in V8 (2018).
- ECMAScript specification: the String type.
- MDN: Unicode character class escape.
- Allan Grønlund and Seth Pettie, Threesomes, Degenerates, and Love Triangles (2014).
- Node.js documentation: TypeScript, test runner.