Prefix sums and hashing

Master the Prefix Sum + Hashing pattern to solve complex contiguous subarray problems in O(N) time. Learn how to handle target sums, divisibility, and binary arrays.

intermediate11 min readBy CureBugs EditorialUpdated 5 Nov 2026

Subarray problems are a staple in software engineering interviews at top tech companies in India, from FAANG to fast-growing startups like Swiggy and Zomato. While finding a contiguous subarray that meets a specific condition can often be solved with nested loops in O(N^2) time, interviewers will expect an O(N) solution. The Prefix Sum + Hashing pattern is a silver bullet for these scenarios, especially when negative numbers rule out other popular techniques like the Sliding Window.

When to use this pattern

Recognizing when to apply Prefix Sums with Hashing is half the battle. Look for these specific signals in the problem statement:

  1. "Contiguous subarray": The problem explicitly asks for subarrays, not subsequences (where elements can be non-adjacent).
  2. "Sum equals exactly K": You need to find subarrays that sum to a specific target, or a multiple of a target (divisible by K).
  3. Binary arrays: Problems asking for "equal number of 0s and 1s" can be mathematically transformed into sum problems.
  4. Negative numbers are present: This is the ultimate giveaway. If the array contains negative numbers, the Sliding Window pattern fails because the window sum is no longer strictly increasing or decreasing.
  5. Constraints: The array size (N) is typically between 10^4 and 10^5. An O(N^2) approach would take roughly 10^8 to 10^10 operations, resulting in a Time Limit Exceeded (TLE) error. You need an O(N) approach that runs in milliseconds.

The core idea

To understand this pattern, we first need to define a Prefix Sum. A prefix sum at index i is the sum of all elements from the start of the array up to i.

Let P[i] be the prefix sum up to index i. The sum of a subarray from index i to index j (inclusive) can be calculated in O(1) time using the formula: Sum(i, j) = P[j] - P[i-1]

If we are looking for a subarray that sums to a specific target K, we can set up the equation: P[j] - P[i-1] = K

Rearranging this equation gives us the secret to the O(N) algorithm: P[i-1] = P[j] - K

What does this mean? As we iterate through the array from left to right, we calculate the current prefix sum P[j]. If we have previously seen a prefix sum equal to P[j] - K, it means there is a valid subarray ending at our current index j! To check if we've seen P[j] - K before in O(1) time, we store all our past prefix sums in a Hash Map.

Template

Here is the standard template for the Prefix Sum + Hashing pattern. Notice the crucial base case initialization in the hash map.

def subarray_pattern(nums, k):
    # Map stores {prefix_sum: frequency_or_index}
    # Base case: A prefix sum of 0 has been seen exactly once (before the array starts)
    hash_map = {0: 1} 
    curr_sum = 0
    result = 0
    
    for i in range(len(nums)):
        curr_sum += nums[i]
        
        # Check if the required past prefix sum exists
        target = curr_sum - k
        if target in hash_map:
            result += hash_map[target]
            
        # Add the current prefix sum to the map
        hash_map[curr_sum] = hash_map.get(curr_sum, 0) + 1
        
    return result

Worked examples

Let's apply this template to three classic interview problems that frequently appear in technical rounds.

Example 1: Subarray Sum Equals K

Problem: Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.

Approach: This is the most direct application of our template. We maintain a running curr_sum. At each step, we check if curr_sum - k exists in our hash map. If it does, we add its frequency to our answer. Finally, we record curr_sum in the hash map.

Complexity:

  • Time Complexity: O(N) because we iterate through the array exactly once, and hash map lookups take O(1) time on average.
  • Space Complexity: O(N) in the worst case, where all prefix sums are distinct and we store N entries in the hash map.
def subarraySum(nums, k):
    counts = {0: 1}
    curr_sum = 0
    ans = 0
    for x in nums:
        curr_sum += x
        target = curr_sum - k
        if target in counts:
            ans += counts[target]
        counts[curr_sum] = counts.get(curr_sum, 0) + 1
    return ans

Example 2: Contiguous Array (Equal 0s and 1s)

Problem: Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0s and 1s.

