FastPrepFastPrep
Problem Brief

Minimum Swaps Required to Group All Red Balls Together

FULLTIMEOA

Given 2 balls Red and White, return the minum number of swaps required where we want to arrange all the red balls into consistent segment (in one move, you can swap adjacent ones)

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

1Example 1

Input
colors = "WRRWR"
Output
2
Explanation
Given S = "WRRWR", your function should return 2. We can move the last ball two positions to the left: 1. "WRRWR" 2. "WRRWW" 3. "WWRRW" This example originates from source 2, which conflicts with source 1. Source 1 lists the input as "WRRWRW" with an output of 2, whereas source 2 shows the input as S="WRRWR" and also gives an output of 2. This new test case was added on 05-24-2025 :) You can find the relevant source ss in the Problem Source section below. 🌷

2Example 2

Input
colors = "WWRWWWWWWWWWRWR"
Output
4
Explanation
Given S = "WWRWWWWWWWWWRWR", your function should return 4. We can move the first and last red balls toward the middle red ball: 1. "WWRWWWWWWWWWRWR" 2. "WWWWWWWWWWWRRWR" 3. "WWWWWWWWWWWRRWR" This new test case was added on 05-24-2025 :) You can find the relevant source ss in the Problem Source section below. πŸ‰

3Example 3

Input
colors = "WWW"
Output
0
Explanation
There are no red balls that need to be grouped together. This new test case was added on 05-24-2025 :) You can find the relevant source ss in the Problem Source section below. 🍊

4Example 4

Input
colors = "WRRWRW"
Output
2
Explanation
This example originates from source 1, which conflicts with source 2. Source 1 lists the input as "WRRWRW" with an output of 2, whereas source 2 shows the input as S="WRRWR" and also gives an output of 2.

Constraints

Limits and guarantees your solution can rely on.

  • 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 πŸ₯‘
  • public int minSwaps(String colors) {
      // write your code here
    }
    
    Input

    colors

    "WRRWR"

    Output

    2

    Sign in to submit your solution.