Skip to content
DSAPrep

    ↑↓ to move · Enter to open · Esc to close

    ← All patterns

    Arrays & Hashing

    Trade memory for speed: remember what you have seen in a hash map or set.

    Reach for it when

    • Find a pair / duplicate / complement in one pass
    • Group items by a computed key (anagrams, frequencies)
    • Count occurrences, or answer membership questions in O(1)

    Core idea

    Most brute-force array solutions re-scan the input for every element. A hash map turns that inner scan into an O(1) lookup: store each value (or a derived key such as a sorted string or a running sum) as you go, and ask the map whether the partner you need has already appeared.

    Template · O(n) time, O(n) space

    def two_sum(nums, target):
    seen = {} # value -> index
    for i, x in enumerate(nums):
    if target - x in seen: # partner already seen?
    return [seen[target - x], i]
    seen[x] = i # record AFTER checking (no self-pairing)
    return []

    Common pitfalls

    • Inserting before checking lets an element pair with itself
    • Lists are unhashable: use a tuple (or a sorted string) as the key
    • Prefix-sum counting needs the base case count[0] = 1

    Practice · 0 / 19 done