1313. Ring Chip Gathering
A circular conveyor has slots.length slots numbered in order, and the last slot is next to the first. The character slots[i] is 1 when slot i holds a chip and 0 when it is empty. In one move a worker swaps the contents of two neighbouring slots, including the pair made by the last and the first slot.
Given slots and k, return the minimum number of moves needed to bring k chips into k slots that are consecutive around the conveyor, wrapping past the end if needed. If the conveyor holds fewer than k chips, return -1. The answer can exceed 32 bits, so return a long.
Think of chips as keeping their order. A window of k neighbouring chips can be gathered around its middle chip, and each window can be costed from prefix sums. The intended solution runs in O(n) time and O(n) space.
Example 1
- Input:
- slots = "1001", k = 2
- Output:
- 0
- Explanation:
The first and last slots are neighbours around the loop, so the two chips already sit side by side and no move is needed.
Example 2
- Input:
- slots = "10101", k = 3
- Output:
- 1
- Explanation:
Chips sit at slots 0, 2 and 4, and slots 4 and 0 are neighbours around the loop. Swapping slots 1 and 2 moves the middle chip next to them, so one move gathers all three.
Example 3
- Input:
- slots = "110", k = 3
- Output:
- -1
- Explanation:
There are only two chips, so three cannot be gathered and the answer is -1.
Constraints
-
1 ≤ slots.length ≤ 105 -
1 ≤ k ≤ slots.length -
slotsconsists only of the characters0and1
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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)