Search⌘ K
AI Features

Common Hashing Patterns

Explore the two main hashing patterns used in coding interviews: frequency counting and prefix sum with hashing. Understand when to apply each pattern to optimize problem-solving with hash tables, reduce time complexity, and handle common interview challenges involving counts and subarray sums.

Recognizing a hash table as the right data structure is only the first step. The next is knowing which pattern to apply. This lesson covers the two most important hashing patterns in coding interviews: frequency counting and prefix sum with hashing. Together, they cover the majority of hash table-based interview problems.

Interview lens: Both patterns share a common signal: repeated lookup or counting over a sequence. Any problem that requires us to know how many times something appeared, or whether a subarray with a given sum exists, is almost certainly one of these two patterns. Spotting that signal early and reaching for a hash table is the reflex this lesson builds.

Frequency counting

The frequency counting pattern uses a hash table to count how many times each element appears in a collection during a single pass. We map each unique element to its count, incrementing the count each time we encounter the element. Once the pass is complete, the hash table gives us O(1)O(1) access to the frequency of any element without scanning the collection again.

This pattern eliminates the need for nested loops. Without a hash table, counting occurrences of every element requires an O(n2)O(n^2) approach: for each element, scan the entire collection to count matches. We build the frequency counts in O(n)O(n) and answer any frequency query in O(1)O(1) thereafter. ...