Minimum adjacent swaps to group red balls

0
Sign in

A row of balls is given as a string balls. Each character is 'R' (red) or 'W' (white).

In one move you may swap two neighbouring balls. Return the minimum number of moves needed so that all red balls form one contiguous block (the block may be anywhere in the row). If the reds are already contiguous, or there are fewer than two reds, return 0.

Some versions add: if the answer is greater than 10^9, return -1.

Constraints

  • 0 <= len(balls) <= 10^5
  • balls contains only 'R' and 'W'

Example 1

Input:  balls = "WRRWWR"
Output: 2

Move the last red ball two places left to get "WRRRWW".

Example 2

Input:  balls = "WWRWWWRWR"
Output: 4

Keep the red at index 6 in place. Move the red at index 2 right by 3 and the red at index 8 left by 1, giving reds at indices 5, 6, 7.

MicrosoftCodingMedium

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.