1360. Three-Value Swap Count

Medium3.5 points estimatedSortingArrayCountingGreedy

A relay team's n runners wear bibs numbered 1, 2 or 3 and stand in a line, recorded in the array nums. In one move you may swap any two runners, whatever the distance between them. Return the smallest number of swaps that leaves the bibs in non-decreasing order. Think of the target as the sorted array, and of each wrongly placed runner as sitting in a zone that belongs to another bib. Two runners who sit in each other's zones are fixed by a single swap. Whatever remains forms triples that rotate through all three bibs and need two swaps each. Aim for O(n log n) time with sorting, or O(n) with counting, and O(n) space.

Example 1

Input:
nums = [2,1,3,2,1]
Output:
2
Explanation:

The sorted line is 1, 1, 2, 2, 3; the three wrongly placed runners rotate through three zones, which takes 2 swaps.

Example 2

Input:
nums = [3,2,1]
Output:
1
Explanation:

Swapping the first and last runners gives 1, 2, 3 in one swap.

Example 3

Input:
nums = [1,1,2,3]
Output:
0
Explanation:

The line is already in order, so no swaps are needed.

Constraints

1 ≤ n ≤ 1000

nums[i] is 1, 2 or 3

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

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…