Zero Array Transformation III

Medium Heaps Advanced

Zero Array Transformation III is a medium heaps problem solved with the advanced pattern. The best approach, optimal (greedy with a max-heap and a difference array), runs in O(n + m log m) time and O(n + m) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from greedy with a linear scan up.

Problem

You are given an integer array nums of length n and a list of queries, where queries[i] = [l_i, r_i] describes the index range from l_i to r_i, both ends included.

When a query is applied, you may lower each element whose index lies in its range by at most one. The choice is made separately for every element: some elements of the range can go down by one while others stay as they are.

You may throw away some of the queries and apply all of the remaining ones. Return the largest number of queries you can throw away so that the remaining queries can still turn every element of nums into 0. If even applying every query cannot make nums all zeros, return -1.

Examples

Example 1

Input
nums = [1,0,2,1], queries = [[0,2],[2,3],[1,2],[0,0]]
Output
2
Why
Keep [0,2] and [2,3]. Index 0 gets one decrement from [0,2], index 2 gets one from each of them, index 3 gets one from [2,3], and index 1 needs nothing (a query may skip any element). So [1,2] and [0,0] can both be removed. No single query covers both index 0 and index 3, so at least two must stay.

Example 2

Input
nums = [3], queries = [[0,0],[0,0],[0,0],[0,0]]
Output
1
Why
Each query lowers index 0 by at most one, so three of the four are needed to bring 3 down to 0. One can be removed.

Example 3

Input
nums = [1,2,1], queries = [[0,1],[2,2]]
Output
-1
Why
Index 1 needs two decrements, but only the query [0,1] covers it. Even with every query kept, nums cannot become all zeros.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^5
  • 1 <= queries.length <= 10^5
  • queries[i].length == 2
  • 0 <= l_i <= r_i < nums.length

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 27 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Greedy with a linear scanO(n + m^2)O(n + m)
Optimal (greedy with a max-heap and a difference array)O(n + m log m)O(n + m)

1Greedy with a linear scan

TimeO(n + m^2)Each scan costs O(m) and ends either in one more chosen query (at most m times) or in returning -1 (once). The walk over the indexes adds O(n).
SpaceO(n + m)The chosen flags take m booleans and the difference array n + 1 integers.

Each query decrements every element of its range by at most one, and it may skip elements. So the kept queries can clear nums exactly when every index i lies inside at least nums[i] kept queries. Keep as few as possible by walking from left to right. At index i, count the kept queries that still cover i. While that count is below nums[i], we are forced to keep one more query that covers i. All such candidates start at or before i, so for the indexes after i the best one is simply the one whose right end is largest: it covers every later index any other candidate covers. Find it by scanning all queries. A difference array (end[r + 1]++) tells us when a kept query stops covering.

  1. Mark every query as not chosen. Let end be an array of n + 1 zeros, and active = used = 0.
  2. For each index i: subtract end[i] from active (kept queries that ended at i - 1).
  3. While active < nums[i]: scan all queries for an unchosen one with l <= i <= r and the largest r. If none exists, return -1. Otherwise choose it: active++, used++, end[r + 1]++.
  4. Return queries.length - used.
class Solution {
    public int maxRemoval(int[] nums, int[][] queries) {
        int n = nums.length, m = queries.length;
        boolean[] chosen = new boolean[m];
        int[] end = new int[n + 1];
        int active = 0, used = 0;
        for (int i = 0; i < n; i++) {
            active -= end[i];
            while (active < nums[i]) {
                int best = -1;
                for (int q = 0; q < m; q++) {
                    if (!chosen[q] && queries[q][0] <= i && queries[q][1] >= i
                            && (best < 0 || queries[q][1] > queries[best][1])) best = q;
                }
                if (best < 0) return -1;
                chosen[best] = true;
                active++;
                used++;
                end[queries[best][1] + 1]++;
            }
        }
        return m - used;
    }
}

2Optimal (greedy with a max-heap and a difference array)

