BackmediumSliding WindowSalesforceUber

Minimized Target Index Solution

Problem Statement

You are given an integer array nums. Let S be the sum of all elements in nums. Your task is to locate the smallest (0‑based) starting index i such that there exists a contiguous subarray nums[i..j] whose elements add up exactly to S. If several subarrays start at the same i, any of them is acceptable. Return i if such a subarray exists; otherwise return -1.

Input: an array of integers nums. Output: a single integer representing the minimal starting index of a subarray whose sum equals the total sum of the entire array, or -1 if no such subarray exists.

The solution must run in linear time relative to the length of nums and use only linear extra space.

Example 1
Input
[3, -1, 2, 4, -2]
Output
2

Explanation: The total sum S = 3 + (-1) + 2 + 4 + (-2) = 6. Subarrays that sum to 6 are: - nums[0..4] = [3, -1, 2, 4, -2] - nums[2..3] = [2, 4] The smallest starting index among these is 2, so the answer is 2.

Example 2
Input
[5, 5, -5, 5]
Output
0

Explanation: S = 5 + 5 + (-5) + 5 = 10. Subarrays with sum 10 include: - nums[0..1] = [5, 5] - nums[0..3] = [5, 5, -5, 5] Both start at index 0, which is the minimal possible index. Hence the output is 0.

Example 3
Input
[1, -1, 1, -1, 1]
Output
0

Explanation: S = 1 + (-1) + 1 + (-1) + 1 = 1. The subarray nums[0..0] = [1] already equals S, so the minimal starting index is 0.

Constraints

  • 1 <= nums.length <= 100000
  • -10^9 <= nums[i] <= 10^9
  • The algorithm must run in O(n) time and O(n) auxiliary space.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Minimized Target Index — Problem Statement & Solution Guide

Sliding WindowMediumFixed Length Window
TimeO(n)
|
SpaceO(1)

Problem Description

You are given an integer array nums. Let S be the sum of all elements in nums. Your task is to locate the smallest (0‑based) starting index i such that there exists a contiguous subarray nums[i..j] whose elements add up exactly to S. If several subarrays start at the same i, any of them is acceptable. Return i if such a subarray exists; otherwise return -1.

Input: an array of integers nums.

Output: a single integer representing the minimal starting index of a subarray whose sum equals the total sum of the entire array, or -1 if no such subarray exists.

The solution must run in linear time relative to the length of nums and use only linear extra space.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimized Target Index"

medium

WHY DOES IT MATTER?

Sliding‑window is essential for any problem that asks for a contiguous segment meeting a numeric condition because it transforms a potentially quadratic search into a linear scan, preserving order while using constant extra space.

OPTIMIZATION CHALLENGE

The insight is that the target sum S is static and equals the sum of the whole array, so the window never needs to restart; each element is visited at most twice (once when entering, once when leaving), collapsing the search space to O(n).

REAL-WORLD CONNECTION

Think of monitoring a data stream for a period where the total traffic equals the daily total; you slide a time window forward, adding new packets and dropping old ones, until the window’s traffic matches the daily quota.

When coding, initialize left = 0, currentSum = 0, then iterate right from 0 to n‑1 adding nums[right]. Whenever currentSum > S, move left forward subtracting nums[left] until currentSum ≤ S. If currentSum == S, return left immediately – this guarantees the smallest possible start index.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem reduces to finding a contiguous subarray whose sum equals the sum of the entire array S. A naive double‑loop that checks every (i, j) pair runs in O(n²) and quickly exceeds time limits for large n. The optimal paradigm is the sliding‑window (two‑pointer) technique, which exploits the fact that all numbers are processed in a linear order while maintaining a running sum. By expanding the right pointer until the window sum meets or exceeds S and then contracting the left pointer when it exceeds S, we can locate any window whose sum exactly matches S in O(n) time. Because S is fixed, the window never needs to be reset, and each element is added and removed at most once, guaranteeing linear complexity.

Interview Questions on This Problem

Q1How would you modify the sliding‑window solution if the array could contain negative numbers?

With negatives, the window sum is no longer monotonic when expanding, so the classic two‑pointer approach fails. You would need to use a hashmap to store prefix sums and look for a previous prefix where currentPrefix‑previousPrefix = S, achieving O(n) time and O(n) space.

Q2Why does the total sum S being zero simplify the answer, and what edge cases must you still handle?

If S is zero, any subarray that sums to zero is valid, so the smallest start index is 0 as long as there exists at least one zero‑sum subarray (e.g., a single zero element). Edge cases include an all‑zero array (return 0) and arrays where no zero‑sum subarray exists despite total sum being zero (which cannot happen because the whole array sums to zero, so the answer is always 0).

Q3Explain how the sliding‑window technique relates to the “minimum size subarray sum” problem and what key difference exists here.

Both problems maintain a moving window and adjust its size based on the current sum relative to a target. The key difference is that in the minimum‑size problem the target is a lower bound (≥ target) and we shrink to minimize length, whereas here the target is an exact value (== S) and we stop as soon as we hit it, returning the earliest start index.

Examples

Example 1

Input

[3, -1, 2, 4, -2]

Output

2

Explanation: The total sum S = 3 + (-1) + 2 + 4 + (-2) = 6. Subarrays that sum to 6 are: - nums[0..4] = [3, -1, 2, 4, -2] - nums[2..3] = [2, 4] The smallest starting index among these is 2, so the answer is 2.

Example 2

Input

[5, 5, -5, 5]

Output

0

Explanation: S = 5 + 5 + (-5) + 5 = 10. Subarrays with sum 10 include: - nums[0..1] = [5, 5] - nums[0..3] = [5, 5, -5, 5] Both start at index 0, which is the minimal possible index. Hence the output is 0.

Example 3

Input

[1, -1, 1, -1, 1]

Output

0

Explanation: S = 1 + (-1) + 1 + (-1) + 1 = 1. The subarray nums[0..0] = [1] already equals S, so the minimal starting index is 0.

Constraints

  • 1 <= nums.length <= 100000
  • -10^9 <= nums[i] <= 10^9
  • The algorithm must run in O(n) time and O(n) auxiliary space.

Optimal Approach & Strategy

Use a sliding window with two pointers, maintaining the current window sum; expand right, shrink left when sum > S, and return left when sum == S.

Brute Force Approach

Check every possible (i, j) pair, compute the subarray sum, and compare it to S; stop at the first i that works.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
   let prefixSum = new Array(nums.length + 1).fill(0);
   for (let i = 0; i < nums.length; i++) {
     prefixSum[i + 1] = prefixSum[i] + nums[i];
   }
   for (let i = nums.length - 1; i >= 0; i--) {
     if (prefixSum[i + 1] === prefixSum[prefixSum.length - 1]) {
       return i;
     }
   }
   return -1;
}

Asked in Top Tech Interviews

SalesforceUber

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.