NeetCode 150, stage 1: Arrays and Hashing

All 150 problems · Two Pointers →

Almost every problem starts with a slice, and the hash map is the first tool that removes a nested loop. This stage trains one trade: you use more memory, and the time goes from O(n²) to O(n).

Garden notes: the Go syntax for this stage, Arrays and Hashing pattern, Arrays, Hash Tables.

Problems on this page

#ProblemLevelPatternTemplate
1217. Contains DuplicateEasyHash setA: Seen set
2242. Valid AnagramEasyLetter countB: Count array or count map
31. Two SumEasyHash map of value to indexA: Seen set
449. Group AnagramsMediumHash map with a count keyB: Count array or count map
5347. Top K Frequent ElementsMediumCount map, then bucket sortC: Bucket by count
6271. Encode and Decode StringsMediumLength-prefix encodingE: Length prefix
7238. Product of Array Except SelfMediumPrefix and suffix productsD: Prefix and suffix passes
836. Valid SudokuMediumSeen sets for rows, columns and boxesA: Seen set
9128. Longest Consecutive SequenceMediumHash set, count from the start of each runA: Seen set

Templates to memorize

Template A: Seen set

Signal

The problem says duplicate, “already seen”, pair or “find the partner”. A brute-force answer compares each item with each other item.

// TEMPLATE A: one pass with a "seen" set or map.
// Ask at each item: "did I already see what I need?"
func hasPairWithSum(nums []int, target int) bool {
    // a set: the value type uses no memory
    seen := make(map[int]struct{}, len(nums))
    for _, x := range nums {
        if _, ok := seen[target-x]; ok { // 1. CHECK for the partner first
            return true
        }
        seen[x] = struct{}{} // 2. STORE x after the check
    }
    return false
}

The moves are CHECK, then STORE. Do the check before the store, so an item is never its own partner. Use a set when the fact “it is there” is enough. Use a map when you also need the index.

Say it

“I trade memory for time. One pass with a hash map gives O(n) time and O(n) space.”

Template B: Count array or count map

Signal

The problem says anagram, frequency, “how many times” or “same letters”. The order of the items does not matter, only the counts.

// TEMPLATE B: count the items, then compare the counts or use them as a
// key.
func letterCount(s string) [26]int {
    var count [26]int // 26 zeros: one counter for each lower-case letter
    for i := 0; i < len(s); i++ {
        count[s[i]-'a']++ // 'a' -> 0, 'b' -> 1, and so on
    }
    return count // arrays compare with ==, and an array can be a map key
}
 
// For values that are not letters, count with a map.
func countValues(nums []int) map[int]int {
    count := make(map[int]int, len(nums))
    for _, x := range nums {
        count[x]++ // a missing key reads as 0, so ++ works
    }
    return count
}

The moves are COUNT, then COMPARE or USE AS A KEY. A [26]int array is faster than a map for lower-case letters. An array is also a valid map key, and a slice is not.

Say it

“Two words are anagrams when their letter counts are equal, so I compare 26 counters.”

Template C: Bucket by count

Signal

The problem asks for the K most frequent items, and it wants better than O(n log n).

// TEMPLATE C: bucket by count. buckets[c] holds the values that appear c
// times.
func mostFrequentFirst(nums []int) []int {
    count := make(map[int]int)
    for _, x := range nums { // 1. COUNT
        count[x]++
    }
    // a count is between 1 and len(nums)
    buckets := make([][]int, len(nums)+1)
    // 2. BUCKET: the count is the index
    for x, c := range count {
        buckets[c] = append(buckets[c], x)
    }
    res := make([]int, 0, len(count))
    // 3. READ from the largest count down
    for c := len(buckets) - 1; c >= 1; c-- {
        res = append(res, buckets[c]...)
    }
    return res
}

The moves are COUNT, BUCKET, then READ FROM THE END. The bucket index is a count, and a count is at most n. So the buckets replace the sort.

Say it

“A count is at most n, so I use the count as an index. That gives O(n) with no sort and no heap.”

Template D: Prefix and suffix passes

Signal

The answer at index i needs all the items before i and all the items after i. The problem forbids division, or division does not help.

// TEMPLATE D: two passes. res[i] = (sum of the items before i) + (sum of
// the items after i).
// Change + to * (and the start value 0 to 1) for a product.
func sumOfOthers(nums []int) []int {
    n := len(nums)
    res := make([]int, n)
    left := 0
    for i := 0; i < n; i++ { // 1. left to right
        res[i] = left   // write first: left does not include nums[i]
        left += nums[i] // then take nums[i] into the running value
    }
    right := 0
    for i := n - 1; i >= 0; i-- { // 2. right to left
        res[i] += right
        right += nums[i]
    }
    return res
}

The moves are PASS LEFT TO RIGHT with a running value, then PASS RIGHT TO LEFT with a second running value. Each pass writes the value before it includes the item at i.

Say it

“The answer at i is the product of the left part times the product of the right part. Two passes give the two parts.”

Template E: Length prefix

Signal

You must put many strings in one string and get them back. The strings can contain each character, so no separator is safe.

// TEMPLATE E: length prefix. "go" becomes "2#go".
func encodeOne(s string) string {
    // WRITE the length, the marker, the text
    return strconv.Itoa(len(s)) + "#" + s
}
 
// decodeOne reads one string that starts at index i.
// It returns the string and the index of the next one.
func decodeOne(data string, i int) (string, int) {
    j := i
    for data[j] != '#' { // FIND the marker after the digits
        j++
    }
    n, _ := strconv.Atoi(data[i:j]) // PARSE the length
    start := j + 1
    return data[start : start+n], start + n // CUT exactly n bytes
}

The moves are WRITE the length, a marker and the text. To read, FIND the marker, PARSE the length, then CUT exactly that many bytes. The reader never searches inside the text, so the text can contain the marker.

Say it

“I write the length before each string, so the decoder never looks for a separator inside the data.”

Mistakes in this stage

  • A write to a nil map panics. Make the map with make or with a literal.
  • The order of a range over a map is random. Sort the result if the order matters.
  • make([]int, n) then append gives n zeros first. Use make([]int, 0, n) before append.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

217. Contains Duplicate

LeetCode 217 · Easy

242. Valid Anagram

LeetCode 242 · Easy

1. Two Sum

LeetCode 1 · Easy

49. Group Anagrams

LeetCode 49 · Medium

347. Top K Frequent Elements

LeetCode 347 · Medium

271. Encode and Decode Strings

LeetCode 271 (premium) · free on NeetCode · Medium

238. Product of Array Except Self

LeetCode 238 · Medium

36. Valid Sudoku

LeetCode 36 · Medium

128. Longest Consecutive Sequence

LeetCode 128 · Medium


All 150 problems · Two Pointers →