Find the smallest prefix of range-decrement operations needed to make an array all zeros, or report that it is impossible.
Problem
You are given an integer array nums and a list of operations. Each operation is a range update of the form [l, r, val], meaning you may apply it to decrease every element in nums[l...r] by val once.
Your task is to determine the minimum number of operations from the start of the list that must be applied so that every element of the array becomes exactly 0. If it is impossible to reach an all-zero array using all operations, return -1.
The key challenge is to decide, for a given prefix of operations, whether that prefix is sufficient to reduce every position to zero without making any value negative in a way that violates the target.
Input Format
- An integer array
nums - An array of operations, where each operation is
[l, r, val]
Output Format
- Return the minimum number of operations from the front of the list required to transform
numsinto an all-zero array. - Return
-1if no prefix of the operations works.
Constraints
1 <= nums.length <= $10^{5}$0 <= nums[i] <= $10^{9}$1 <= operations.length <= $10^{5}$0 <= l <= r < nums.length1 <= val <= $10^{9}$
Notes
- Operations are considered in the given order.
- You only need to determine whether a prefix of operations is enough; you do not need to find the exact subset of operations.
- Efficient solutions typically test prefixes with a range-accumulation data structure.
Example 1
Input
nums = [2, 1, 3] operations = [[0, 2, 1], [0, 1, 1], [2, 2, 2]]
Output
3
Explanation
After the first three operations, the total decrements are:
- index 0: 1 + 1 = 2
- index 1: 1 + 1 = 2
- index 2: 1 + 2 = 3
So the array becomes
[0, 0, 0]. No smaller prefix works.
Example 2
Input
nums = [1, 2] operations = [[0, 0, 1], [1, 1, 1]]
Output
-1
Explanation
Even after applying all operations, index 1 can only be reduced by 1, but it needs 2. So it is impossible.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.