Code Logo

Minimum Prefix Index Reaching Target

Published at05 Jan 2026
Easy 3 views
Like17

This problem is about watching the running total of an array as you move from left to right. At each index, you add the current number to the sum of everything before it. The goal is to find the first index where that prefix sum becomes at least the target.

What matters is the earliest moment the running total reaches the goal. Even if later positions also satisfy the condition, they do not matter once an earlier prefix already works.

For example, if nums = [4,4] and target = 10, the running totals are [4,8], so the answer is -1 because the target is never reached. If nums = [1,1,1,1] and target = 3, the running totals are [1,2,3,4], so index 2 is the first position where the total is at least 3.

So the task is to compute prefix sums in order and return the smallest index whose running total is >= target, or -1 if that never happens.

Example Input & Output

Example 1
Input
nums = [1, 1, 1, 1], target = 3
Output
2
Explanation

Running totals are [1, 2, 3, 4]; index 2 is the first position with total >= 3.

Example 2
Input
nums = [2, 3, 1, 5], target = 5
Output
1
Explanation

Running totals are [2, 5, 6, 11]; the first time we reach at least 5 is at index 1.

Example 3
Input
nums = [4, 4], target = 10
Output
-1
Explanation

Running totals are [4, 8]; the target is never reached.

Algorithm Flow

Recommendation Algorithm Flow for Minimum Prefix Index Reaching Target
Recommendation Algorithm Flow for Minimum Prefix Index Reaching Target

Solution Approach

The simplest and best approach here is a single left-to-right pass with a running sum. Since we need the first index where the prefix total reaches the target, the moment that condition becomes true, we can stop immediately.

We start with a variable to hold the current prefix sum:

let total = 0;

Then we scan the array in order:

for (let i = 0; i < nums.length; i++) {
  total += nums[i];

  if (total >= target) {
    return i;
  }
}

Each step updates the running total for the prefix ending at index i. As soon as total >= target, we know i is the minimum valid index, because we are scanning from left to right.

If the loop finishes without reaching the target, then no prefix works, so we return:

return -1;

This runs in O(n) time and uses O(1) extra space.

Best Answers

java
class Solution{public int min_prefix_index(Object n,Object t){int[]a=(int[])n;int tg=(int)t;int s=0;for(int i=0;i<a.length;i++){s+=a[i];if(s>=tg)return i;}return -1;}}