Zero Array Transformation I - Problem

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] 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,4], queries = [[1,2],[1,3],[0,1]]
Output: false
💡 Note: Position 3 has value 4 but only 1 query can affect it (query [1,3]), so it cannot be reduced to 0
Example 2 — Possible Transformation
$ Input: nums = [1,0,1], queries = [[0,2]]
Output: true
💡 Note: Single query [0,2] can decrement positions 0 and 2 once each, making array [0,0,0]
Example 3 — Edge Case
$ Input: nums = [0,0,0], queries = []
Output: true
💡 Note: Array is already all zeros, no queries needed

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 105
  • 1 ≤ queries.length ≤ 105
  • queries[i].length == 2
  • 0 ≤ li ≤ ri < nums.length

Visualization

Tap to expand
Zero Array Transformation I INPUT nums array: 2 i=0 1 i=1 3 i=2 4 i=3 queries: [1, 2] [1, 3] [0, 1] Query Ranges: 0 1 2 3 q0 q1 q2 ALGORITHM STEPS 1 Build Difference Array For each query [l,r]: diff[l]++, diff[r+1]-- 2 Process Queries q0: diff[1]++, diff[3]-- q1: diff[1]++, diff[4]-- q2: diff[0]++, diff[2]-- 3 Compute Prefix Sum maxDecrements[i] = prefix sum at index i maxDec: 1 3 2 1 4 Check Condition For all i: nums[i] <= maxDec[i]? FINAL RESULT Compare: nums[i] vs maxDec[i] i nums max OK? 0 2 1 NO 1 1 3 OK 2 3 2 NO 3 4 1 NO nums[0]=2 > maxDec[0]=1 Cannot reduce to zero! Output: false Key Insight: The difference array technique computes the MAXIMUM possible decrements at each index in O(n+q) time. If any nums[i] > maxDecrements[i], it's impossible to reduce that position to zero, so return false. This avoids simulating each query, making it optimal for large inputs. TutorialsPoint - Zero Array Transformation I | Difference Array (Optimal)
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
9.0K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen