Seen set
Use a set when you only care whether something has appeared before.
This lesson is about a simple tradeoff:
spend extra memory so you do not repeat expensive searching.
That is the heart of many arrays and hashing questions.
Seen set
Use a set when you only care whether something has appeared before.
Value to index map
Use a hash map when you need to find a matching partner quickly.
Frequency map
Use counts when the exact number of occurrences matters.
Given an array nums and a target, return the indices of two numbers that add up to the target.
Check every pair.
for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j]Runtime: O(n^2)
For each number, you really want to know whether the complement already appeared.
If the current number is num, the needed partner is target - num.
A hash map can store values we have seen and the index where we saw them.
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: seen = {}
for i, num in enumerate(nums): need = target - num if need in seen: return [seen[need], i] seen[num] = iRuntime: O(n)
Space: O(n)
Do these in order:
Do not force hashing onto every array question.
Sometimes the right answer is sorting, two pointers, prefix sums, or plain iteration. The win here is not “always use a map”. The win is learning when fast lookup is the missing piece.
Try to answer these from memory:
O(n) solution?Next: Training roadmap