LeetCode Collections: Interview Problems from Naive to Optimal / Module 01

Module 1: The Interview Method, on Arrays and Hashing

Work seven array and hashing problems as spoken interviews, from the nested-loop answer to one pass with a Map, a Set or a few counters.

Here is a first answer to 1. Two Sum. It tries every pair of positions in the array.

// O(n^2) time, O(1) memory: tries every pair, about n^2 / 2 of them.
export function twoSumBrute(nums: number[], target: number): number[] {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] === target) return [i, j];
    }
  }
  return [];
}

LeetCode allows up to 10⁴ numbers, and at that size this function took 23.40 ms in one run, so it passes. But the problem’s page asks for something faster than O(n²), which means work that grows more slowly than the square of the input size. At 100,000 numbers, the same loops took 2,479.61 ms, and one pass with a Map took 6.32 ms.

This module teaches you to get from that first answer to the fast one out loud, while someone watches. You’ll work seven array and hashing problems as interviews, each from the slow solution to the fast one.

After this module, you can:

  • work a problem out loud in nine steps, from clarifying questions to follow-up questions
  • read a problem’s limits and turn them into a target cost before you write code
  • spot a search inside a loop and replace it with a Map or a Set, and say what memory that costs
  • count with a plain array when the keys are small integers, and build an answer from both sides of the array when division is not allowed

Run the solutions with Node.js 24

Every solution in this course is TypeScript, and Node.js runs it directly. Node.js removes the type annotations before it runs the file. That step is called type stripping, and it means there is no build step. You can see how it works in DSA Module 1.

The code runs on Node.js 24.22.1, a long-term-support (LTS) release. Every number in this module comes from that version on an Apple M2 laptop with macOS.

The code is in the course repository. It has one folder per module, and one folder per problem inside it, each with solution.ts and solution.test.ts. From the repository’s root, this command runs every test in this module:

node --test "module-01/**/*.test.ts"

Each test file checks every solution, slow and fast, on LeetCode’s examples and on this module’s cases. In each solution.ts, the last function has LeetCode’s name and signature, so you can paste it, with any helper above it, into LeetCode.

The interview method in nine steps

In a coding interview, the interviewer watches how you reach the code as well as the code itself. Table 1 sums up what the interview-prep pages of four companies ask of you.

What the page asks of you Google Meta Amazon Microsoft
Ask clarifying questions yes yes yes yes
Start with a working solution, then improve it – close yes –
Talk through your thinking your reasoning while you code while you code your approach
Test your code and check edge cases – yes yes yes
State the time and memory cost in Big O – yes yes yes

Table 1: what four companies’ interview pages ask for. A dash means we did not find it on the pages listed in the sources, read on 2026-11-20.

Table 1 uses two terms you may not know. Big O describes how the work grows with the input size n: O(n) grows in step with n, and with O(n²), doubling n makes about four times the work. An edge case is an input at the edge of what’s allowed, such as an empty array or the largest value. DSA Module 1 teaches Big O in full.

Amazon’s SDE II page says “Start with a working solution and enhance as you go.” Meta’s interview guide says “Iterate rather than immediately trying to jump to the clever solution.” None of the four pages names a brute force, a solution that tries every possible answer. But a brute force is often the quickest working solution, so this course starts there, and the lab names those functions with Brute.

Every problem in this course follows the same nine steps:

  1. Restate and clarify. Say the problem back in your own words. Ask two to four questions: empty input, duplicates, negative values, sorted or not, what to return when there is no answer.
  2. Examples and edge cases. Write one small example of your own and two or three edge cases, each with the output you expect.
  3. The naive solution. Give the obvious correct solution, its cost in Big O with one line on why, and check that cost against the input limits.
  4. Find the repeated work. Name the work the naive solution does again and again, or the fact it ignores (sorted input, a small alphabet).
  5. Optimize. Remove that work in one step, or two when a middle solution helps. Name the pattern and its cost.
  6. Code. Write the final solution with clear names and no clever tricks.
  7. Test out loud. Trace your own example through the code, line by line, then one edge case.
  8. Final cost. Time and memory, with one line on why each.
  9. Follow-ups. Answer the questions the interviewer asks after a working answer: a bigger input, a stream, less memory.

We found no company page that names steps 2, 4 and 9. So treat them as practice habits, not as rules an interviewer checks.

Read the limits to get the target cost

Every LeetCode problem lists its limits, such as 1 ≤ n ≤ 10^5. They tell you how fast the solution must be before you write any code. DSA Module 1 measured a budget of about 10⁸ simple steps per second in Node.js. Figure 1 gives the largest input each cost can handle within that budget.

largest n for 10^8 steps     the cost you can afford
             26              O(2^n)
            464              O(n^3)
         10,000              O(n^2)
      4,523,071              O(n log n)
    100,000,000              O(n)

Figure 1: read the table from the input limit to the slowest cost that still fits in about a second.

Two Sum allows up to 10⁴ numbers. O(n²) is then about 5 × 10⁷ pair checks, inside the budget, so the nested loops pass. A limit of 10⁵, as in most problems in this module, makes O(n²) about 5 × 10⁹ steps. That’s 50 times the budget, so you need O(n log n) or better.

Why use 10⁸, when the M2 is faster? On the M2, twoSumBrute did 5 × 10⁷ pair checks in 23.40 ms, about 2 × 10⁹ checks per second. But a Map lookup costs more than an addition, and the 10⁸ budget leaves room for that. So the budget is a safe estimate, not a tight one.

Read three more things on the page:

  • The value range. An array indexed by value needs one slot per possible value. Values from -10⁴ to 10⁴ fit in 20,001 slots, but values from -10⁹ to 10⁹ would need two billion.
  • Rules in the statement. Some problems require a cost (“must run in O(n) time”) or forbid a tool (“without using division”). Those rules beat the budget.
  • The follow-up line. Some pages end with a harder question, like Two Sum’s “better than O(n²)”. Expect the interviewer to ask it.

When the limit allows the simple solution, say so. It’s easier to get right under time, and you can offer the faster one next.

Talk while you write code

