const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Patterns

Array & Hashing Patterns for LeetCode Interviews

Master the core array and hash map patterns that unlock O(n) solutions to the most common coding interview problems

9 min read|

Arrays and hash maps are the foundation of every interview

The patterns that make O(n) solutions click

Arrays and Hash Maps Are the Most-Tested Category in Coding Interviews

If you could only study one topic before a coding interview, it should be arrays and hash maps. These two data structures appear in more interview questions than any other category — across FAANG, startups, and everything in between. Understanding leetcode array hashing patterns is the single highest-leverage investment in your interview prep.

The reason is simple: arrays are the most fundamental data structure in programming, and hash maps are the tool that makes brute-force solutions fast. Together, they form the backbone of dozens of classic problems — from Two Sum to Group Anagrams to Top K Frequent Elements.

This guide covers the four core hash map patterns you need to recognize, walks through the classic array problems interviewers love, and shows you how to avoid the common mistakes that trip up candidates. By the end, you will have a mental toolkit for solving array and hashing problems confidently in O(n) time.

Why Arrays and Hash Maps Are Foundational

Arrays and hash maps are foundational because they are building blocks for nearly every other pattern in your interview toolkit. Two pointers operate on arrays. Sliding window operates on arrays. Even tree and graph problems often start by parsing input into arrays or adjacency lists backed by hash maps.

From a frequency perspective, array and hash table interview questions dominate the easy and medium tiers on LeetCode. A study of the most commonly asked questions at top tech companies shows that over 40% involve arrays, strings, or hash maps as the primary data structure. If you skip this category, you are leaving the most probable questions unpracticed.

Hash maps in particular are the secret weapon that separates linear solutions from quadratic ones. Any time you find yourself writing a nested loop to search for a complement, a duplicate, or a group membership, a hash map can almost certainly replace the inner loop with an O(1) lookup.

  • Arrays appear in over 40% of coding interview questions across all difficulty levels
  • Hash maps provide O(1) average lookup, insert, and delete — the key to eliminating nested loops
  • Most other patterns (two pointers, sliding window, prefix sums) build directly on array fundamentals
  • Interviewers expect fluency with hash maps as a baseline — it is not an advanced topic

Core Hash Map Patterns for Coding Interviews

There are four hash map patterns that cover the vast majority of array hashing problems you will encounter. Once you internalize these, you will recognize the right approach within the first 30 seconds of reading a new problem.