TimeO(n + m log m)Sorting costs O(m log m). Every query is pushed once and popped at most once, each in O(log m). The walk over the indexes is O(n).
SpaceO(n + m)The heap holds at most m right ends and the difference array has n + 1 slots.

Same greedy, without the full scan. Sort the queries by their left end and feed them, in that order, into a max-heap of right ends as soon as the walk reaches their left end. The heap then holds exactly the unchosen queries that start at or before i. While index i is short, look at the top of the heap: if its right end is at least i, keep that query (it reaches farthest, so it is the best choice); if even the top ends before i, every query in the heap does, and nothing can cover i any more, so return -1. Why is the greedy safe? Any valid choice must keep some extra query covering i at this point; swapping it for the farthest-reaching candidate still covers i and covers at least as much of the future, so the count never gets worse.

  1. Sort queries by left end. Create a max-heap of right ends, a difference array end of size n + 1, and set active = used = 0, j = 0.
  2. For each index i: active -= end[i]; push the right end of every query with l <= i (advance j).
  3. While active < nums[i] and the heap top is at least i: pop r, then active++, used++, end[r + 1]++.
  4. If active is still below nums[i], return -1.
  5. Return queries.length - used.
class Solution {
    public int maxRemoval(int[] nums, int[][] queries) {
        int n = nums.length, m = queries.length;
        Arrays.sort(queries, (a, b) -> a[0] - b[0]);
        PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> b - a);
        int[] end = new int[n + 1];
        int active = 0, used = 0, j = 0;
        for (int i = 0; i < n; i++) {
            active -= end[i];
            while (j < m && queries[j][0] <= i) heap.offer(queries[j++][1]);
            while (active < nums[i] && !heap.isEmpty() && heap.peek() >= i) {
                int r = heap.poll();
                active++;
                used++;
                end[r + 1]++;
            }
            if (active < nums[i]) return -1;
        }
        return m - used;
    }
}

Edge cases to test

  • Every value is already 0: no query is needed, so the answer is queries.length
  • Even with all queries some index gets too few covering queries: return -1
  • One index needs many decrements, so many identical queries must stay
  • Several queries cover an index; the one that reaches farthest to the right is the best one to keep
  • A query that starts before the current index can still be chosen late: it may skip the indexes it does not need
  • Queries are not given in order of their left ends, so they must be sorted (or bucketed) first

Hints

Hint 1

Each kept query gives each index in its range at most one decrement, so nums can be cleared exactly when every index i is covered by at least nums[i] kept queries.

Hint 2

Walk the indexes from left to right. If index i is covered by too few kept queries, you must keep one more query that covers i. Which one helps the future the most?

Hint 3

Among the unused queries that start at or before i and still reach i, the one with the largest right end covers every later index the others cover. Keep a max-heap of right ends, and a difference array to know when a kept query stops covering.

FAQ

What is the best time complexity for Zero Array Transformation III?

Optimal (greedy with a max-heap and a difference array) runs in O(n + m log m) time and O(n + m) extra space. Sorting costs O(m log m). Every query is pushed once and popped at most once, each in O(log m). The walk over the indexes is O(n).

Which pattern does Zero Array Transformation III use?

It is a heaps problem that uses the advanced pattern. Other problems with the same pattern: Find K Pairs with Smallest Sums, Find Median from Data Stream, Trapping Rain Water II.

Is there a brute force solution for Zero Array Transformation III?

Yes. Greedy with a linear scan takes O(n + m^2) time and O(n + m) space. Each query decrements every element of its range by at most one, and it may skip elements.

Which edge cases should I test for Zero Array Transformation III?

Every value is already 0: no query is needed, so the answer is queries.length; Even with all queries some index gets too few covering queries: return -1; One index needs many decrements, so many identical queries must stay; Several queries cover an index; the one that reaches farthest to the right is the best one to keep; A query that starts before the current index can still be chosen late: it may skip the indexes it does not need; Queries are not given in order of their left ends, so they must be sorted (or bucketed) first.