Meta and Amazon ask you to talk through your thinking while you code. Google and Microsoft ask you to explain your reasoning or your approach. These habits keep the interviewer with you, and the Candidate in this module uses most of them:

  • Before the first line, say the plan in one sentence and the cost you expect.
  • When you create a variable, say what it holds (“indexOf maps a value to the position where I saw it”).
  • Say the rule your loop keeps true (“everything in the map is to the left of i“).
  • When you assume something, say it (“you said there’s always an answer, so I won’t check”).
  • When you stop to think, say what you’re checking.

Testing counts too. Microsoft’s page asks you to test your code before you say you’re done, and Meta’s guide counts it in your favor when you find your own bugs.

The pattern: replace a search inside a loop with a Map or a Set

Four slow solutions in this module share one shape. A loop has a second loop, includes or find inside it, and that inner search reads the array to find one value. So the work is n searches of up to n items each, O(n²).

The fix is a hash table, built once or as you go. A hash table turns each key into a number and uses that number to jump to the key’s slot. So a lookup doesn’t read the other keys. In JavaScript, Map and Set are hash tables.

A lookup or an insert is O(1) in the average case, the expected cost over typical inputs. In the worst case, many keys land in the same slot and lookups slow down. DSA Module 3 builds a hash table and shows when that happens.

Signs that point to this pattern:

  • a pair or partner: “two numbers that add up to the target”
  • “seen before?”, duplicates, “is x in the array?”
  • grouping: “all the words with the same letters”
  • counting: “how many times”, “most frequent”

The cost is memory. A Map or Set holds up to n entries, so it needs O(n) extra memory. DSA Module 1 measured a Set of 1,000,000 integers at 20.0 MB and a Map at 28.0 MB. When memory is tight, or when you need the values in order anyway, sorting can be the better choice.

Rule: If an inner loop asks one question about values you’ve already seen, a Map or Set built as you go answers it in O(1) on average.

1. Two Sum

1. Two Sum is rated Easy. You get an array of integers and a target. Exactly two different positions hold numbers that add up to the target, and you return those two positions, in any order.

  • 2 ≤ n ≤ 10^4, where n is the length of nums
  • -10^9 ≤ nums[i] ≤ 10^9 and -10^9 ≤ target ≤ 10^9
  • exactly one answer exists
  • the page’s follow-up asks for a solution faster than O(n²)

LeetCode’s TypeScript signature is function twoSum(nums: number[], target: number): number[]. Try the problem on LeetCode before you read the interview.

Hint

For each number x, you know the exact value its partner must have. How fast can you check whether you’ve already seen that value?

Interviewer: Read the first problem, and tell me how you understand it.

Candidate: I get an array of integers and a target, and I return the positions of two numbers that add up to the target. Is there always exactly one such pair?

Interviewer: Yes, exactly one.

Candidate: Can I use the same position twice? For example, a target of 8 and a single 4.

Interviewer: No, two different positions. But two positions can hold the same value.

Candidate: Can the numbers be negative or zero? And is the array sorted?

Interviewer: Negative numbers and zero can both appear. The array isn’t sorted, and any order of the two positions is fine.

The interviewer and the candidate are invented. The problems, limits and timings are real.

Candidate: Here’s my example, and three edge cases with the answers I expect.

nums                        target   expected
[8, -2, 5, 11]                   3   [1, 2]    -2 + 5
[4, 1, 4]                        8   [0, 2]    equal values at two positions
[5, 0, -7, 0]                    0   [1, 3]    zeros, and a target of 0
[-1000000000, 1000000000]        0   [0, 1]    only two numbers, at the limits

Candidate: The obvious solution tries every pair, with two nested loops. That’s the twoSumBrute function at the top of this page.

Candidate: That’s n(n – 1)/2 pairs, so O(n²) time and O(1) memory. With n up to 10⁴, it’s about 5 × 10⁷ pair checks, inside the budget. So it passes the limits.

Interviewer: Can you do better than O(n²)? Where does this code waste time?

Candidate: For each number x, the inner loop answers one question: is target - x somewhere else in the array? It answers it by reading the array again, once for every x.

Candidate: So I’ll keep a map from each value I’ve seen to its position. I walk the array once, and for each x I look up target - x before I store x. Each lookup is O(1) on average, so the whole pass is O(n).

// O(n) time, O(n) memory: one pass; a map from value to index answers "have I seen target - x?" in O(1).
function twoSum(nums: number[], target: number): number[] {
  const indexOf = new Map<number, number>();
  for (let i = 0; i < nums.length; i++) {
    const partner = indexOf.get(target - nums[i]);
    if (partner !== undefined) return [partner, i];
    indexOf.set(nums[i], i);
  }
  return [];
}

Candidate: indexOf holds only numbers to the left of i. So when I reach the second number of the pair, the first one is already in the map.

Interviewer: Walk me through your example.

Figure 2 shows each step of the Candidate’s trace, with the map after the step.

nums  [8] [-2] [5] [11]      target 3
       0    1   2    3

i   nums[i]   target - nums[i]   found in indexOf?   indexOf after the step
0      8            -5           no                  {8 => 0}
1     -2             5           no                  {8 => 0, -2 => 1}
2      5            -2           yes, at 1           return [1, 2]

Figure 2: when i reaches 5, its partner -2 is already in the map, so one pass finds the pair.

Candidate: Now [4, 1, 4] with target 8. At i = 0 the map is empty, so I don’t find 4, and I store 4 at position 0. At i = 2 I look up 4, find position 0, and return [0, 2].

Candidate: That case is why I look up before I store. If I stored first, the 4 at position 0 would find itself.

Interviewer: What’s the final cost?

Candidate: O(n) time: one pass, with one lookup and one insert per number, each O(1) on average. O(n) memory, because the map can hold every number except the last.

Interviewer: What if the array were sorted?

The Candidate’s answer

Candidate: Then I don’t need the map. I start one index at each end. If the sum is too small, the left index moves right, and if it’s too large, the right index moves left.

Candidate: That’s O(n) time and O(1) memory. Module 2 works this problem as 167. Two Sum II.

Interviewer: What if I want every pair that adds up to the target?

The Candidate’s answer

