Skip to main content

Arrays & Hashing

Learning objectives
  • Recognize when a problem reduces to "have I seen this before?", "how many times?", or "what is the sum of this range?"
  • Apply prefix sums, difference arrays and prefix-sum + hash map to subarray problems in O(n)
  • Choose between a map, a fixed-size counting array, sorting, and a sorted slice for lookups
  • Explain how Go maps are implemented (Swiss tables since Go 1.24) and the operational consequences: random iteration, no shrinking, no concurrent writes

TL;DR​

  • Hash map = trade O(n) memory for O(1) average lookups. It turns nested-loop "find the partner" problems (Two Sum) into a single pass.
  • Prefix sums: P[i+1] = P[i] + a[i], then any range sum is P[r+1] − P[l] in O(1). A running account balance is a prefix sum.
  • Prefix sum + hash map counts subarrays with sum k in O(n), and works with negative numbers where sliding windows fail.
  • Difference arrays apply many range increments in O(1) each, then one prefix pass materializes them (bookings per night, active sessions per minute).
  • Counting arrays ([26]int) beat maps for small fixed alphabets, and arrays are comparable, so they work as map keys (anagram grouping).
  • Go maps: Swiss tables since Go 1.24 (groups of 8 slots + control bytes, 7/8 load factor, growth one bounded table at a time). Iteration order is random, maps never shrink, and concurrent writes crash the process.

When to reach for it​

  • "Find two items that combine to X" → store what you have seen; look up the complement.
  • "Count / group / deduplicate" → map[K]int, map[K][]V, map[K]struct{}.
  • "Sum (or XOR, or count) of a range", many queries over static data → prefix sums.
  • "Number of subarrays with sum / balance / parity equal to k" → prefix sum + map of earlier prefix values.
  • "Apply +v to every element in [l, r]" many times → difference array.
  • The alphabet is tiny and fixed (lowercase letters, digits, bytes) → counting array instead of a map.
  • You need O(1) existence checks for a "seen" set while iterating, and memory is affordable.

Core concepts​

Arrays and slices in Go​

A Go array [N]T is a value: fixed length, copied on assignment, comparable when T is comparable. A slice is a 24-byte header (pointer, length, capacity) that views an array. Index access is O(1) and iteration is cache-friendly because elements are contiguous. Slicing (s[a:b]) shares the backing array — fast, but writes through one slice are visible through the other, and a small slice keeps a huge array alive. See Complexity Analysis for growth costs and Common Pitfalls for aliasing.

Prefix sums​

Define P[0] = 0 and P[i+1] = P[i] + a[i]. Then the inclusive sum of a[l..r] is P[r+1] − P[l]. Using n+1 entries avoids special-casing l = 0.

// RangeSum answers inclusive range-sum queries in O(1) after O(n) setup.
// Amounts are int64 minor units (cents): never use floats for money.
type RangeSum struct{ prefix []int64 }

func NewRangeSum(amounts []int64) RangeSum {
p := make([]int64, len(amounts)+1)
for i, a := range amounts {
p[i+1] = p[i] + a
}
return RangeSum{prefix: p}
}

// Sum returns amounts[l] + ... + amounts[r].
func (rs RangeSum) Sum(l, r int) int64 { return rs.prefix[r+1] - rs.prefix[l] }

Banking view: if a is the list of ledger postings for an account in time order, P is the running balance, "net movement between two postings" is a subtraction, and "balance as of a timestamp" becomes a binary search over posting times followed by one lookup (see Binary Search and Double-Entry Ledger Design).

2D prefix sums extend the idea to grids: P[i+1][j+1] = a[i][j] + P[i][j+1] + P[i+1][j] − P[i][j], and a rectangle sum is four lookups (inclusion–exclusion).

Difference arrays​

The inverse operation. To add v to every element of [l, r], do d[l] += v and d[r+1] −= v; a final prefix pass over d produces the values. Each update is O(1) instead of O(r − l).

// occupancy returns rooms booked per night. Each booking is a
// half-open [checkIn, checkOut) range of night indexes.
func occupancy(nights int, bookings [][2]int) []int {
diff := make([]int, nights+1)
for _, b := range bookings {
diff[b[0]]++
diff[b[1]]-- // the checkout night is free again
}
occ := make([]int, nights)
running := 0
for i := range nights {
running += diff[i]
occ[i] = running
}
return occ
}

This is exactly the inventory question in a Hotel Reservation System: many range bookings, then "is any night over capacity?".

