Magicsheet logo

Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

Medium
25%
Updated 8/1/2025

Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

What is this problem about?

The Maximum Number of Non-Overlapping Subarrays With Sum Equals Target coding problem asks you to find the maximum number of non-overlapping subarrays in a given array nums where each subarray's sum equals a specified target.

Why is this asked in interviews?

Google frequently asks this type of problem to assess a candidate's understanding of prefix sums combined with hash tables for efficient lookups, and greedy approaches for maximizing counts under non-overlapping constraints. It tests the ability to adapt standard sum-equals-target patterns to more complex scenarios.

Algorithmic pattern used

Prefix Sum with Hash Map and Greedy: Maintain a running prefix sum. Store (prefix_sum, index) pairs in a hash map. When iterating through the array, if current_prefix_sum - target is found in the hash map, it means a subarray ending at the current index with sum target exists. To ensure non-overlapping, after finding such a subarray, greedily "reset" your prefix sum and hash map to only consider elements after this found subarray. This greedy choice (taking the earliest possible subarray) maximizes future opportunities.

Example explanation

nums = [1, 1, 1, 1, 1], target = 2.

  1. prefix_sum = 0, map = {0: -1} (dummy entry for sum 0)
  2. i = 0, num = 1: prefix_sum = 1. 1 - 2 = -1 not in map. map = {0: -1, 1: 0}.
  3. i = 1, num = 1: prefix_sum = 2. 2 - 2 = 0 is in map. Found subarray nums[0..1]. Count = 1. Reset: prefix_sum = 0, map = {0: 1} (new dummy starting after current subarray).
  4. i = 2, num = 1: prefix_sum = 1. 1 - 2 = -1 not in map. map = {0: 1, 1: 2}.
  5. i = 3, num = 1: prefix_sum = 2. 2 - 2 = 0 is in map. Found subarray nums[2..3]. Count = 2. Reset: prefix_sum = 0, map = {0: 3}.
  6. i = 4, num = 1: prefix_sum = 1. 1 - 2 = -1 not in map. map = {0: 3, 1: 4}. Result: 2 non-overlapping subarrays.

Common mistakes candidates make

  • Not resetting the prefix sum/hash map: Failing to "reset" after finding a valid subarray will lead to overlapping counts. The problem requires non-overlapping.
  • Incorrect map usage: Ensure the map stores the prefix_sum to index mapping correctly, especially the initial (0, -1) entry.
  • Complexity: Naive nested loops for all subarrays are O(N^2). Prefix sum with a hash map brings it down to O(N).

Interview preparation tip

For the Array Hash Table Greedy Prefix Sum interview pattern, this problem highlights a common strategy: when a greedy choice maximizes future options (like taking the shortest valid subarray to leave maximum remaining elements), it's often optimal. Master prefix sums and hash map applications for range sum queries.

Similar Questions