Candidate: If you only want how many pairs there are, the map keeps a count per value. Each x adds the count of target - x seen so far, and it’s still O(n). If you want the pairs themselves, the output alone can be O(n²): in [2, 2, 2, 2] with target 4, every one of the six pairs counts.

One mistake is common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module.

  • Storing before the lookup. With indexOf.set above indexOf.get, a number can find itself. For [5, 2, 8] and target 10, that version returns [ 0, 0 ] (5 + 5) instead of [ 1, 2 ]. Look up first, then store.

Lab folder: module-01/0001-two-sum/ in the course repository.

217. Contains Duplicate

217. Contains Duplicate is rated Easy. You get an array of integers. You return true if any value appears at least twice, or false if every value is different.

  • 1 ≤ n ≤ 10^5
  • -10^9 ≤ nums[i] ≤ 10^9

The signature is function containsDuplicate(nums: number[]): boolean. Try it on LeetCode first.

Hint

For each value, you need one fact: have you seen it before? Which structure answers that without a scan?

Interviewer: Next problem. Does any value in the array repeat?

Candidate: So I return true as soon as one value appears a second time. Can the array be empty?

Interviewer: No, it has at least one number. The values go from minus a billion to a billion.

Candidate: Then I can’t use an array indexed by value, because it would need two billion slots. Am I allowed to change the input, for example sort it in place?

Interviewer: I’d rather you didn’t.

Candidate: Here are my cases.

nums                        expected
[40, 7, -3, 12, 7]          true     7 appears twice
[5]                         false    one number
[-1000000000, 1000000000]   false    the two limits

Candidate: The naive solution compares every pair.

// O(n^2) time, O(1) memory: compares every pair, about n^2 / 2 of them.
export function containsDuplicateBrute(nums: number[]): boolean {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] === nums[j]) return true;
    }
  }
  return false;
}

Candidate: That’s O(n²) time and O(1) memory. At 10⁵ numbers it’s about 5 × 10⁹ comparisons, 50 times the budget, so it’s too slow.

Interviewer: What does it repeat?

Candidate: It compares each value with every later value. But I only need one fact per value: have I seen it before?

Candidate: Sorting a copy would put equal values next to each other, in O(n log n) time. But a set of the values I’ve seen does it in one pass. For each value, if it’s already in the set, I return true. Otherwise I add it.

// O(n) time, O(n) memory: one pass; a set answers "seen before?" in O(1) on average.
function containsDuplicate(nums: number[]): boolean {
  const seen = new Set<number>();
  for (const value of nums) {
    if (seen.has(value)) return true;
    seen.add(value);
  }
  return false;
}

Interviewer: Test it.

Figure 3 shows the set after each value of the Candidate’s example.

nums  [40] [7] [-3] [12] [7]
        0   1    2    3   4

value   in seen?   seen after the step
  40    no         {40}
   7    no         {40, 7}
  -3    no         {40, 7, -3}
  12    no         {40, 7, -3, 12}
   7    yes        return true

Figure 3: the second 7 finds the first one with one set lookup, without a scan.

Candidate: For [5], the loop adds 5 and ends, so it returns false.

Interviewer: And the cost?

Candidate: O(n) time on average: one lookup and one insert per value. O(n) memory in the worst case, when every value is different and the set holds all of them.

Interviewer: When would you sort instead?

Candidate: When memory is tight and I’m allowed to sort the input in place, or when the data comes sorted already. Then equal values sit next to each other, and I don’t need the set.

Interviewer: What if you must use O(1) extra memory?

The Candidate’s answer

Candidate: If I may change the input, I sort it in place and compare neighbors. That’s O(n log n) time with no set, and the only extra memory is what the sort itself uses.

Interviewer: What if the values are between 0 and 1,000?

The Candidate’s answer

Candidate: Then an array of 1,001 booleans, indexed by value, replaces the set. It’s still O(n) time, with a fixed 1,001 slots of memory.

One mistake is common here:

  • Sorting the caller’s array. A version that calls nums.sort changes the array it was given. After it runs, the caller’s [40, 7, -3, 12, 7] is [ -3, 7, 7, 12, 40 ]. Sort a copy, or ask first.

Lab folder: module-01/0217-contains-duplicate/ in the course repository. It also holds the sorted version, containsDuplicateSort.

242. Valid Anagram

242. Valid Anagram is rated Easy. You get two strings, s and t. You return true if t uses exactly the same letters as s, each the same number of times, in any order.

  • 1 ≤ s.length, t.length ≤ 5 × 10^4
  • both strings hold only lowercase English letters
  • the page’s follow-up asks what changes if the strings can hold any Unicode characters

The signature is function isAnagram(s: string, t: string): boolean. Try it on LeetCode first.

Hint

You don’t need the letters in order. What do you need to know about each letter?

Interviewer: Two strings. Is the second one an anagram of the first?

Candidate: So t must use the same letters as s, each the same number of times. Which characters can appear?

Interviewer: Lowercase a to z only.

Candidate: Can the two lengths differ?

Interviewer: Yes. Each one is between 1 and 50,000.

Candidate: Then different lengths mean false right away. Here are my cases.

s          t          expected
"listen"   "silent"   true
"a"        "a"        true     the shortest strings
"ab"       "abb"      false    the lengths differ
"aab"      "abb"      false    the same letters, different counts

Candidate: First solution: sort the letters of both strings and compare. Two strings are anagrams exactly when their sorted letters are equal.

// O(n log n) time, O(n) memory: two strings are anagrams exactly when their sorted letters match.
export function isAnagramSort(s: string, t: string): boolean {
  if (s.length !== t.length) return false;
  return [...s].sort().join("") === [...t].sort().join("");
}

Candidate: That’s O(n log n) time for the sorts and O(n) memory for the arrays. With n = 5 × 10⁴, n log n is about 8 × 10⁵ steps, so it fits.

Interviewer: It fits. Can you do it in linear time?

Candidate: Sorting puts every letter in order, and the question doesn’t need the order. It only needs how many times each letter appears.

Candidate: With 26 letters, I can keep 26 counters in an array. I add one for each letter of s and subtract one for each letter of t. At the end, every counter must be zero.

