BudiBadu Logo

Minimum Prefix Index Reaching Target

Array Easy 1 views
Like17

You’re given a list of positive integers and a target value. In Minimum Prefix Index Reaching Target, your task is to find the Smallest Index at which the running total (prefix sum) meets or exceeds that target. If you reach the end of the list and the total is still below the target, return -1.

The "secret sauce" here is Cumulative Sum Monitoring. Because all values are positive, your running total increases steadily with every step. You walk through the list from left to right, adding each number to a counter. The moment that counter hits the target, you capture the current index and return it. This approach is lightning fast (O(n) time and O(1) space) and incredibly reliable. It’s a fundamental building block for range-based calculations, allowing you to find the exact "tipping point" in a sequence where a requirement is finally satisfied. It turns a simple loop into a precise measurement tool for sequence limits!

Examples

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 - Budibadu
Recommendation Algorithm Flow for Minimum Prefix Index Reaching Target - Budibadu

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;}}