[LeetCode] Zero Array Transformation I

3355. Zero Array Transformation I

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] in nums.
  • 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.

A subset of an array is a selection of elements (possibly none) of the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool isZeroArray(vector<int>& nums, vector<vector<int>>& queries) {
vector<int> pre(nums.size() + 1);
for(auto& q : queries) {
pre[q[0]]++;
pre[q[1] + 1]--;
}
for(int i = 0; i < nums.size(); i++) {
if(i) pre[i] += pre[i-1];
nums[i] -= pre[i];
if(nums[i] > 0) return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/17/PS/LeetCode/zero-array-transformation-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.