// O(n) time, O(1) memory: lowercase English letters only, so 26 counters replace the map.
function isAnagram(s: string, t: string): boolean {
  if (s.length !== t.length) return false;
  const counts = new Array<number>(26).fill(0);
  for (let i = 0; i < s.length; i++) {
    counts[s.charCodeAt(i) - 97]++;
    counts[t.charCodeAt(i) - 97]--;
  }
  return counts.every((c) => c === 0);
}

Candidate: charCodeAt(i) - 97 turns a into 0 and z into 25, because 97 is the code of a.

Interviewer: Run it on your first example.

Figure 4 shows the counters that are not zero after each step, for "listen" and "silent".

i   s[i]   t[i]   counters that are not zero after the step
0    l      s     l: 1, s: -1
1    i      i     l: 1, s: -1
2    s      l     (none)
3    t      e     t: 1, e: -1
4    e      n     t: 1, n: -1
5    n      t     (none)

every counter is 0, so the answer is true

Figure 4: a letter’s +1 from s and its -1 from t can come at different steps; only the counts at the end matter.

Candidate: For "aab" and "abb", the lengths match, but after the loop a is 1 and b is -1. So it returns false.

Interviewer: Final cost?

Candidate: O(n) time: one pass over both strings, then one check of 26 counters. O(1) memory: 26 counters, however long the strings are.

Interviewer: What if the strings can hold any Unicode characters?

The Candidate’s answer

Candidate: Then 26 counters aren’t enough. I’d count in a Map keyed by character, and walk the strings with for...of, so each step reads one whole character. That’s still O(n) time, with memory for each distinct character.

“Going deeper” at the end of this module shows that version and why s[i] can split a character in two.

Interviewer: What if the strings arrive as streams, too long to keep?

The Candidate’s answer

Candidate: I keep only the counters and update them as characters arrive: plus one from s, minus one from t. Memory stays the same however long the streams are, one counter per distinct character.

One mistake is common here:

  • Checking letters, not counts. A version that checks only that every letter of t appears in s returns true for "aab" and "abb". The answer is false. Count each letter.

Lab folder: module-01/0242-valid-anagram/ in the course repository.

49. Group Anagrams

49. Group Anagrams is rated Medium. You get a list of lowercase words. You put words that are anagrams of each other into the same group, and return the groups in any order.

  • 1 ≤ n ≤ 10^4 words
  • each word has 0 to 100 letters (k below)
  • only lowercase English letters

The signature is function groupAnagrams(strs: string[]): string[][]. Try it on LeetCode first.

Hint

Find a key that is the same for every anagram of a word, and different for every other word.

Interviewer: This one builds on the last. Group the anagrams in a list of words.

Candidate: So each group holds words with the same letter counts, and every word goes into exactly one group. Can a word be empty?

Interviewer: Yes, a word has 0 to 100 letters.

Candidate: Can the same word appear twice?

Interviewer: It can. Keep both copies. Any order is fine, for the groups and inside them.

Candidate: Here are my cases. The last one has one a and eleven bs against eleven as and one b.

strs                                         expected groups
["stop", "pots", "dusty", "tops", "study", "opts", "a"]
              ["stop", "pots", "tops", "opts"] ["dusty", "study"] ["a"]
["", "", "b"]                                ["", ""] ["b"]
["ab", "ab", "ba"]                           ["ab", "ab", "ba"]
["abbbbbbbbbbb", "aaaaaaaaaaab"]             two groups of one

Candidate: The naive solution compares each word with the first word of every group so far. If one matches, the word joins that group. Otherwise it starts a new one.

The check is sameLetters, a helper in the lab file with the same 26 counters as isAnagram. This excerpt shows only the loop:

// O(n^2 * k) time in the worst case, O(n * k) memory: each string is checked against
// the first string of every group so far; with no anagrams there are n groups.
export function groupAnagramsBrute(strs: string[]): string[][] {
  const groups: string[][] = [];
  for (const word of strs) {
    const group = groups.find((g) => sameLetters(g[0], word));
    if (group) group.push(word);
    else groups.push([word]);
  }
  return groups;
}

Candidate: In the worst case, no two words are anagrams, so there are n groups. Each word is checked against every group before it, about n²/2 checks of k letters, so O(n² · k). At 10⁴ words of 100 letters, that’s 5 × 10⁹ steps, too slow.

Interviewer: What’s repeated?

Candidate: groups.find compares the word with every group again. If I had a key that’s equal for all anagrams of a word, “which group?” would be one map lookup.

Candidate: The simplest key is the word’s letters, sorted. “stop”, “pots” and “tops” all become “opst”.

// O(n * k log k) time, O(n * k) memory: anagrams share one key, their sorted letters.
export function groupAnagramsSortKey(strs: string[]): string[][] {
  const groups = new Map<string, string[]>();
  for (const word of strs) {
    const key = [...word].sort().join("");
    const group = groups.get(key);
    if (group) group.push(word);
    else groups.set(key, [word]);
  }
  return [...groups.values()];
}

Candidate: Sorting each key costs O(k log k), so this is O(n · k log k) time. That’s about 7 × 10⁶ steps at the limits, so it fits.

Interviewer: Can you build the key without sorting?

Candidate: Yes, from the 26 letter counts, joined with commas. That takes one pass over the word.

// O(n * (k + 26)) time, O(n * k) memory: the key is the 26 letter counts, built in one pass per word.
function groupAnagrams(strs: string[]): string[][] {
  const groups = new Map<string, string[]>();
  for (const word of strs) {
    const counts = new Array<number>(26).fill(0);
    for (let i = 0; i < word.length; i++) counts[word.charCodeAt(i) - 97]++;
    const key = counts.join(","); // the commas keep [1, 11] and [11, 1] apart
    const group = groups.get(key);
    if (group) group.push(word);
    else groups.set(key, [word]);
  }
  return [...groups.values()];
}

Interviewer: Trace your first example.

Each real key is 26 numbers joined with commas. So Figure 5 writes a key as the letters it counts; in this example, every counted letter appears once.

