Ctrl K

Friends in One Row

Hard
You went to the movies with friends, but the tickets ended up scattered. The row is given as an array seats: seats[i] = 1 if seat i is taken by someone from your group, and 0 if a stranger sits there. In one move, two people in adjacent seats swap places. Return the smallest number of moves after which at least k people from your group sit in consecutive seats with no gaps.
Example 1
seats=[0, 1, 0, 1, 1, 0, 1], k=3 → 1

Friends sit in seats 1, 3, 4 and 6. One move is enough: the friend in seat 1 swaps with the neighbour in seat 2, and seats 2, 3, 4 are all friends.

Example 2
seats=[1, 0, 0, 1, 0, 0, 1], k=3 → 4

The cheapest target is seats 2, 3, 4: the left friend moves right twice and the right friend moves left twice, 4 moves in total.

Example 3
seats=[1, 1, 0, 1], k=2 → 0

Two friends already sit next to each other in seats 0 and 1, so no moves are needed.

Constraints
  • 1 ≤ len(seats) ≤ 10⁵
  • seats[i] is 0 or 1
  • 1 ≤ k ≤ number of ones in seats
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSignal in the Remotest Village HardGather k Tokens HardEven Out With Increments MediumRug Over Painted Stretches MediumRichest Row of Houses Medium
loading Python…
Input
seats=[0, 1, 0, 1, 1, 0, 1], k=3
Expected
1

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