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 deleting one element

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

Given a binary array bits, you must delete exactly one element. Return the length of the longest run of consecutive ones in what remains.

Examples

InputOutputWhy
bits = [1,1,0,1]3Delete the 0.
bits = [0,1,1,1,0,1,1,0,1]5Delete the 0 at index 4: 1,1,1,1,1.
bits = [1,1,1]2Something must be deleted, so one of the ones goes.

Constraints

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

Hints

Hint 1

Deleting a zero joins the runs of ones on either side of it. What does the stretch from the start of one to the end of the other look like?

Hint 2

It is a window with at most one zero. After the deletion its length is one less.

Hint 3

Take the longest window with at most one zero and subtract one. That also handles an array of all ones.

Where people lose marks

  • Returning n for an array of all ones. A deletion is compulsory.
  • Tracking runs on either side of each zero with separate arrays: correct, but more code and more edge cases than the window.
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.