Approach: This problem doesn't look like a sum problem at first glance. The trick is to transform it: treat every 0 as -1. Now, the problem becomes "find the longest contiguous subarray with a sum of 0".

Since we want the maximum length (not the total count), our hash map should store the first index where we saw a particular prefix sum, rather than its frequency. The length of the subarray will be current_index - first_seen_index. Our base case also changes slightly: a sum of 0 is conceptually seen at index -1 before the array begins.

Complexity:

  • Time Complexity: O(N)
  • Space Complexity: O(N)
def findMaxLength(nums):
    # Map stores {prefix_sum: first_seen_index}
    first_seen = {0: -1}
    curr_sum = 0
    max_len = 0
    
    for i, x in enumerate(nums):
        # Treat 0 as -1
        curr_sum += 1 if x == 1 else -1
        
        if curr_sum in first_seen:
            # Calculate length and update max_len
            max_len = max(max_len, i - first_seen[curr_sum])
        else:
            # Only store the FIRST time we see a sum to maximize length
            first_seen[curr_sum] = i
            
    return max_len

Example 3: Subarray Sums Divisible by K

Problem: Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.

Approach: This requires a bit of modular arithmetic. If a subarray sum S[i..j] is divisible by K, it means (P[j] - P[i-1]) % K == 0. Mathematically, this implies that P[j] % K == P[i-1] % K.

So, instead of storing the actual prefix sums in our hash map, we store the remainders of the prefix sums when divided by K. If we encounter a remainder that we've seen before, it means the subarray between the previous occurrence and the current index has a sum divisible by K.

Complexity:

  • Time Complexity: O(N)
  • Space Complexity: O(K) because there are only K possible remainders (0 to K-1).
def subarraysDivByK(nums, k):
    counts = {0: 1}
    curr_sum = 0
    ans = 0
    
    for x in nums:
        curr_sum += x
        # In Python, modulo handles negative numbers correctly (e.g., -5 % 3 == 1)
        rem = curr_sum % k
        
        if rem in counts:
            ans += counts[rem]
            
        counts[rem] = counts.get(rem, 0) + 1
        
    return ans

Variations and pitfalls

While the template is robust, there are a few nuances that can trip you up in a high-pressure interview environment:

  1. The Negative Modulo Trap: As highlighted in Example 3, languages like C++, Java, and JavaScript handle modulo operations on negative numbers differently than Python. In C++, -5 % 3 evaluates to -2, but mathematically, the remainder should be positive (1). Always adjust negative remainders using (rem % k + k) % k or a simple if (rem < 0) rem += k;.
  2. Frequency vs. Index: Pay close attention to what the problem is asking. If it asks for the number of subarrays, your hash map should store frequencies (map[sum]++). If it asks for the longest subarray, your hash map should store the first index where the sum was seen (map[sum] = i).
  3. Space Complexity Constraints: Unlike some Dynamic Programming problems where you can optimize space by only keeping the last few variables, Prefix Sum + Hashing inherently requires O(N) space (or O(K) for divisibility) because you need to remember the entire history of prefix sums. If an interviewer asks for an O(1) space solution, you will likely have to compromise on time complexity and revert to O(N^2), unless the array is strictly non-negative, in which case you should pivot to the Sliding Window pattern.

Practice checklist

To truly master this pattern, you need to build muscle memory. Start by implementing the three examples above from scratch, then challenge yourself with variations. Reviewing related patterns like Sliding Window and Two Pointers will also help you quickly identify which tool to use during an interview.

Mock interview

Solve one like this with an interviewer watching

Getting the answer alone is half the round. The other half is clarifying the problem, explaining your approach, coding while you talk and handling the follow-up. Try it on a problem you haven't seen.

  • A timed problem in a real editor, judged on hidden tests
  • Hints if you ask, and they count against you like they would in the room
  • A scored report that quotes your answers and says what to fix
Start a mock coding round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
DSA patterns•intermediate

The two pointers pattern

15 min read
DSA patterns•intermediate

The sliding window pattern

11 min read
DSA patterns•intermediate

The monotonic stack pattern

12 min read
DSA patterns•intermediate

Interval problems: merging and scheduling

14 min read
Prefix sums and hashing · CureBugs