Zero Array Transformation I Problem
Description
LeetCode Problem 3355.
You are given an integer array nums of length n and a 2D array queries, where queries[i] = [l_i, r_i].
For each queries[i]:
- Select a subset of indices within the range
[l_i, r_i]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.
Example 1:
Input: nums = [1,0,1], queries = [[0,2]]
Output: true
Explanation:
- For i = 0:
- Select the subset of indices as [0, 2] and decrement the values at these indices by 1.
- The array will become [0, 0, 0], which is a Zero Array.
Example 2:
Input: nums = [4,3,2,1], queries = [[1,3],[0,2]]
Output: false
Explanation:
- For i = 0:
- Select the subset of indices as [1, 2, 3] and decrement the values at these indices by 1.
- The array will become [4, 2, 1, 0].
- For i = 1:
- Select the subset of indices as [0, 1, 2] and decrement the values at these indices by 1.
- The array will become [3, 1, 0, 0], which is not a Zero Array.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^51 <= queries.length <= 10^5queries[i].length == 20 <= l_i <= r_i < nums.length
Solution
Approach: Difference Array
We can use a difference array to solve this problem.
Define an array d of length n + 1, with all initial values set to 0. For each query [l, r], we add 1 to d[l] and subtract 1 from d[r + 1].
Then we traverse the array d within the range [0, n - 1], accumulating the prefix sum s. If nums[i] > s, it means nums cannot be converted to a zero array, so we return false.
After traversing, return true.
The time complexity is O(n + m), and the space complexity is O(n), where n and m are the lengths of the array nums and the number of queries, respectively.
class Solution:
def isZeroArray(self, nums: List[int], queries: List[List[int]]) -> bool:
d = [0] * (len(nums) + 1)
for l, r in queries:
d[l] += 1
d[r + 1] -= 1
s = 0
for x, y in zip(nums, d):
s += y
if x > s:
return False
return True