← Questions

Longest ON run with k range flips

0
AmazonCodingLast asked Apr 2026

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^5
  • 0 <= k <= n
  • server_states contains 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 most k? (At most.)
  • Can flips extend outside the window we care about?
  • For k = 0, is the answer the longest run of 1s 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 j flips exactly when it holds at most j separate 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 k OFF 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 with k >= 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 L servers 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

sliding window · strings · greedy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding