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: Find minimum queries needednums = [2,1,3]213queries = [[0,2,1],[1,2,1]]Query 1: [0,2,1]Query 2: [1,2,1]After k=2 queries: max decrements = [1,2,2]1221≥2? No, 2≥1? Yes, 2≥3? No... Need k=2!Answer: minimum k = 2
Understanding the Visualization
1
Input
Array nums and queries with [left, right, value] ranges
2
Process
Apply first k queries to get total possible decrements
3
Check
Verify if decrements ≥ original values for all positions
Key Takeaway
🎯 Key Insight: Binary search on k combined with difference arrays for O(n log m) efficiency
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