Hash maps remember what you have seen
Most array questions have an obvious answer: check every pair. The first upgrade to try is a hash map, which stores values you have already passed so each later lookup costs on average. You trade memory for a factor of in time.
The standard move is the complement lookup. To count pairs of order sizes that add to a target , walk the array once. At each value , ask how many earlier values equal , then record .
from collections import Counter
def count_pairs(xs, target):
seen = Counter()
count = 0
for x in xs:
count += seen[target - x]
seen[x] += 1
return count
count_pairs([3, 5, 2, 5, 3, 7, 1], 8) # 5The two 3s and two 5s give pairs, and gives one more, so the answer is 5. Looking up before inserting matters: it stops a value from pairing with itself when , and it counts duplicates correctly. Time is , space .
The same idea covers a long list of interview staples. Anagram grouping keys a dictionary on "".join(sorted(word)) or on a letter count. "First repeated trade ID" is a set membership test. Whenever the inner loop of your brute force is searching for a specific value, a hash map can usually replace that loop.