Arrays and hashing
Use sets and dictionaries to turn nested loops into a single pass.
22 min
Most array problems share one trap: the obvious solution compares each item with every other item, which is O(n²). A hash table (a Python dict or set) usually removes the inner loop, because you can ask "have I seen this?" or "what was stored for this key?" in O(1).
1. Seen-before (set). Remember what you have met, check each new item against it.
2. Count (dict). Count occurrences, or group items by a key:
counts = {}
for x in items:
counts[x] = counts.get(x, 0) + 13. Complement lookup (dict of value to index). To find two numbers that add to a target, for each x you need target - x. Look it up in a dict of the numbers you have already passed:
seen = {} # value -> index
for j, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], j]
seen[x] = jBecause you only look back at earlier items, every pair is checked once, in O(n) time and O(n) space. You trade memory for speed.
Words that are anagrams share the same sorted letters. Use the sorted letters as a dict key to group them: groups.setdefault("".join(sorted(w)), []).append(w). The key is the signature that identifies the group.
- Dict keys must be hashable: strings, numbers, tuples are; lists are not (use
tuple(lst)). - Ask whether duplicates are possible.
[3, 3]with target 6 is a valid pair of different positions. - Decide whether to check before or after storing: storing first would let an item pair with itself.
A gift card is worth exactly $30. A shop lists prices [12, 18, 7, 23]. Find the indexes of two items that cost exactly $30 together.
- 1
seen = {}
An empty dict that will map price to index for items already passed.
Write pair_for_budget(prices, budget). Return [i, j], the indexes (with i < j) of two items whose prices add up to budget. Scan left to right and return the first j that finds a partner; the partner is the earliest item that fits. If there is no pair, return []. O(n) time.
pair_for_budget([12, 18, 7, 23], 30) is [0, 1].
Your code must satisfy
- pair_for_budget([12, 18, 7, 23], 30)→[0,1]first two
- pair_for_budget([5, 9, 1, 8], 9)→[2,3]later pair
- pair_for_budget([3, 3], 6)→[0,1]equal values
- pair_for_budget([1, 2, 3], 10)→[]no pair
- pair_for_budget([], 5)→[]empty
- pair_for_budget([5], 10)→[]cannot reuse one item
def pair_for_budget(prices, budget):
passWrite group_anagrams(words) returning a list of groups, where each group holds the words that are anagrams of each other. Keep words inside a group in their original order, and order the groups by the first appearance of any of their words.
group_anagrams(["eat", "tea", "tan", "ate", "nat"]) is [["eat", "tea", "ate"], ["tan", "nat"]].
Your code must satisfy
- group_anagrams(["eat", "tea", "tan", "ate", "nat"])→[["eat","tea","ate"],["tan","nat"]]classic
- group_anagrams([])→[]empty
- group_anagrams(["a", "b"])→[["a"],["b"]]no anagrams
- group_anagrams(["ab", "ba", "ab"])→[["ab","ba","ab"]]repeat word
- group_anagrams(["", ""])→[["",""]]empty string
def group_anagrams(words):
pass“A nested loop is fine, because computers are fast.”
For small test inputs the slow code runs instantly.
What is actually true
With n = 10⁵ items, a nested loop does 10¹⁰ comparisons, which takes minutes or hours. Interview inputs are often chosen to be that large, and "can you do better?" is the usual follow-up.
How to catch yourself
Ask yourself: what am I searching for inside the inner loop? A dict or set answers it in O(1).
Which hash structure to use.
set
- Stores
- values only
- Answers
- have I seen x?
- Example
- first repeat, duplicates
Best for existence checks
dict (counts)
- Stores
- value to count
- Answers
- how many times?
- Example
- word frequency, majority
Best for counting and grouping
dict (value to index)
- Stores
- value to position
- Answers
- where did I see x?
- Example
- pair for a target
Best for complement lookups
- A set or dict turns "search the rest of the list" into an O(1) lookup, so O(n²) becomes O(n).
- Three patterns: seen-before (set), counting/grouping (dict), complement lookup (value to index).
- Check for the partner before you store the current item.
- You trade O(n) memory for time; say so out loud.
Hashing checks.
Which can be a dict key?
- AA list
- BA tuple of numbers
- CA dict
- DA set
What is the time and space of the dict-based pair search?
- AO(n²) time, O(1) space
- BO(n) time, O(n) space
- CO(n log n) time, O(1) space
- DO(1) time, O(n) space
How many groups does group_anagrams(["ab", "ba", "cd", "dc", "ee"]) return?
Why store x after checking for target - x?
- ATo save memory
- BSo an item cannot pair with itself
- CDicts require it
- DIt is faster
To count items with a dict, write counts[x] = counts.(x, 0) + 1.
Capitalisation, spacing and punctuation are ignored when grading.
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.