1312. Three-Colour Ring Grouping

Hard7.5 points estimatedSliding WindowStringGreedyCounting

A necklace is a closed loop of beads, each coloured red (R), green (G) or blue (B). The string beads lists them in order around the loop, so the last bead is next to the first. A jeweller wants every colour to form a single unbroken arc of the loop, with no colour split into separate pieces. A colour that is not present needs nothing.

In one move the jeweller may pick any two beads of the necklace, at any distance from each other, and exchange them. Return the smallest number of moves that makes each colour one contiguous arc.

Trying every final layout from scratch is too slow. Each possible layout is three consecutive blocks whose sizes are the colour counts, so slide that layout around the loop and update the tallies of which bead sits where. The intended solution runs in O(n) time and O(1) extra space.

Example 1

Input:
beads = "RGRG"
Output:
1
Explanation:

Exchanging the green bead at index 1 with the red bead at index 2 gives RRGG, where each colour is one arc, so one move is enough.

Example 2

Input:
beads = "RRGGBB"
Output:
0
Explanation:

Each colour is already one arc, so no move is needed.

Example 3

Input:
beads = "RGBRGB"
Output:
2
Explanation:

No single exchange groups all three colours, and two exchanges are enough, so the answer is 2.

Constraints

  • 1 ≤ beads.length ≤ 105

  • beads consists only of the characters R, G and B

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…