Trade O(n) space for O(1) lookup. The most powerful tool for "have I seen this?" type questions.
For each number, check if complement (target - num) is in the map. Step through to see how the hashmap builds up.
Type a word and see character frequencies counted with Counter.
| Operation | dict / set | list |
|---|---|---|
Lookup (x in ...) | O(1) | O(n) |
| Insert | O(1) | O(1) end / O(n) middle |
| Delete | O(1) | O(n) |
x in arr inside a loop, replace arr with a set. This drops O(n²) to O(n).Counter or defaultdict(int) to count occurrences. Check if two strings are anagrams: their Counters must be equal.set when you only need "does this exist?" not how many times. Smaller memory than dict, same O(1) lookup.def two_sum(arr, target): seen = {} # value → index for i, num in enumerate(arr): needed = target - num if needed in seen: # O(1) lookup return [seen[needed], i] seen[num] = i # add AFTER checking! return []
seen BEFORE checking, a number might match with itself. Always check first, then add.from collections import Counter, defaultdict # Anagram check — O(n) def is_anagram(s, t): return Counter(s) == Counter(t) # Group anagrams def group_anagrams(words): groups = defaultdict(list) for word in words: key = "".join(sorted(word)) groups[key].append(word) return list(groups.values()) # Longest Consecutive Sequence — O(n) def longest_consecutive(nums): s = set(nums) best = 0 for n in s: if n - 1 not in s: # start of sequence length = 1 while n + length in s: length += 1 best = max(best, length) return best