The frequency counting pattern uses a hash map to count occurrences of each element. This is the foundation for problems like Valid Anagram (#242), where you compare character frequencies, and Top K Frequent Elements (#347), where you rank elements by count. The template is always the same: iterate once to build the frequency map, then iterate the map to extract your answer.

The two-sum pattern stores elements you have already seen in a hash map, keyed by the complement you need. For each new element, you check whether its complement exists in the map. This turns the brute-force O(n²) double loop into a single-pass O(n) solution. The same idea generalizes to any problem where you need to find pairs satisfying a condition.

The grouping-by-key pattern uses a hash map where the key represents some canonical form and the value is a list of items sharing that form. Group Anagrams (#49) is the classic example: sort each word to get a canonical key, and group words with the same key. This pattern also appears in grouping intervals, grouping by remainder, and bucketing by frequency.

The prefix sum pattern precomputes cumulative sums in an array, then uses a hash map to find subarrays with a target sum in O(n) time. Subarray Sum Equals K (#560) is the definitive example. You store prefix sums as keys and their counts as values, checking whether the current prefix sum minus the target has been seen before.

  • Frequency counting: count occurrences, compare distributions, find modes
  • Two-sum / complement lookup: find pairs or complements in a single pass
  • Grouping by key: bucket items by a canonical form (sorted string, modulus, etc.)
  • Prefix sums with hash map: find subarrays with target sum in O(n)
💡

Pro Tip

When you need O(1) lookup, reach for a hash map — it turns brute-force O(n²) into elegant O(n).

Classic Array Problems Every Candidate Should Know

Two Sum (#1) is the most-asked interview question in history for a reason. It tests whether you can trade space for time by using a hash map. The brute-force approach checks every pair in O(n²). The optimal approach iterates once: for each element, check if its complement exists in the map, and if not, store the element for future lookups. If you can explain this trade-off clearly, you have demonstrated the core hash map insight.

Contains Duplicate (#217) is another foundational problem. Insert each element into a hash set as you iterate. If the element is already in the set, return true. This is O(n) time and O(n) space — a pattern you will use repeatedly for duplicate detection, cycle detection, and membership checking.

Group Anagrams (#49) combines hashing with the grouping-by-key pattern. Sort each string to produce a canonical key, then group all strings sharing the same key. The time complexity is O(n * k log k) where k is the maximum string length. An alternative uses a character frequency tuple as the key to avoid sorting, bringing it closer to O(n * k).

Top K Frequent Elements (#347) chains two patterns: frequency counting followed by a selection step. Build a frequency map, then extract the top k elements. You can use a heap for O(n log k) or bucket sort for O(n). This problem tests whether you can compose patterns fluently.

  • Two Sum (#1): hash map complement lookup — O(n) time, O(n) space
  • Contains Duplicate (#217): hash set membership — O(n) time, O(n) space
  • Group Anagrams (#49): grouping by sorted key — O(n * k log k)
  • Top K Frequent Elements (#347): frequency map + heap or bucket sort — O(n log k) or O(n)

Sliding Window and Advanced Array Techniques

While pure hash map problems dominate the easy tier, medium and hard array problems often combine hashing with other techniques. The sliding window pattern is the most important of these combinations. When a problem asks for a contiguous subarray or substring satisfying some condition, sliding window is usually the right approach.

Maximum Subarray (#53) uses Kadane's algorithm — a specialized sliding window that tracks the maximum sum ending at each position. The key insight is that you either extend the current subarray or start fresh, whichever gives a larger sum. This runs in O(n) time and O(1) space, making it one of the most efficient algorithms you will learn.

Product of Array Except Self (#238) is a brilliant example of the prefix and suffix technique. You cannot use division (the problem explicitly forbids it), so instead you compute prefix products from the left and suffix products from the right, then multiply them. This achieves O(n) time and can be done in O(1) extra space by reusing the output array.

These problems test your ability to think beyond brute force. Interviewers want to see you recognize that a nested loop is unnecessary and propose an array traversal technique that keeps the solution linear.

  1. 1Read the problem constraints: does it ask for a contiguous subarray or substring?
  2. 2If yes, consider sliding window — expand the right pointer, shrink the left when invalid
  3. 3If the problem involves cumulative values, consider prefix sums or prefix products
  4. 4If the problem asks for pairs or complements, reach for a hash map
  5. 5Combine patterns when needed — many medium problems require two techniques working together
ℹ️

Did You Know

Arrays and hash maps are the most-tested category in coding interviews across all companies.

Common Mistakes with Array and Hash Map Problems

The most frequent mistake is forgetting edge cases. Empty arrays, single-element arrays, arrays with all identical elements, and arrays with negative numbers all require special handling. Interviewers deliberately include these in test cases to see whether your solution is robust. Always ask yourself: what happens when the input is empty or has one element?

Another common trap is assuming hash map order. In many languages, hash maps do not preserve insertion order. If your solution depends on iterating keys in a specific sequence, you need a different data structure — an ordered map, a sorted array of keys, or an explicit index. Python's dict preserves insertion order as of 3.7, but JavaScript's Map and Java's HashMap do not guarantee it in all cases.

Hash collision awareness matters too. While collisions are rare with good hash functions, using mutable objects as keys (like lists in Python) will cause errors or unexpected behavior. Always use immutable, hashable key types — strings, tuples, or frozen sets.

Finally, many candidates default to sorting when a hash map would be faster. Sorting costs O(n log n); a hash map pass costs O(n). Unless the problem specifically requires sorted output, check whether a hash map gives you the information you need without paying the sorting overhead.

  • Test with empty arrays, single elements, all-duplicate arrays, and negative numbers
  • Do not rely on hash map iteration order unless your language guarantees it
  • Use immutable types as hash map keys — never use mutable lists or arrays
  • Prefer hash map O(n) solutions over sorting O(n log n) unless sorting is explicitly needed

Practice Strategy — Drilling Array and Hashing Patterns with YeetCode

The fastest way to build fluency with array and hashing patterns is deliberate, spaced practice. Solve a problem, then revisit it the next day without looking at your notes. If you can reconstruct the approach from scratch, move on. If you struggle, reset and try again in two days.

YeetCode's flashcard system is built for exactly this workflow. Each card presents a problem and asks you to recall the pattern, the key insight, and the time complexity before revealing the answer. The spaced repetition algorithm adjusts the interval based on your confidence — problems you know well appear less often, while shaky ones come back quickly.

Start with the four core hash map patterns in this article, then branch into two pointers, sliding window, and other categories. Arrays and hash maps are the foundation — once you are confident here, every other pattern becomes easier because you already know how to think about lookups, counting, and grouping.

Aim for 2-3 problems per day during your study period. Consistency beats volume. Twenty minutes of focused daily practice builds more durable recall than a single weekend marathon.

  • Master the four hash map patterns first: frequency counting, two-sum, grouping, prefix sums
  • Use spaced repetition to review solved problems at increasing intervals
  • Solve each problem twice: once with guidance, once from scratch the next day
  • Track your confidence on each pattern to identify weak spots early
  • Aim for 2-3 focused problems per day rather than marathon sessions
⚠️

Watch Out

Watch for hash map collision edge cases and remember that hash map order is not guaranteed.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now