Home / Patterns / Arrays & Hashing

Arrays & Hashing Pattern Hub

9 problems

Contains Duplicate

easy
TC: O(N) · SC: O(N)

Maintain a hash set of previously seen numbers. Return True immediately if the current element is already in the set; otherwise insert and continue.

Encode and Decode Strings

medium
TC: O(N) · SC: O(N)

Length-prefix framing (`<len>#<string>`). Read digits up to `#` to know the exact payload character count `L`, then slice the next `L` characters literally—content characters like `#` inside payloads are never ambiguous.

Group Anagrams

medium
TC: O(N * K) · SC: O(N * K)

Canonicalize every string to its 26-letter frequency signature (avoiding K log K sorting overhead per string) and bucket strings sharing the identical signature.

Longest Consecutive Sequence

medium
TC: O(N) · SC: O(N)

Put all numbers in a Set. Iterate over set elements (not the raw array to skip duplicates), and ONLY start expanding `x, x+1, x+2...` if `x - 1` is NOT in the set (marking `x` as a sequence head).

Product of Array Except Self

medium
TC: O(N) · SC: O(1)

Compute prefix products left-to-right directly into `res[i]`, then sweep right-to-left maintaining a running scalar `suffix` product and multiply `res[i] *= suffix`.

Time Based Key-Value Store

medium
TC: O(log N) · SC: O(N)

Since `set()` timestamps are strictly increasing per key, appending `(timestamp, value)` keeps the per-key list sorted automatically in O(1). `get()` binary searches the rightmost `t <= timestamp`.

Top K Frequent Elements

medium
TC: O(N) · SC: O(N)

Bucket Sort on Frequency: count occurrences in a hash map, then place elements at index `buckets[freq]` (size `N + 1`). Scan buckets from N down to 1 to harvest top k in strictly linear O(N) time.

Two Sum

easy
TC: O(N) · SC: O(N)

Store `{ value: index }` in a map as you iterate. Before inserting `nums[i]`, check whether `target - nums[i]` is already present.

Valid Anagram

easy
TC: O(N) · SC: O(1)

Two strings are anagrams iff they have equal length and identical character frequency histograms. Increment for `s` and decrement for `t` in one 26-slot array (or map) and verify all counts return to 0.