word    key, as the letters it counts    group
stop    o p s t                          new group 1
pots    o p s t                          group 1
dusty   d s t u y                        new group 2
tops    o p s t                          group 1
study   d s t u y                        group 2
opts    o p s t                          group 1
a       a                                new group 3

[...groups.values()]  [[stop, pots, tops, opts], [dusty, study], [a]]

Figure 5: anagrams get equal keys, so each word costs one map lookup, however many groups exist.

Candidate: A Map returns its values in the order their keys were first added, so the groups come out in order of their first word. For the last edge case, the keys start with 1,11, and 11,1,, so the two words land in different groups.

Interviewer: And the cost?

Candidate: O(n · (k + 26)) time: k steps to count each word, and 26 numbers to join into its key. O(n · k) memory, because the groups hold every word, plus one key per group.

Interviewer: Which key would you pick if words were very long?

The Candidate’s answer

Candidate: The count key. It costs O(k) per word, against O(k log k) for sorting. With words of at most 100 letters, the difference is only a factor of about log k, so either key is fine here.

Interviewer: What if I only want the size of each group?

The Candidate’s answer

Candidate: Then the map stores a count per key instead of a list of words. Memory drops to one key and one number per group.

Two mistakes are common here:

  • Count keys with no separator. Joining the counts with "" turns both [1, 11, 0, …] and [11, 1, 0, …] into "111000…". For ["abbbbbbbbbbb", "aaaaaaaaaaab"] that version returns [ [ 'abbbbbbbbbbb', 'aaaaaaaaaaab' ] ], one group where there should be two. Join with a separator.
  • An array as the Map key. One version uses the sorted letter array itself as the key. For ["stop", "pots", "tops"] it returns [ [ 'stop' ], [ 'pots' ], [ 'tops' ] ]. A Map matches an array key only to that same array, and each sort makes a new one. Join the array into a string.

Lab folder: module-01/0049-group-anagrams/ in the course repository.

347. Top K Frequent Elements

347. Top K Frequent Elements is rated Medium. You get an array of integers and a number k. You return the k values that appear most often, in any order, and the input always has exactly one right answer.

  • 1 ≤ n ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • k is between 1 and the number of distinct values
  • the page’s follow-up asks for a time better than O(n log n)

The signature is function topKFrequent(nums: number[], k: number): number[]. Try it on LeetCode first.

Hint

A value’s count is a whole number between 1 and n. What can you do with numbers that small?

Interviewer: Return the k values that appear most often.

Candidate: So I count each value and return the k values with the highest counts. What if two values tie at the cut-off, say k = 1 and two values each appear three times?

Interviewer: The input guarantees a unique answer, so that can’t happen.

Candidate: Can k be larger than the number of distinct values?

Interviewer: No, it’s at most that number. And any order is fine for the output.

Candidate: Here are my cases.

nums                           k   expected
[7, 3, 7, -2, 3, 7, 5, 3, 7]   2   [7, 3]       7 four times, 3 three times
[4, 4, 9, 9, 6]                2   [4, 9]       a tie inside the top k
[8, -1, 0]                     3   [8, -1, 0]   every value
[5, 5, 5]                      1   [5]          one value, seen n times

Candidate: First, I count each value with a map, in O(n). Then I sort the distinct values by count, highest first, and take the first k.

function countEach(nums: number[]): Map<number, number> {
  const counts = new Map<number, number>();
  for (const value of nums) counts.set(value, (counts.get(value) ?? 0) + 1);
  return counts;
}

// O(n + u log u) time, O(u) memory: sorts the distinct values by count, takes the first k.
export function topKFrequentSort(nums: number[], k: number): number[] {
  const counts = countEach(nums);
  return [...counts.keys()].sort((a, b) => counts.get(b)! - counts.get(a)!).slice(0, k);
}

Candidate: With u distinct values, that’s O(n + u log u) time and O(u) memory. u is at most 10⁵, so it fits, but it’s the O(n log n) the follow-up asks me to beat.

Interviewer: Where’s the extra work?

Candidate: The sort puts all u values in order, and I need only the top k. Also, the counts are small whole numbers, between 1 and n.

Candidate: So I can use a count as an array index. I make n + 1 buckets, put each value in the bucket for its count, then read the buckets from n down until I have k values.

Bucket sort is a sort that first spreads the items into several buckets, as described in NIST’s dictionary of algorithms. Here a bucket’s index is a count. So reading the buckets in order reads the values by count.

// O(n) time, O(n) memory: a count is between 1 and n, so bucket i holds the values seen i times;
// read the buckets from n down until k values are taken.
function topKFrequent(nums: number[], k: number): number[] {
  const counts = countEach(nums);
  const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => []);
  for (const [value, count] of counts) buckets[count].push(value);
  const result: number[] = [];
  for (let count = nums.length; count >= 1 && result.length < k; count--) {
    for (const value of buckets[count]) {
      result.push(value);
      if (result.length === k) break;
    }
  }
  return result;
}

Interviewer: Walk me through your first example.

Figure 6 shows the buckets for the Candidate’s example, with n = 9.

counts  {7 => 4, 3 => 3, -2 => 1, 5 => 1}         n = 9, k = 2

buckets  []  [-2, 5]  []  [3]  [7]  []  []  []  []  []
          0     1      2   3    4    5   6   7   8   9

read from 9 down: 9 to 5 are empty, 4 gives 7, 3 gives 3
result  [7, 3]

Figure 6: no count is above n, so buckets n down to 1 hold every value, already in order of count.

Candidate: For [5, 5, 5] with k = 1, the count of 5 is 3, which is n. That’s why I need n + 1 buckets, because bucket 3 must exist. Reading from 3 down gives [5].

Interviewer: Final cost?

Candidate: O(n) time: counting is n steps, filling the buckets u steps, and reading them at most n + 1 buckets and k values. O(n) memory for the n + 1 buckets and the map.

Interviewer: What if the values arrive as a stream, and I can ask for the top k at any time?

The Candidate’s answer

Candidate: I keep the count of every value seen so far, because a value outside the top k now can join it later. Each time you ask, I build the buckets from the counts again.

Interviewer: What if ties at the cut-off were allowed?

The Candidate’s answer

