959. Gather the Ones
Lanterns are hung on a circular rope with n hooks, where bits[i] is 1 if hook i holds a lit lantern and 0 if it is empty. The rope is circular: hook n-1 is next to hook 0. In one move you may swap the contents of any two hooks.
Return the minimum number of moves needed so that all lit lanterns occupy hooks that are consecutive around the circle (a block that may wrap past the end back to the start). If there are no lit lanterns, or only lit ones, the answer is 0.
Example 1
- Input:
- bits = [1,0,1,0,0,1]
- Output:
- 1
- Explanation:
The array is circular, so positions 5, 0 and 1 hold 1, 1, 0; one swap moves the 1 at index 2 into index 1, so one swap groups all three ones.
Example 2
- Input:
- bits = [1,1,0,1,1]
- Output:
- 0
- Explanation:
Indices 3, 4, 0, 1 are already adjacent around the circle, so no swap is needed.
Example 3
- Input:
- bits = [0,0,0]
- Output:
- 0
- Explanation:
There are no ones, so nothing needs grouping.
Constraints
- 1 ≤ bits.length ≤ 105
- bits[i] is 0 or 1
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)