Levels cleared from every starting point
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Uber. It tests prefix sums, two pointers and arrays.
A game has n levels in a row. You are given two integer arrays of length n, layers and energy, and an integer K.
A run that starts at level i begins with exactly K energy and plays levels i, i+1, i+2, ... in order. At level j:
- Pay
layers[j]energy. - If the energy you have left is at least
energy[j], you clear the level, score 1 point, and move on toj+1. - Otherwise the run ends at once. No later level counts.
Every run is independent and starts again with K energy.
Return an array answer of length n where answer[i] is the score of the run that starts at level i.
Implement:
def max_levels(layers: list[int], energy: list[int], k: int) -> list[int]: ...
Constraints
1 <= n <= 10^50 <= layers[j], energy[j] <= 10^90 <= K <= 10^14
Example 1
layers = [2, 3, 1, 4], energy = [5, 2, 4, 1], K = 10
output = [3, 3, 2, 1]
From level 0: 10-2=8 (>=5, pass), 8-3=5 (>=2, pass), 5-1=4 (>=4, pass), 4-4=0 (<1, stop). Score 3.
From level 1: 7 (>=2), 6 (>=4), 2 (>=1). Score 3.
Example 2
layers = [0, 0], energy = [10, 0], K = 5
output = [0, 1]
Level 0 needs 10 energy left, so a run from 0 scores nothing. A run from 1 clears level 1.
An O(n^2) simulation is a fine start. Aim for O(n) or O(n log n).
Clarifying questions
- Is the check on the energy after paying, as written, so energy can go below zero and then fail?
- Is the run over once one level fails, even if later levels are free?
- Can
Kbe0? - Will there be many runs with different
Kvalues?
What a strong answer covers
- Uses prefix sums of
layers. Leveljpasses in a run fromiwhenprefix[j + 1] + energy[j] <= K + prefix[i]. - Notes that the right side never decreases as
igrows (layers are non-negative). So the first failing level never moves left. - Uses two pointers for O(n) time, or binary search over a sparse table or segment tree for O(n log n).
- Uses 64-bit values (
Kgoes up to10^14) and caps each answer atn - i. - Tests both examples, all zeros, a first level that always fails, and a run that clears to the end.
Follow-ups
- A different
Kfor each starting level. - One level may be skipped per run.
- Clearing a level gives back some energy, so the threshold is no longer monotone.
- Return the start with the best score.
Where it's asked
What it tests
prefix sums · two pointers · arrays
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
