Minimum adjacent swaps to group red balls
I was asked this
No reports yet. Sign in to say where you were asked it.
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-
ballscontains 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
-1rule for answers above10^9apply 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
pof 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 eachq[i]to the median ofq, computed inO(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 / 4moves formreds can exceed10^9) before checking the-1threshold. - 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