Candidate: I’d ask how to break them: smaller value first, or the value seen first. Then I sort only the values in the bucket where the cut-off falls.

One mistake is common here:

  • n buckets instead of n + 1. With length: nums.length, a value seen n times has no bucket. For [5, 5, 5] and k = 1, that version throws TypeError: Cannot read properties of undefined (reading 'push'), where the answer is [ 5 ]. Make nums.length + 1 buckets, so indexes 0 to n exist.

Lab folder: module-01/0347-top-k-frequent-elements/ in the course repository. It also holds a heap version, which “Going deeper” describes.

238. Product of Array Except Self

238. Product of Array Except Self is rated Medium. You get an array of integers. You return a new array whose position i holds the product of every number except nums[i]. You must not use division, and the solution must run in O(n) time.

  • 2 ≤ n ≤ 10^5
  • -30 ≤ nums[i] ≤ 30
  • the product of any prefix or suffix of nums fits in a 32-bit integer
  • the page’s follow-up asks for O(1) extra memory, where the output array does not count

The signature is function productExceptSelf(nums: number[]): number[]. Try it on LeetCode first.

Hint

Split “every number except position i” into two parts that you can each keep as a running product while you walk the array.

Interviewer: For each position, the product of all the other numbers. No division.

Candidate: So answer[i] is the product of every number except nums[i]. Can there be zeros?

Interviewer: Yes, values go from -30 to 30.

Candidate: And no division at all, even when there are no zeros?

Interviewer: None.

Candidate: Can the products overflow?

Interviewer: Every prefix and suffix product fits in a 32-bit integer.

Candidate: Then a JavaScript number holds them exactly, since it’s exact for every integer up to 2⁵³ – 1. Here are my cases.

nums             expected
[2, 5, -1, 3]    [-15, -6, 30, -10]
[7, -4]          [-4, 7]              the shortest input
[4, 0, 5]        [0, 20, 0]           one zero
[3, 0, 2, 0]     [0, 0, 0, 0]         two zeros

Candidate: The naive solution multiplies all the other numbers for each position.

// O(n^2) time, O(1) extra memory: for each index, multiplies every other number again.
export function productExceptSelfBrute(nums: number[]): number[] {
  const answer: number[] = [];
  for (let i = 0; i < nums.length; i++) {
    let product = 1;
    for (let j = 0; j < nums.length; j++) {
      if (j !== i) product *= nums[j];
    }
    answer.push(product);
  }
  return answer;
}

Candidate: That’s O(n²) time, 10¹⁰ multiplications at 10⁵ numbers, so it’s too slow, and the statement asks for O(n) anyway. Extra memory is O(1).

Interviewer: What does it repeat?

Candidate: For position 2 it multiplies 2 and 5, and for position 3 it multiplies 2 and 5 again. Every answer is “everything left of i” times “everything right of i”, and each of those changes by one number per step.

Candidate: So I compute both once. before[i] is the product of everything left of i, and after[i] of everything right of i.

A prefix product is the running product of all items before an index. It works like a running sum, with * in place of +, and you can see the sum version as prefix sums in DSA Module 2.

// O(n) time, O(n) extra memory: before[i] is the product of everything left of i,
// after[i] of everything right of i; the answer is before[i] * after[i].
export function productExceptSelfPrefix(nums: number[]): number[] {
  const n = nums.length;
  const before = new Array<number>(n).fill(1);
  const after = new Array<number>(n).fill(1);
  for (let i = 1; i < n; i++) before[i] = before[i - 1] * nums[i - 1];
  for (let i = n - 2; i >= 0; i--) after[i] = after[i + 1] * nums[i + 1];
  return nums.map((_, i) => before[i] * after[i]);
}

Candidate: Three passes, so O(n) time, and O(n) extra memory for before and after.

Interviewer: Can you do it with O(1) extra memory, not counting the output?

Candidate: Then the output array holds the left products. I walk back from the right with one number, right, the product of everything to the right of i.

// O(n) time, O(1) extra memory (the output does not count, as the page says): the answer array
// holds the left products, and one running number holds the right product.
function productExceptSelf(nums: number[]): number[] {
  const n = nums.length;
  const answer = new Array<number>(n).fill(1);
  for (let i = 1; i < n; i++) answer[i] = answer[i - 1] * nums[i - 1];
  let right = 1;
  for (let i = n - 1; i >= 0; i--) {
    answer[i] *= right;
    right *= nums[i];
  }
  return answer;
}

Interviewer: Trace it.

Figure 7 shows both passes on the Candidate’s example.

nums     [2] [5] [-1] [3]
          0   1    2   3

pass 1, left to right: answer[i] = answer[i - 1] * nums[i - 1]
answer   [1] [2] [10] [-10]

pass 2, right to left: answer[i] *= right, then right *= nums[i]
i = 3    answer[3] = -10 *   1 = -10     right =   3
i = 2    answer[2] =  10 *   3 =  30     right =  -3
i = 1    answer[1] =   2 *  -3 =  -6     right = -15
i = 0    answer[0] =   1 * -15 = -15     right = -30

answer   [-15] [-6] [30] [-10]

Figure 7: when pass 2 reaches i, answer[i] holds everything left of i and right everything right of it.

Candidate: For [4, 0, 5], pass 1 gives [1, 4, 0]. Pass 2 sets position 2 to 0 · 1 = 0, position 1 to 4 · 5 = 20, and position 0 to 1 · 0 = 0. That’s [0, 20, 0].

Interviewer: Final cost?

Candidate: O(n) time, two passes. O(1) extra memory: one number, right, besides the output.

Interviewer: Suppose division were allowed. How would you handle zeros?

The Candidate’s answer

Candidate: I’d count the zeros first. With none, each answer is the total product divided by nums[i], and with two or more, every answer is 0. With one zero, only the zero’s position gets the product of the other numbers, and every other position is 0.

Interviewer: What if the products could be larger than 2⁵³?

The Candidate’s answer

Candidate: In JavaScript I’d use BigInt, an integer type with no size limit, at a cost in speed. In a language with fixed-size integers, the statement’s promise that every prefix and suffix fits is what makes the code safe.

Pause and predict. mistakes.ts has a version that ignores the rule and divides the total by each number:

