Zero array after range-decrement queries
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Uber's coding round, last asked Apr 2026. It tests prefix sums and difference arrays.
You get an array of non-negative integers nums and a list of queries [l, r]. Process the queries in order. For each one you may pick any subset of the indices between l and r, inclusive, and subtract 1 from each picked index. Decide whether you can make every element exactly 0 after all queries. Values may never go below 0.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
can_zero(nums: list[int], queries: list[list[int]]) -> bool.
Example
can_zero([1, 0, 1], [[0, 2]]) -> True # pick indices 0 and 2
can_zero([4, 3, 2, 1], [[1, 3], [0, 2]]) -> False # index 0 is covered once but needs 4
Constraints
-
1 <= len(nums) <= 10^5,0 <= nums[i] <= 10^5. -
1 <= len(queries) <= 10^5,0 <= l <= r < len(nums).
Clarifying questions
- Must every query be applied, or may some be skipped? (Picking an empty subset is the same as skipping.)
- Can a query subtract more than 1 from an index?
- Does the order of the queries matter?
- Should I return the decision only, or a plan of which indices each query picks?
What a strong answer covers
- The key observation: each index can be decremented once per query that covers it, and choices at different indices are independent, so the answer is True exactly when every
nums[i]is at most the number of queries coveringi. - Counting coverage with a difference array and a prefix sum: O(n + q) time, O(n) space.
- Why simulating each query index by index is O(n · q) and too slow.
- Tests: all zeros, a query covering one index, an index covered by no query.
Follow-ups
- Return the smallest
ksuch that the firstkqueries suffice, or -1 (binary search onk, or a sweep). - Each query
[l, r, v]may subtract up tovfrom each picked index. - Each query must subtract exactly 1 from every index in its range. What changes?
Where it's asked
- Uber · Coding · Last asked Apr 202660 min · Two rounds; one is often object-oriented design (a parking lot, a meeting scheduler, an expression evaluator) · No AI, except a newer AI-assisted debugging round in some senior loops
What it tests
prefix sums · difference arrays
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
