Magicsheet logo

Find Two Non-overlapping Sub-arrays Each With Target Sum

Medium
25%
Updated 8/1/2025

Find Two Non-overlapping Sub-arrays Each With Target Sum

1. What is this problem about?

The Find Two Non-overlapping Sub-arrays Each With Target Sum interview question is a complex optimization problem. You are given an integer array and a target value. You need to find two non-overlapping contiguous subarrays that each sum up to target. Among all such pairs of subarrays, you want to find the one that minimizes the total sum of their lengths. If no such pair exists, return -1.

2. Why is this asked in interviews?

Google ask the Find Two Non-overlapping Sub-arrays coding problem to test a candidate's mastery of Sliding Window and Dynamic Programming. It’s a multi-layered problem where you must first identify all valid subarrays and then choose the best two without intersection. It evaluations your ability to maintain "best so far" statistics while scanning an array.

3. Algorithmic pattern used

This problem follows the Sliding Window and Prefix Minimum pattern.

  1. Identify Subarrays: Use a sliding window or a prefix sum map to find all subarrays that sum to target.
  2. DP Array: Maintain an array minLen[i] representing the minimum length of a valid subarray found in the range nums[0...i].
  3. Optimization: As you find a valid subarray nums[left...right] with sum target:
    • Its length is L=rightleft+1L = right - left + 1.
    • Check if a valid subarray exists before left using minLen[left-1].
    • Total length = L+minLen[left1]L + minLen[left-1].
    • Update global minimum total length.
    • Update minLen[right] for future windows.

4. Example explanation

nums = [3, 2, 2, 4, 3], target = 3.

  • Subarrays summing to 3: [3] at index 0 (len 1) and [3] at index 4 (len 1).
  • At index 0: Found [3]. minLen[0] = 1.
  • At index 4: Found [3]. Valid previous minLen before index 4 exists? Yes, at index 0.
  • Total length: 1+1=21 + 1 = 2. Result: 2.

5. Common mistakes candidates make

  • Brute Force: Checking all pairs of subarrays (O(N4)O(N^4)), which will time out.
  • Overlapping: Forgetting to ensure the two subarrays do not share any indices.
  • Missing the Global Minimum: Not correctly updating the minLen array, which should store the minimum length seen anywhere in the prefix, not just ending at ii.

6. Interview preparation tip

When asked for "two non-overlapping" items, think about splitting the array at index ii. Find the "best" item to the left of ii and the "best" item to the right of ii. This Dynamic Programming interview pattern is a standard way to handle non-overlap constraints.

Similar Questions