Zero Array Transformation II - Problem

You are given an integer array nums of length n and a 2D array queries where queries[i] = [li, ri, vali].

Each queries[i] represents the following action on nums: Decrement the value at each index in the range [li, ri] in nums by at most vali. The amount by which each value is decremented can be chosen independently for each index.

A Zero Array is an array with all its elements equal to 0.

Return the minimum possible non-negative value of k, such that after processing the first k queries in sequence, nums becomes a Zero Array. If no such k exists, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3], queries = [[0,2,1],[1,2,1]]
Output: 2
💡 Note: With k=2 queries: first query decrements range [0,2] by up to 1 each, second query decrements range [1,2] by up to 1 each. Total possible decrements: [1,2,2], which covers nums=[2,1,3]
Example 2 — Impossible Case
$ Input: nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]
Output: -1
💡 Note: Even with all queries, max decrements are [1,3,3,2]. Position 0 needs 4 decrements but only gets 1, so impossible
Example 3 — Already Zero
$ Input: nums = [0,0,0], queries = [[0,2,1]]
Output: 0
💡 Note: Array is already all zeros, so k=0 queries needed

Constraints

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

Visualization

Tap to expand
Zero Array Transformation II INPUT nums = [2, 1, 3] 2 idx 0 1 idx 1 3 idx 2 Queries: q[0] = [0, 2, 1] Range [0-2], decrement by 1 q[1] = [1, 2, 1] Range [1-2], decrement by 1 Goal: Find minimum k queries to make all elements = 0 ALGORITHM STEPS 1 Binary Search on k Search range [0, queries.length] 2 Difference Array Track cumulative decrements 3 Check Feasibility Can k queries zero array? 4 Find Minimum k Narrow search to answer Simulation: After k=1 (q[0]): 1 0 2 Not zero! After k=2 (q[0]+q[1]): 0 0 0 OK! Minimum k = 2 FINAL RESULT Original Array: 2 1 3 After k=2 Queries: 0 0 0 Output: k = 2 Both queries needed: q[0] + q[1] zeroes array k=1 insufficient Key Insight: Binary search on k combined with difference array technique allows O(n log m) solution. For each candidate k, check if first k queries can provide enough decrements at every index. TutorialsPoint - Zero Array Transformation II | Binary Search + Difference Array Approach
Asked in
Google 15 Microsoft 12 Amazon 8
3.2K Views
Medium Frequency
~25 min Avg. Time
89 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