Problem
You are given an integer array nums of length n and a 2D array queries, where queries[i] = [li, ri].
For each queries[i]:
- Select a subset of indices within the range
[li, ri]innums. - Decrement the values at the selected indices by 1.
A Zero Array is an array where all elements are equal to 0.
Return true if it is possible to transform nums into a Zero Array after processing all the queries sequentially, otherwise return false.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= nums.length <= 1050 <= nums[i] <= 1051 <= queries.length <= 105queries[i].length == 20 <= li <= ri < nums.length
Similar Problem
Zero Array Transformation 2 Zero Array Transformation 3
Solution
Method 1 - Efficient Range Decrements Using Delta Array
The challenge is to determine if we can turn all elements of nums into 0 using the given queries. Directly applying each query to nums would be inefficient (O(n × q)). Instead, we leverage a delta array to efficiently manage range operations:
- Use the delta array to record where range decrements start and stop.
- Calculate the cumulative effect of delta values on
numsin a single pass, allowing us to apply all queries efficiently. - If at any index, the total decrements (
nums[i] + cumulative changes) are insufficient to makenums[i] <= 0, returnFalse.
Approach
Delta Array for Efficient Range Updates:
- For each query
[start, end], updatedelta[start] -= 1(start a decrement) anddelta[end + 1] += 1(stop the decrement afterend).
- For each query
Cumulative Changes:
- Use a cumulative sum (
total_possible_change) to apply all range effects while iterating throughnums. - Check if
nums[i] + total_possible_change > 0at any index. If true, returnFalse.
- Use a cumulative sum (
Final Verification:
- If we process all indices without failure, return
True.
- If we process all indices without failure, return
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n + q)- Processing queries:
O(q)forqqueries to populate thedeltaarray. - Validating array:
O(n)iterating throughnumsto apply the total possible changes. - Total:
O(n + q).
- Processing queries:
- 🧺 Space complexity:
O(n)for usingdeltaarray
Dry Run
- Initial Delta Array:
delta = [0, 0, 0].
- Processing Query [0, 2]:
delta[0] -= 1 → delta = [-1, 0, 0].delta[3] cannot be updated as it is out of bounds.
- Applying Delta:
- At
i = 0:total_possible_change = -1,nums[0] = 1 + (-1) = 0. - At
i = 1:total_possible_change = -1,nums[1] = 0 + (-1) = -1(valid since it’s ≤ 0). - At
i = 2:total_possible_change = -1,nums[2] = 1 + (-1) = 0.
- At
- Final Check:
nums = [0, 0, 0] → Return True.