STOP 02 · LINEAR STRUCTURES
Hash Counting and Relationship Modeling
One-pass hash map lookup O(n) time · O(n) space
- Learn first
Warm up with this one
LC 1Two SumStuck? Peek at the approach
Look up each complement before inserting the current value so the same index cannot be used twice.
Key points
- Query the complement before storing the current value: one pass finds earlier partners and never pairs an element with itself.
- Store what the question needs: an index for positions, a count for how many, and the first index only when you need the earliest.
- Keys can be built: a sorted string, a count tuple or a (row, value) pair puts everything of one kind into one bucket.
Common pitfalls
- Inserting before querying pairs an element with itself when target equals 2x.
- In C++, map[key] on a missing key inserts a default value; use find or count to test membership.
- In Java, comparing two Integer objects with == can fail above 127; use equals or unbox to int first.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Hash table · chaining and resizing
Insert 12, 7, 4, 15, 9, 20, 3 in order
Try your own input
- Keys
- 0
- Buckets
- 4
- Load factor
- 0.00
- Resizes
- 0
4 empty buckets. Key k goes to bucket k mod (bucket count); keys that land in one bucket form a chain.
InvariantKey k always sits in bucket k mod (bucket count); with the load factor at most 0.75, chains stay constant length on average.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 1, with it.
Python
def two_sum(nums: list[int], target: int) -> tuple[int, int]:
seen: dict[int, int] = {} # value -> index of an earlier element
for i, x in enumerate(nums):
if target - x in seen: # look up before inserting: no self-pairing
return seen[target - x], i
seen[x] = i
return -1, -1C++
pair<int, int> twoSum(const vector<int>& nums, int target) {
unordered_map<int, int> seen; // value -> index of an earlier element
for (int i = 0; i < (int)nums.size(); i++) {
auto it = seen.find(target - nums[i]); // find() never inserts, unlike []
if (it != seen.end()) return {it->second, i};
seen[nums[i]] = i;
}
return {-1, -1};
}Java
class Solution {
int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>(); // value -> index of an earlier element
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]); // look up before inserting: no self-pairing
if (j != null) return new int[] {j, i};
seen.put(nums[i], i);
}
return new int[] {-1, -1};
}
}Go
func twoSum(nums []int, target int) (int, int) {
seen := map[int]int{} // value -> index of an earlier element
for i, x := range nums {
if j, ok := seen[target-x]; ok { // look up before inserting: no self-pairing
return j, i
}
seen[x] = i
}
return -1, -1
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Group by a canonical keyO(n · L log L) time · O(n · L) space
When elements that are the same in some sense must be grouped (anagrams, shifted strings, isomorphic words): compute a canonical key per element and bucket by it. The key can be the sorted letters or the 26 letter counts joined. LC 49 (Group Anagrams) and LC 249 (Group Shifted Strings).
Python
def group_anagrams(words: list[str]) -> list[list[str]]:
"""Words grouped by anagram class, groups in order of first appearance."""
index: dict[str, int] = {} # canonical key -> position of its group
groups: list[list[str]] = []
for w in words:
key = "".join(sorted(w)) # anagrams share their sorted letters
if key not in index:
index[key] = len(groups)
groups.append([])
groups[index[key]].append(w)
return groupsC++
// Words grouped by anagram class, groups in order of first appearance.
vector<vector<string>> groupAnagrams(const vector<string>& words) {
unordered_map<string, int> index; // canonical key -> position of its group
vector<vector<string>> groups;
for (const string& w : words) {
string key = w;
sort(key.begin(), key.end()); // anagrams share their sorted letters
auto [it, fresh] = index.try_emplace(key, (int)groups.size());
if (fresh) groups.emplace_back();
groups[it->second].push_back(w);
}
return groups;
}Java
class Solution {
// Words grouped by anagram class, groups in order of first appearance.
List<List<String>> groupAnagrams(String[] words) {
Map<String, List<String>> groups = new LinkedHashMap<>(); // canonical key -> its words, in first-seen order
for (String w : words) {
char[] letters = w.toCharArray();
Arrays.sort(letters); // anagrams share their sorted letters
groups.computeIfAbsent(new String(letters), k -> new ArrayList<>()).add(w);
}
return new ArrayList<>(groups.values());
}
}Go
import "sort"
// groupAnagrams returns the words grouped by anagram class, in order of first appearance.
func groupAnagrams(words []string) [][]string {
index := map[string]int{} // canonical key -> position of its group
var groups [][]string
for _, w := range words {
letters := []byte(w)
sort.Slice(letters, func(i, j int) bool { return letters[i] < letters[j] })
key := string(letters) // anagrams share their sorted letters
at, ok := index[key]
if !ok {
at = len(groups)
index[key] = at
groups = append(groups, nil)
}
groups[at] = append(groups[at], w)
}
return groups
}Hash set: count runs only from their startsO(n) time · O(n) space
For the longest run of consecutive integers in O(n) (LC 128), without sorting: put the numbers in a set, and treat x as a run start only when x - 1 is absent, then count upwards from it. Each number is touched at most twice, so it stays linear.
Python
def longest_consecutive(nums: list[int]) -> int:
"""Length of the longest run of consecutive integers, in O(n)."""
have = set(nums)
best = 0
for x in have:
if x - 1 in have:
continue # not a run start: the run is counted from its start
y = x
while y + 1 in have:
y += 1
best = max(best, y - x + 1)
return bestC++
// Length of the longest run of consecutive integers, in O(n).
int longestConsecutive(const vector<int>& nums) {
unordered_set<int> have(nums.begin(), nums.end());
int best = 0;
for (int x : have) {
if (have.count(x - 1)) continue; // not a run start: the run is counted from its start
int y = x;
while (have.count(y + 1)) y++;
best = max(best, y - x + 1);
}
return best;
}Java
class Solution {
// Length of the longest run of consecutive integers, in O(n).
int longestConsecutive(int[] nums) {
Set<Integer> have = new HashSet<>();
for (int x : nums) have.add(x);
int best = 0;
for (int x : have) {
if (have.contains(x - 1)) continue; // not a run start: the run is counted from its start
int y = x;
while (have.contains(y + 1)) y++;
best = Math.max(best, y - x + 1);
}
return best;
}
}Go
// longestConsecutive returns the length of the longest run of consecutive integers, in O(n).
func longestConsecutive(nums []int) int {
have := map[int]bool{}
for _, x := range nums {
have[x] = true
}
best := 0
for x := range have {
if have[x-1] {
continue // not a run start: the run is counted from its start
}
y := x
for have[y+1] {
y++
}
best = max(best, y-x+1)
}
return best
}Why it works
- One pass misses nothing: for any answer pair i < j, index i is already in the map when the scan reaches j, so the pair is found at j. Looking up before storing means j is never paired with itself.
- Grouping is correct when equal keys mean the same class and different classes get different keys. A sorted string or a letter-count tuple has that property, so each bucket holds exactly one class.
- Expected O(1) lookups make the whole scan O(n); heavy collisions can degrade it, which is worth one sentence in an interview.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
我用哈希表把找配对从 O(n²) 降到 O(n)。从左往右扫,每到一个元素先查它需要的另一半是否已经出现过,再把它自己存进去。任意一对答案在扫到右边那个元素时,左边那个已经在表里,所以不会漏;先查后存也保证不会和自己配对。时间 O(n),空间 O(n)。I use a hash map to turn the pair search from O(n²) into O(n). Scanning left to right, I first look up the complement of the current element, then store the element itself. For any valid pair, the left element is already in the map when I reach the right one, so nothing is missed, and looking up before storing prevents pairing an element with itself. That is O(n) time and O(n) space.Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
Practice by stage
This stop's 19 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 5
| # | Problem | Approach | Rating |
|---|---|---|---|
| 1 | Two Sum | Look up each complement before inserting the current value so the same index cannot be used twice. | |
| 219 | Contains Duplicate II | Store each value's most recent position and use index differences to detect nearby duplicates. | |
| 409 | Longest Palindrome | Use frequency parity to calculate the longest constructible palindrome, separating paired characters from the center. | |
| 266 | Palindrome Permutation 🔒 | Reduce the existence of a palindromic permutation to the number of odd character frequencies. | |
| 1010 | Pairs of Songs With Total Durations Divisible by 60 | Count complementary remainders, handling remainder zero and the halfway remainder as self-pairing cases. |
Core 13
| # | Problem | Approach | Rating |
|---|---|---|---|
| 49 | Group Anagrams | Build a stable equivalence-class key for strings and compare sorted-string keys with character-count keys. | |
| 128 | Longest Consecutive Sequence | Extend consecutive runs only from their starting values and justify the total work of the hash-based scan. | |
| 454 | 4Sum II | Split four-array combinations into two groups of pair sums and reduce enumeration with frequency hashing. | |
| 187 | Repeated DNA Sequences | Detect repeated fixed-length substrings and compare direct string keys with rolling encodings. | |
| 249 | Group Shifted Strings 🔒 | Represent shift-equivalent strings by adjacent character differences modulo the alphabet size, handling wraparound and single characters. | |
| 1679 | Max Number of K-Sum Pairs | Consume complementary value counts in pairs, ensuring each element is used at most once. | |
| 2342 | Max Sum of a Pair With Equal Sum of Digits | Group numbers by digit sum and retain the two largest in each group without sorting every candidate. | |
| 2364 | Count Number of Bad Pairs | Rearrange the index-difference and value-difference condition into equal-key counting, then subtract from the total number of pairs. | |
| 1814 | Count Nice Pairs in an Array | Rearrange the equation involving reversed numbers into a per-element key and count equal-key pairs. | |
| 1657 | Determine if Two Strings Are Close | Distinguish the requirement of identical character sets from the requirement that frequency arrays can be permuted. | |
| 554 | Brick Wall | Turn crossing the fewest bricks into finding the most frequently aligned internal edge position. | |
| 1930 | Unique Length-3 Palindromic Subsequences | Fix the outer character's first and last positions, then count distinct middle characters to form length-three palindromes. | |
| 2131 | Longest Palindrome by Concatenating Two Letter Words | Pair reversed words and handle symmetric words separately as possible palindrome centers. |
Advanced 1
| # | Problem | Approach | Rating |
|---|---|---|---|
| 220 | Contains Duplicate III | Maintain neighboring values within a bounded index window, comparing ordered sets with bucket partitioning. |
OA questions on this topic 268
- Count Powers of k in ReadingsMeta
- Longest Subarray With Value Frequency > ThresholdMeta
- Longest Contiguous-House Segment After Each BuildMeta
- Enumerating Narrative SectionsMeta
- Self-Sufficient SubstringAmazon
- Outlier ValueAmazon
- Get Total BalancedAmazon
- Find Maximum PackagesAmazon
- Find Max Health SumAmazon
- Find Score (p-Matching)Amazon
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.