Longest ON run with k range flips
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's online assessment, last asked Apr 2026. It tests sliding window, strings and greedy.
A data center rack holds n servers in a row. Their states are given as a binary string server_states, where '1' means the server is ON and '0' means it is OFF.
An operator may run a range flip at most k times. A range flip picks any contiguous block of servers [i, j] and toggles every server in it: ON becomes OFF and OFF becomes ON. Flips may overlap.
Return the length of the longest contiguous run of ON servers that can exist after at most k range flips.
def max_consecutive_on(server_states: str, k: int) -> int: ...
Constraints
0 <= n <= 2 * 10^50 <= k <= n-
server_statescontains only'0'and'1'
Example 1
server_states = "0110100", k = 1
output: 4
Flip [3, 3] to get 0111100. That gives a run of 4 (indices 1–4). Flipping [0, 0] instead gives 1110100, a run of only 3.
Example 2
server_states = "1001011", k = 2
output: 7
Flip [1, 2] and [4, 4], and every server is ON.
Note: a flip that covers an ON server turns it OFF, so a flip is not the same as setting a range to ON.
Clarifying questions
- Must the flips be exactly
k, or at mostk? (At most.) - Can flips extend outside the window we care about?
- For
k = 0, is the answer the longest run of1s already there? - Do we need the flips themselves, or only the length?
What a strong answer covers
- Shows that a window can be all ON after
jflips exactly when it holds at mostjseparate blocks of OFF servers. A flip's two ends can fix at most two "edges" of OFF blocks, and each OFF block has two edges. - Shows that one exact flip per OFF block is enough, so the bound can be reached.
- Reduces the task to the longest window with at most
kOFF blocks, solved with a sliding window over the runs. That is O(n). - Points out why "flip = set to ON" reasoning goes wrong: a flip over an ON server turns it OFF.
- Tests
k = 0, all OFF withk >= 1, all ON, the empty string and both examples.
Follow-ups
- Return the flips.
- Each flip costs its length, and there is a total budget.
- The rack is circular.
- Flips are limited to at most
Lservers each.
Where it's asked
- Amazon · Online assessment · Last asked Apr 2026Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant
What it tests
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.
