← Questions

Minimum adjacent swaps to group red balls

0
MicrosoftCoding

A coding interview question asked at Microsoft. It tests greedy, median and strings.

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.

Clarifying questions

  • Does the -1 rule for answers above 10^9 apply in this version?
  • Is the empty string or a string with no reds valid input, returning 0?
  • Does the block have to stay inside the row, with no wrap-around?
  • Are the characters limited to uppercase 'R' and 'W'?

What a strong answer covers

  • Collects the indices p of the reds. Grouping them around the median red minimises the total distance moved.
  • Simplifies with q[i] = p[i] - i: the answer is the sum of distances from each q[i] to the median of q, computed in O(n) after one scan.
  • Explains why one adjacent swap of a red and a white moves one red one step, and why reds never need to pass each other.
  • Uses 64-bit or arbitrary-size sums (about m^2 / 4 moves for m reds can exceed 10^9) before checking the -1 threshold.
  • Tests the examples, an already grouped row, a single red, and reds at both far ends.

Follow-ups

  • Group the whites instead, or pick whichever colour costs less.
  • Allow swaps of any two balls, not just neighbours.
  • The row is a circle.

Where it's asked

What it tests

greedy · median · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding