Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Longest run of ones after k flips

Medium · Target 15 minutes · Sliding window· Type asked at

Given a binary array bits and an integer k, you may change at most k zeros into ones. Return the length of the longest run of consecutive ones you can produce.

Examples

InputOutputWhy
bits = [1,1,1,0,0,0,1,1,1,1,0], k = 26Flip the zeros at 4 and 5: indices 4 to 9.
bits = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 310Indices 2 to 11 hold ten elements, three of them zeros.
bits = [0,0,0], k = 00

Constraints

  • 1 ≤ n ≤ 10⁵
  • bits[i] is 0 or 1
  • 0 ≤ k ≤ n

Hints

Hint 1

You never need to decide which zeros to flip one by one. Which runs can become all ones?

Hint 2

A run can be made all ones exactly when it contains at most k zeros.

Hint 3

Window with a zero counter: grow, and while the counter exceeds k, move the left end past a zero.

Where people lose marks

  • Simulating flips, which leads to exponential or quadratic searches.
  • Decrementing the zero count when any element leaves, instead of only when a zero leaves.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.