Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Practice · Coding

Arrays and hashing

Trade memory for time: a hash map answers "have I seen this?" in O(1), and most array problems reduce to asking it the right question.


When it applies

Reach for a hash map or set when the work you are repeating is a lookup — "have I seen this value", "how many times", "what index was it at". Each of those is O(n) by scanning and O(1) by hashing, and that single change is what turns a quadratic solution linear.

The harder skill is choosing what to key on. Keying on the value solves membership; keying on a running total solves range sums; keying on a sorted signature groups anagrams. Get the key right and the problem usually collapses to one pass.

Signals: "count the number of", "find duplicates", "group by", "subarray summing to", "seen before", "in O(n) time". If the input is already sorted, check whether two pointers does the same job in O(1) space before you spend O(n) memory.


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

seen = {}                    # key -> whatever you need back
for i, x in enumerate(a):
    key = derive(x)          # the whole problem is choosing this
    if key in seen:
        use(seen[key], i)    # look up BEFORE inserting, or you match x with itself
    seen[key] = i

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.