Problem · Array

Minimum Swaps Required to Group All Red Balls Together

Learn this problem
MediumMicrosoft logoMicrosoftFULLTIMEOA
See Microsoft hiring insights

Problem statement

Given a string of red and white balls, return the minimum number of adjacent swaps required to arrange all red balls into one contiguous segment.

Given that S is "RW" repeated 100,000 times, your function should return -1, as the minimum number of swaps required exceeds 10^9.

Function

minSwaps(colors: String) → int

Examples

Example 1

colors = "WRRWR"return = 1
Swap the last red ball with the white ball immediately before it: "WRRWR" becomes "WRRRW". All red balls are contiguous after one adjacent swap.

Example 2

colors = "WWRWWWWWWWWWRWR"return = 10
The red balls start at indices 2, 12, and 14. After subtracting their target offsets 0, 1, and 2, the normalized positions are 2, 11, and 12. Moving them around the median normalized position costs 9 + 0 + 1 = 10 swaps.

Example 3

colors = "WWW"return = 0
There are no red balls that need to be grouped together.

Example 4

colors = "WRRWRW"return = 1
As in the first example, moving the final red ball one position to the left makes all three red balls contiguous.

Constraints

  • N is an integer in the range [1..100,000]
  • The string S consists only of the characters 'R' and 'W'.
  • Constraints updated in full on 05-24-2025 🥑
  • More Microsoft problems

    drafts saved locally
    public int minSwaps(String colors) {
      // write your code here
    }
    
    colors"WRRWR"
    expected1
    checking account