Ctrl K

Ones on a Ring

Medium
The array ring of zeros and ones is closed into a circle: the last element counts as a neighbour of the first. In one swap you may exchange the values at any two different positions. Find the smallest number of swaps after which all the ones occupy one unbroken arc of the ring, that is, they stand side by side, possibly wrapping around from the end of the array to its start.
Example 1
ring=[1, 0, 0, 1, 0, 1] → 1

The array is a ring, so the last element neighbours the first. The ones at positions 5 and 0 are already adjacent; one swap moves the one at position 3 to position 4, forming the block 4, 5, 0.

Example 2
ring=[0, 1, 0, 1, 0, 1, 0, 1] → 2

Four ones alternate with zeros. Any arc of four cells holds exactly two ones, so two swaps are needed to bring in the rest.

Example 3
ring=[1, 1, 0, 0, 1] → 0

Going around the ring, the ones already form a block: 4, 0, 1.

Constraints
  • 1 ≤ len(ring) ≤ 10⁵
  • Each ring[i] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShortest Stretch to the Goal MediumEvenly Stepped Stretches MediumLongest Run of Ones With One Fix MediumNearest k Values MediumWindows With a Small Product Medium
loading Python…
Input
ring=[1, 0, 0, 1, 0, 1]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 120 tests on the server, hidden ones included.