// 238: divides the total product by each number (the page forbids division; this is why).
function productExceptSelfDivide(nums: number[]): number[] {
  const total = nums.reduce((a, b) => a * b, 1);
  return nums.map((x) => total / x);
}

What does it return for [4, 0, 5]?

It returns [ 0, NaN, 0 ]. The total is 0, so every position divides 0 by something. At the zero’s own position that’s 0 / 0, which is NaN in JavaScript. So the version loses 20, the one answer that isn’t 0.

One mistake is common here:

  • Dividing the total. Apart from breaking the rule, it fails on zeros. It returns [ 0, NaN, 0 ] for [4, 0, 5], and [ 0, NaN, 0, NaN ] for [3, 0, 2, 0]. The answers are [ 0, 20, 0 ] and [ 0, 0, 0, 0 ]. Use the two passes.

Lab folder: module-01/0238-product-of-array-except-self/ in the course repository.

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence is rated Medium. You get an unsorted array of integers. You return the length of the longest run of consecutive values, like 3, 4, 5, that all appear in the array, in any positions. A repeated value counts once.

  • 0 ≤ n ≤ 10^5, so the array can be empty
  • -10^9 ≤ nums[i] ≤ 10^9
  • the statement requires O(n) time

The signature is function longestConsecutive(nums: number[]): number. Try it on LeetCode first.

Hint

Which values of a run are worth starting a count from?

Interviewer: Last problem: the longest run of consecutive values.

Candidate: So I look for the longest set of values like 3, 4, 5 that are all in the array, wherever they are, and return its length. Can the array be empty?

Interviewer: Yes. Return 0 then.

Candidate: If a value repeats, does it count twice?

Interviewer: No. [7, 7, 7] has a longest run of 1. And the statement asks for O(n) time.

Candidate: Here are my cases.

nums                        expected
[10, 5, 12, 3, 11, 4, 20]   3     both 3, 4, 5 and 10, 11, 12
[]                          0     empty
[7, 7, 7]                   1     a repeat counts once
[-2, -1, 0, 1]              4     a run that crosses zero

Candidate: The naive solution counts up from every value, and checks each next value with includes.

// O(n^3) time in the worst case, O(1) memory: from each number, counts upward while the
// next value is in the array, and each "is it in the array?" is a full scan.
export function longestConsecutiveBrute(nums: number[]): number {
  let best = 0;
  for (const start of nums) {
    let length = 1;
    while (nums.includes(start + length)) length++;
    best = Math.max(best, length);
  }
  return best;
}

Candidate: In the worst case the whole array is one run. Then each of n starts counts up to n values, and each includes scans up to n items: O(n³). At 10⁵ numbers that’s 10¹⁵ steps, far too slow.

Interviewer: Where’s the waste?

Candidate: In two places. Each “is the next value here?” scans the whole array. And a run of length L gets counted again from each of its L values.

Candidate: Sorting a copy would put each run together, but that’s O(n log n), and the statement asks for O(n). So I fix each waste on its own.

Candidate: First, I put the values in a set, so each check is O(1) on average. Second, I start counting only from a value x when x – 1 isn’t in the set, because that’s where a run begins.

// O(n) time, O(n) memory: a set answers "is x here?" in O(1), and counting starts only at
// values with no x - 1, so each value is visited at most twice in total.
function longestConsecutive(nums: number[]): number {
  const values = new Set(nums);
  let best = 0;
  for (const start of values) {
    if (values.has(start - 1)) continue; // not the start of a run
    let length = 1;
    while (values.has(start + length)) length++;
    best = Math.max(best, length);
  }
  return best;
}

Interviewer: Walk me through it.

Figure 8 follows the loop over the set. A Set returns its values in the order they were first added, so the loop sees them in input order.

values  {10, 5, 12, 3, 11, 4, 20}

start   start - 1 in values?   count up from start      length   best
  10    9: no                  11 yes, 12 yes, 13 no       3        3
   5    4: yes, skip                                               3
  12    11: yes, skip                                              3
   3    2: no                  4 yes, 5 yes, 6 no          3        3
  11    10: yes, skip                                              3
   4    3: yes, skip                                               3
  20    19: no                 21 no                       1        3

Figure 8: only 10, 3 and 20 start a count, so each value is read once more inside a run, not once per member.

Candidate: For [], the set is empty, the loop never runs, and best stays 0. For [7, 7, 7], the set is {7}, neither 6 nor 8 is in it, and the answer is 1.

Interviewer: Why do you need the start check, if the answer is right without it?

Pause and predict. Delete the line if (values.has(start - 1)) continue;. The answer stays right. On one run of 20,000 consecutive values, how does the time change, and why?

Candidate: Without the check, a run of n values gets counted from every member: n steps from the first, n – 1 from the second, and so on. That’s about n²/2 set lookups, so O(n²).

mistakes.ts times both versions on one run of 20,000 values. In one run, the version without the check took 2,597.4 ms, and the version with it took 2.0 ms. Both returned 20000.

Interviewer: So what’s the final cost?

Candidate: O(n) time: building the set is n inserts. The outer loop does one lookup per distinct value, and the inner loop visits each value at most once over the whole run. O(n) memory for the set.

Interviewer: What if I want the run itself, not its length?

The Candidate’s answer

Candidate: I keep the start of the best run next to its length. At the end I return the values from start to start + length - 1.

Interviewer: What if you can’t use O(n) extra memory?

The Candidate’s answer

Candidate: If I may change the input, I sort it in place, then walk it once, skipping repeats and starting over at each gap. That’s O(n log n) time with no set, so it gives up the statement’s O(n) rule to save memory.

One more mistake is common here, besides a missing start check:

  • best starting at 1. For an empty array, that version returns 1 instead of 0. Start best at 0.

Lab folder: module-01/0128-longest-consecutive-sequence/ in the course repository. It also holds the sorted version, longestConsecutiveSort.

Measured: Two Sum, nested loops against a Map

Two Sum is the problem this module measures. The script is measure.ts in the module folder, and it uses bench.ts from DSA Module 1, kept in the repository’s shared/ folder.

