Find First Index Where Prefix Sum Becomes Non-Positive
Updated
Problem statement
You are given an array of integers inventory representing inventory stock. The prefix sum at index i is the cumulative sum inventory[0] + inventory[1] + ... + inventory[i]. Find the first (smallest) 0-based index i where the prefix sum is non-positive, that is, less than or equal to 0. If no such index exists, return -1.
Function
findFirstNonPositivePrefixSumIndex(inventory: int[]) → int Complete the function findFirstNonPositivePrefixSumIndex in the editor.
findFirstNonPositivePrefixSumIndex has the following parameter:
int[] inventory: an array of integers representing inventory stock
Returns int: the first 0-based index where the prefix sum is less than or equal to 0, or -1 if there is none
Examples
Example 1
inventory = [1, 2]return = -1Prefix sums are [1, 3], no non-positive sum.
Example 2
inventory = [2, -4, 1]return = 1Prefix sums are [2, -2, -1]. The running sum first drops to 0 or below at index 1 (2 + (-4) = -2), so the answer is 1.
Example 3
inventory = [1, 2, 3, -6]return = 3Prefix sums are [1, 3, 6, 0], becomes non-positive at index 3.
Constraints
1 <= n <= 10^5, wherenis the length ofinventory-10^9 <= inventory[i] <= 10^9
More Amazon interview questions
- LRU Cache for Query ResultsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Maximal SquareONSITE INTERVIEW · Seen Nov 2026
- Serialize and Deserialize a Binary TreeONSITE INTERVIEW · Seen Nov 2026
- Course SchedulePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course Schedule IIPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Diagonal Traversal of a Binary TreeONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Spread Through a GridPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Consistent-Hash Packet RouterPHONE SCREEN · Seen Nov 2026
- Count Connected ComponentsPHONE SCREEN · Seen Nov 2026
- Maximize K-Element AND with an Increment BudgetOA · Seen Nov 2026
Similar questions at other companies
- Minimum Positive Starting ValueBooking.com · OA
- Array Interval SumsHeadlands Technologies · OAHeadlands Technologies interview questions
- Minimum AmountBelvedere Trading · OA
- Online No-Intercept Linear RegressionTwo Sigma · OATwo Sigma interview questions
- Range Sum QueriesIntuit · OAIntuit interview questions
- Count Sortable SplitsGoogle · OAGoogle interview questions
- Array Challenge (QR Intern)Akuna Capital · OAAkuna Capital interview questions
- Range Negation UpdatesJP Morgan Chase · OAJP Morgan Chase interview questions
- Threshold AlertsGoldman Sachs · OAGoldman Sachs interview questions
- First Prefix Reaching a Target ScoreVisa · OAVisa interview questions