KatInterview

Longest Circular Run of Ones with One Flip

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashingsliding-windowcircular-arraytwo-pointers

Last updated

Tests sliding window technique on a circular binary array to find the maximum consecutive ones achievable by flipping at most one zero.

Problem

You have a binary array bits that wraps around — think of it as a ring where the element after the last position is the element at position 0.

You may change at most one 0 in the array to a 1. Return the longest unbroken sequence of 1s you can form anywhere along this ring.

Because the ring is circular, a valid sequence may start near the end of the array and continue from the beginning. However, each position may appear at most once in a sequence, so the answer can never be greater than the length of the array.

Constraints

  • 1 <= len(bits) <= 10^5
  • bits[i] is either 0 or 1

Examples

Example 1

Input: longest_circular_ones([1, 0, 1, 1, 0, 1])

Output: 5

Example 2

Input: longest_circular_ones([0, 0, 0])

Output: 1

Example 3

Input: longest_circular_ones([1, 1, 1])

Output: 3

Hints

Hint 1

A contiguous segment of any circular array always appears as a plain contiguous window somewhere inside the doubled array `bits + bits`. You don't need to build that copy — virtual indexing with `i % n` works fine.

Hint 2

The problem reduces to: find the longest window in that doubled array that contains at most one `0`, subject to the window never being longer than `n`. Two pointers handle both conditions at once.

Hint 3

The length cap `right - left + 1 <= n` is critical. Without it, an all-ones array or a single-zero array would let the window grow past `n` and count the same index twice. Watch for this off-by-one in your shrink condition.