Problem 234367 · hard · Phase 02 Linear Data Structures

Alternate the Jerseys

strings · arrays · greedy · adjacent swaps

Players sit in a row of seats wearing red or blue jerseys, described by the string row ('R' for red, 'B' for blue). The photographer wants the colours to alternate: no two neighbouring seats may hold the same colour. In one move, two players in neighbouring seats swap places.

Return the minimum number of moves needed, or -1 if the colours can never alternate. An empty row, or a row that already alternates, needs 0 moves.

Examples

Input:  row = "RRBB"
Output: 1
Explanation: swap seats 1 and 2 to get "RBRB".

Input:  row = "RRRBBB"
Output: 3
Explanation: "RRRBBB" -> "RRBRBB" -> "RBRRBB" -> "RBRBRB".

Input:  row = "RRRB"
Output: -1

Constraints

  • 0 <= len(row) <= 10**5
  • row contains only 'R' and 'B'.
  • The answer can exceed 10**9; return it as an ordinary Python integer.
  • Target: O(n) time. Performing the swaps one at a time is far too slow for the largest tests.

Goals

  • See that swapping two equal jerseys never helps
  • Pair the k-th red player with the k-th red target seat
  • Try both possible alternating patterns and reject impossible counts
Starting Python…