Hash maps and sets​

  • Set: map[K]struct{} (zero-byte values) or map[K]bool (simpler to read). Both are fine; be consistent.
  • Counter: m[k]++ works on a missing key because the zero value is 0.
  • Grouping: m[k] = append(m[k], v) works on a missing key because a nil slice appends fine.
  • Keys must be comparable: numbers, strings, pointers, channels, arrays and structs of comparable fields. Slices, maps and funcs are not. An interface key whose dynamic type is not comparable panics at runtime.
  • Composite keys: use a struct (type key struct{ account string; day int }) or an array ([2]int), never string concatenation — "ab"+"c" and "a"+"bc" collide.
  • Not addressable: &m[k] does not compile, and m[k].Field = x does not work for struct values; store pointers or reassign the whole value.

Counting with fixed-size arrays​

For a known small alphabet, var cnt [26]int is faster than a map (no hashing, no allocation, contiguous) and, because arrays are comparable, [26]int can itself be a map key — the canonical anagram signature. For bytes use [256]int; for Unicode text fall back to map[rune]int.

Go map internals at a glance​

Go 1.24 replaced the map implementation with Swiss tables (the design popularized by Google's Abseil C++ library). The language semantics did not change; performance and memory behaviour did. Go 1.24 also shipped GOEXPERIMENT=noswissmap as a temporary escape hatch.

  • A map is a directory of tables (extendible hashing). Each table is an array of groups; a group holds 8 slots plus an 8-byte control word, one control byte per slot.
  • The 64-bit hash is split: H1 (upper 57 bits) picks the starting group, H2 (lower 7 bits) is stored in the control byte of a full slot. A control byte otherwise marks the slot as empty or deleted (tombstone).
  • Lookup compares H2 against all 8 control bytes of a group at once (SIMD on amd64, bit tricks elsewhere), then compares full keys only for matching slots. If the group has an empty slot and no match, the key is absent; otherwise probing continues to the next group (quadratic probing over groups).
  • Maximum load factor is 7/8. A table that fills up grows; once a table reaches its maximum size (1024 slots in the Go 1.24 implementation) it splits into two instead. Only one table is rehashed at a time, which bounds the latency of any single insert in a huge map.
  • Small maps (up to 8 entries) are a single group with no directory.
  • Pre-1.24 maps used buckets of 8 entries with "tophash" bytes, overflow-bucket chains, a 6.5 average load per bucket, and incremental evacuation during growth. You will still meet that description in older articles and interviews.

Behaviour that matters in production, regardless of implementation:

  • Iteration order is deliberately randomized. Sort keys (slices.Sorted(maps.Keys(m))) for deterministic output — reports, hashes over data, golden-file tests.
  • Maps do not shrink. Deleting 9M of 10M entries keeps the memory; clear(m) empties but also keeps capacity. Allocate a new map to release memory.
  • Concurrent writes are a fatal error (fatal error: concurrent map writes), not a recoverable panic. Guard with a sync.Mutex/RWMutex or use sync.Map for its narrow use cases (sync, atomic & context).
  • Hash flooding resistance: every map gets a random seed, and the hash uses AES hardware instructions where available, so attackers cannot precompute colliding keys — relevant for maps keyed by user-supplied input such as HTTP headers.
  • NaN keys: NaN != NaN, so each m[math.NaN()] = v inserts a new unreachable entry. Avoid float keys.

Trade-offs​

OptionStrengthsWeaknessesChoose when
map[K]VO(1) average insert/lookup, any comparable keyMemory overhead per entry, random order, worse constants for tiny nGeneral lookup/count/group with large or unknown key space
Counting array [N]intNo hashing or allocation, comparable as a keyOnly for small dense key rangesLetters, digits, bytes, small bounded integers
Sort + scanO(1) extra space, groups equal items, enables two pointersO(n log n), reorders dataMemory is tight or you need ordered output anyway
Sorted slice + binary searchCompact, cache-friendly, ordered iteration and range queriesO(n) insertsMostly-static data read many times (rate tables, BIN ranges)
Prefix sumsO(1) range queriesO(n) rebuild on any updateStatic data, many range queries
Fenwick / segment treeO(log n) updates and range queriesMore codeData changes between queries
Bitset1 bit per possible keyNeeds a dense integer key spaceMembership over IDs in a known range

In practice​

Problem 1 — Two Sum (LeetCode 1)​

Problem. Given integers and a target, return indexes of two distinct elements that add up to the target.

Approach. For each value v, the partner is target − v. Look it up in a map of values already seen (value → index) before inserting v, which also handles v + v = target correctly.

func twoSum(nums []int, target int) (int, int, bool) {
seen := make(map[int]int, len(nums)) // value -> index
for i, v := range nums {
if j, ok := seen[target-v]; ok {
return j, i, true
}
seen[v] = i
}
return 0, 0, false
}

Complexity. O(n) average time, O(n) space. Follow-up: if the input is sorted, two pointers give O(1) space (Two Pointers & Sliding Window).

Problem 2 — Group Anagrams (LeetCode 49)​

Problem. Group words that are permutations of each other.

Approach. The canonical key is the letter histogram. A [26]int is comparable, so it can be the map key directly — no sorting each word (O(k log k)) and no string building.

func groupAnagrams(words []string) [][]string {
groups := make(map[[26]int][]string)
for _, w := range words {
var key [26]int
for i := 0; i < len(w); i++ {
key[w[i]-'a']++ // input is lowercase ASCII
}
groups[key] = append(groups[key], w)
}
out := make([][]string, 0, len(groups))
for _, g := range groups {
out = append(out, g)
}
return out
}

Complexity. O(n·k) time for n words of length k, O(n·k) space. Note the output group order is random — sort it if a test or API requires determinism.

Problem 3 — Subarray Sum Equals K (LeetCode 560)​

Problem. Count contiguous subarrays whose sum is exactly k. Values may be negative.

Approach. A subarray (i, j] sums to k exactly when P[j] − P[i] = k, i.e. P[i] = P[j] − k. Walk left to right keeping a count of every prefix value seen so far; at each step add the number of earlier prefixes equal to prefix − k. Seed the map with 0: 1 for subarrays starting at index 0. A sliding window does not work here because negative numbers break monotonicity.

func subarraySum(nums []int, k int) int {
count, prefix := 0, 0
seen := map[int]int{0: 1} // prefix sum -> occurrences
for _, v := range nums {
prefix += v
count += seen[prefix-k]
seen[prefix]++
}
return count
}

Complexity. O(n) time, O(n) space. Reconciliation flavour: "which contiguous run of statement lines explains a discrepancy of exactly 1,250.00?" is the same algorithm over amounts in cents (Reconciliation & Settlement).

Problem 4 — Longest Consecutive Sequence (LeetCode 128)​

Problem. Given unsorted integers, find the length of the longest run of consecutive values (e.g. 4, 5, 6, 7) in O(n).

Approach. Put everything in a set. Only start counting from a value v where v − 1 is absent (a run start), then walk v + 1, v + 2, …. Each value is visited by at most one walk, so the total is linear. Iterate over the set, not the input, so duplicate run starts do not repeat work.

func longestConsecutive(nums []int) int {
set := make(map[int]struct{}, len(nums))
for _, v := range nums {
set[v] = struct{}{}
}
best := 0
for v := range set {
if _, hasPrev := set[v-1]; hasPrev {
continue // not the start of a run
}
length := 1
for {
if _, ok := set[v+length]; !ok {
break
}
length++
}
best = max(best, length)
}
return best
}

Complexity. O(n) average time, O(n) space. Sorting gives O(n log n) with O(1) extra — say both.

Practice list​

  • Easy: Two Sum (1), Contains Duplicate (217), Valid Anagram (242), Range Sum Query – Immutable (303)
  • Medium: Group Anagrams (49), Top K Frequent Elements (347), Product of Array Except Self (238), Valid Sudoku (36), Encode and Decode Strings (271), Longest Consecutive Sequence (128), Subarray Sum Equals K (560), Contiguous Array (525), Range Sum Query 2D – Immutable (304)
  • Hard: First Missing Positive (41), Number of Submatrices That Sum to Target (1074)

Common pitfalls​

  • Relying on map iteration order in output, tests, or a checksum over records. Symptom: flaky tests, different report ordering per run.
  • Concurrent map writes from goroutines handling requests. Symptom: the whole service crashes with fatal error: concurrent map writes under load, never in unit tests. Run tests with -race.
  • Writing to a nil map (var m map[string]int; m["a"] = 1) panics. Reading from a nil map is fine.
  • Expecting memory back after deletes. A long-lived dedup map that peaked during a flash sale keeps its peak size; rotate it (allocate a new one) periodically.
  • Off-by-one in prefix sums: using n entries instead of n+1, or forgetting the 0: 1 seed in the prefix-count map (misses subarrays starting at index 0).
  • Overflow: prefix sums of 10⁵ values up to 10⁹ exceed int32; Go's int is 64-bit on 64-bit platforms, but explicit int32 fields in structs overflow silently.
  • Floats for money in sums. Rounding drift makes reconciliation fail by a cent. Use int64 minor units or a decimal type (Schema Patterns: Money, Audit, Multi-tenancy).
  • String-concatenated composite keys that collide ("ab"+"c" vs "a"+"bc"). Use struct or array keys.

Interview angle​

  • Start with the brute force (nested loops), then say "I can trade memory for time with a hash map" — interviewers want to hear the trade-off named.
  • For subarray questions, explicitly ask "can values be negative?" — it decides between a sliding window and prefix sum + map.
  • Expect follow-ups: "What if the data does not fit in memory?" (partition by hash into files, external sort, or a Bloom filter pre-check), "What if this is a stream?" (bounded maps, approximate counting with a count-min sketch — see Data Structures Inside Real Systems), "Is your map safe under concurrency?".
  • A strong Go candidate mentions random iteration order, the comparable-key rule (arrays as keys), and that maps do not shrink. Knowing that Go 1.24 moved to Swiss tables signals you follow the runtime.
  • Red flags: claiming map lookups are O(1) worst case without qualification, using fmt.Sprint to build keys in a hot loop, or ignoring the "negative numbers" edge case.

Self-check​

1. Why must the prefix-count map in Subarray Sum Equals K start with 0 → 1?

The subarray nums[0..j] sums to k when P[j+1] − P[0] = k, and P[0] = 0. Without the seed, the empty prefix is never counted, so every qualifying subarray that starts at index 0 is missed.

2. Why does a sliding window fail for "count subarrays with sum k" when values can be negative?

Sliding windows rely on monotonicity: growing the window can only increase the sum, shrinking can only decrease it, so you know which pointer to move. With negative values, extending the window may lower the sum, so there is no safe rule for moving pointers. Prefix sums with a hash map do not depend on monotonicity.

3. Describe a Go map lookup in the Swiss-table implementation.

Hash the key with the map's seed. The upper 57 bits (H1) choose a table via the directory and a starting group; the lower 7 bits (H2) are compared against all 8 control bytes of the group in parallel. Matching slots have their full keys compared. If no match and the group has an empty slot, the key is absent; otherwise the probe moves to the next group.

4. Why can [26]int be a map key but []int cannot?

Map keys must be comparable with ==. Arrays of comparable elements are comparable value types (compared element by element). Slices are references to a backing array whose contents can change, so Go does not define == for them (only comparison with nil).

5. When would you choose a sorted slice with binary search over a map?

When data is mostly static and read heavily, memory is tight, or you need ordered iteration or range queries (e.g. card BIN ranges, tiered fee tables, rate schedules). A sorted slice is compact and cache-friendly, gives O(log n) lookups and supports "first entry ≥ x" queries that a map cannot answer.

6. Scenario: an idempotency-key dedup map in a payment service grows to 2 GB during a sale and never shrinks. What happened and what do you do?

Go maps keep their allocated tables after deletions, so the memory peak persists. Options: rotate maps by time window (current + previous generation, drop the old one wholesale), bound the structure (TTL cache with eviction), or move dedup to a shared store with TTLs (Redis, a database unique index), which you need anyway for correctness across replicas — see Idempotency & Exactly-Once.

7. How do you add +1 to 10⁵ ranges over 10⁶ positions efficiently?

Use a difference array: for each range [l, r], d[l]++ and d[r+1]-- (O(1) each), then one prefix-sum pass over d to get the final counts. Total O(n + q) instead of O(n·q).

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Build a mini reconciler. Input: two CSV-like slices of (reference string, amountCents int64) — one from the bank statement, one from your ledger — with duplicates allowed.

  1. Report unmatched entries on each side using a map[struct{ ref string; amt int64 }]int multiset (increment for one side, decrement for the other).
  2. For a separate list of daily net movements, find every contiguous run of days whose total equals a given discrepancy, using prefix sums + map (adapt Problem 3 to return index ranges).
  3. Write table-driven tests including duplicates, negative amounts (refunds), and an empty side; make the output deterministic by sorting.

Done when tests pass with go test -race, runtime is O(n + m), and the report order is stable across runs.

Further reading​

  • Michael Pratt, "Faster Go maps with Swiss Tables" — The Go Blog (2025), and the Go 1.24 release notes
  • Matt Kulukundis, "Designing a Fast, Efficient, Cache-friendly Hash Table, Step by Step" — CppCon 2017 talk (the Abseil Swiss table)
  • Keith Randall, "Inside the Map Implementation" — GopherCon 2016 (the pre-1.24 design)
  • Aziz, Lee, Prakash, Elements of Programming Interviews — arrays and hash tables chapters
  • NeetCode 150 — "Arrays & Hashing" section (neetcode.io)
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).