measure.ts builds the slow case for the nested loops. Every pair that adds up to the target uses the last number, so the loops try almost every pair first. Here is an excerpt of the file, with the first two of its four bench calls:

bench("twoSumBrute (two nested loops)", [5_000, 10_000, 20_000], randomCase, ({ nums, target }) => {
  sink += twoSumBrute(nums, target)[1];
});

bench("twoSum (one pass with a Map)", [5_000, 10_000, 20_000], randomCase, ({ nums, target }) => {
  sink += twoSum(nums, target)[1];
});

Each call adds its result to sink, so Node.js can’t skip the work. The other two calls run twoSum at 100,000 and 1,000,000 numbers, and twoSumBrute at 100,000. bench runs each size once to warm up, then five times on fresh inputs, and prints the median.

Pause and predict. twoSumBrute tries about n²/2 pairs. When n doubles, how many times longer should it take? And twoSum?

Here is what node module-01/measure.ts printed:


twoSumBrute (two nested loops)
             n   median ms   x prev
         5,000        5.88         
        10,000       23.40      4.0
        20,000       97.29      4.2

twoSum (one pass with a Map)
             n   median ms   x prev
         5,000        0.33         
        10,000        0.60      1.8
        20,000        1.28      2.1

twoSum, larger
             n   median ms   x prev
       100,000        6.32         
     1,000,000       78.13     12.4

twoSumBrute, ten times LeetCode's limit
             n   median ms   x prev
       100,000     2479.61         

sink 7619946

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.

Each doubling of n made twoSumBrute 4.0 and 4.2 times slower, which is O(n²). twoSum grew 1.8 and 2.1 times per doubling, and 12.4 times from 100,000 to 1,000,000, which is close to linear. The small twoSum times are under 2 ms, so timer noise moves their ratios.

The last table is the opening’s number. At 100,000 numbers, the nested loops took 2,479.61 ms, 106 times the 10,000 row. That’s close to the 100 times O(n²) predicts for ten times the input.

Underneath: how V8 stores a Map and a Set

V8 is the JavaScript engine inside Node.js. It keeps a Map or a Set in one block of memory: an array of buckets, then the entries in the order they were added. So both return their contents in insertion order, which Group Anagrams and Longest Consecutive Sequence relied on. You can read this layout in V8’s ordered-hash-table.h. Keys compare like ===, so an array key matches only the same array, as the ECMAScript specification defines. DSA Module 3 draws the whole table step by step.

Going deeper

You can skip this section. It covers the details the interviews above left out.

Unicode in Valid Anagram

A code point is the number Unicode gives one character. JavaScript stores strings as UTF-16 code units, which are 16-bit numbers. A code point above 0xFFFF, such as most emoji, takes two code units. s[i] reads one code unit, but for...of on a string reads whole code points, as the MDN page on the string iterator shows.

So the Unicode version in the lab walks both strings with for...of:

// O(n) time, O(k) memory for k distinct characters: counts each code point up for s and down for t.
// Works for any Unicode text (the page's follow-up), because for...of walks code points.
export function isAnagramMap(s: string, t: string): boolean {
  if (s.length !== t.length) return false;
  const counts = new Map<string, number>();
  for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
  for (const ch of t) {
    const left = counts.get(ch) ?? 0;
    if (left === 0) return false;
    counts.set(ch, left - 1);
  }
  return true;
}

A Map version that reads s[i] instead returns true for "\u{1F600}\u{1F900}" and "\u{1F500}\u{1FA00}", two pairs of different emoji. The answer is false. The two strings hold the same four code units, paired differently.

An “é” can also be stored two ways: as one code point, or as “e” followed by a combining accent. In one run, isAnagramMap("\u00e9", "e\u0301"), the two forms of “é”, returned false. After normalize("NFC") on both strings, it returned true. So in an interview, ask whether to normalize.

-0 in Product of Array Except Self

The correct code returns [ -0, -6, 0 ] for [2, 0, -3]. That’s because right becomes -3 · 0 before the last step, and that is -0 in JavaScript. JSON.stringify prints the answer as [0,-6,0]. But assert.deepStrictEqual compares numbers with Object.is(), as the Node.js assert docs say, and Object.is(-0, 0) is false. So a local test that expects 0 fails, and the lab’s test adds 0 to each value first, because -0 + 0 is 0.

A heap for Top K Frequent Elements (stretch)

A third answer keeps a min-heap, a tree stored in an array that always has its smallest item on top. The heap holds the k most frequent values seen so far, and it costs O(n + u log k) time. The lab has this version as topKFrequentHeap, and it imports the heap from shared/heap.ts. Module 8 works heap problems, and DSA Module 8 builds the heap.

Cheat sheet

Figure 9 maps each problem in this module to the sign that pointed to its solution.

sign in the problem                      problem  tool              cost
find a partner value for each item       1        Map num => index  O(n)
"seen before?" for each item             217      Set               O(n)
same letters in any order, a to z        242      26 counters       O(n)
group words by a shared key              49       Map key => list   O(n(k+26))
most frequent, counts at most n          347      buckets by count  O(n)
everything except this one, no division  238      left and right    O(n)
values that follow each other            128      Set, run starts   O(n)

Figure 9: when the naive solution searches the array inside a loop, a Map, a Set or an array of counts removes the search.

  • Method: clarify, examples and edge cases, naive solution and its cost, repeated work, optimize, code, test out loud (your example, then one edge case), final cost, follow-ups.
  • Limits: about 10⁸ simple steps per second. n up to 10⁴ allows O(n²); n up to 10⁵ needs O(n log n) or better.
  • Map and Set: O(1) per lookup on average, O(n) extra memory. Look up before you store when an item must not pair with itself.
  • Small integer keys: count in a plain array, such as 26 letters or counts from 1 to n.
  • Both sides: “everything except i” is everything left of i times everything right of i.
  • Final costs: 1, 217 and 128 in O(n) time and memory; 242 in O(n) time, O(1) memory; 49 in O(n · (k + 26)); 347 in O(n); 238 in O(n) with O(1) extra.
  • Next: Module 2 works problems on sorted input, where two pointers moving toward each other replace the map and its memory.

Sources