Zero Array Transformation IV - Problem

You are given an integer array nums of length n and a 2D array queries, where queries[i] = [l_i, r_i, val_i].

Each queries[i] represents the following action on nums:

  • Select a subset of indices in the range [l_i, r_i] from nums.
  • Decrement the value at each selected index by exactly val_i.

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],[1,1,3]]
Output: 2
💡 Note: After applying first 2 queries: query [0,2,1] reduces range [0,2] by 1, query [1,2,1] reduces range [1,2] by 1. Total reductions: [1,2,2] which can make [2,1,3] → [0,0,0]
Example 2 — Impossible Case
$ Input: nums = [5,2,4], queries = [[0,1,1],[1,2,1]]
Output: -1
💡 Note: Even using all queries, maximum reductions are [1,2,1] which cannot reduce [5,2,4] to zero since 1 < 5
Example 3 — Zero Queries Needed
$ 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] ≤ 109
  • 1 ≤ queries.length ≤ 105
  • queries[i].length = 3
  • 0 ≤ li ≤ ri < nums.length
  • 1 ≤ vali ≤ 109

Visualization

Tap to expand
Zero Array Transformation IV INPUT nums array: 2 1 3 [0] [1] [2] queries: q[0]: [0,2,1] range[0-2], val=1 q[1]: [1,2,1] range[1-2], val=1 q[2]: [1,1,3] range[1-1], val=3 Goal: Make all zeros Find min k queries to achieve zero array ALGORITHM STEPS 1 Process Query 0 [0,2,1]: Select all indices [2,1,3] - [1,1,1] = [1,0,2] 2 Process Query 1 [1,2,1]: Select idx 1,2 [1,0,2] - [0,0,1] = [1,0,1] 3 Greedy Selection q0: idx 0,2 (val 1 each) q1: idx 1,2 (val 1 each) 4 Check Zero Array After k=2 queries: [0,0,0] -- OK! Optimized Diff Array idx[0]: 2-1-0 = 1, need 1 idx[1]: 1-1-1 = -1, need 0 idx[2]: 3-1-1 = 1, need 1 All covered with k=2! FINAL RESULT Transformation Steps: Initial: 2 1 3 After q[0]: 1 0 2 After q[1]: 0 0 0 Output: k = 2 Zero Array Achieved! Only 2 queries needed Query 2 not required [OK] Key Insight: The greedy approach with difference array efficiently tracks cumulative decrements across ranges. For each query [l,r,val], we can selectively apply val to indices in range. Binary search on k finds minimum queries. Here, q[0] covers idx 0,2 and q[1] covers idx 1,2 to reach all zeros. TutorialsPoint - Zero Array Transformation IV | Optimized Greedy with Difference Array
Asked in
Google 35 Microsoft 28 Amazon 22
23.4K Views
Medium Frequency
~25 min Avg. Time
856 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