1362. Adjacent Swaps to Match
A conveyor belt carries parcels tagged with integers, listed left to right in the array source. The packing plan wants the same parcels laid out as in the array target, which contains exactly the same tags, with repeats allowed. One move swaps two parcels that are next to each other on the belt.
Return the minimum number of moves that turn source into target, as a long. Parcels with equal tags are interchangeable, but swapping two of them never helps, so the k-th copy of a tag in source must end up where the k-th copy of that tag sits in target. Aim for O(n log n) time and O(n) space.
Example 1
- Input:
- source = [3,1,2], target = [1,2,3]
- Output:
- 2
- Explanation:
Move the 3 two places right with two adjacent swaps, giving [1, 2, 3].
Example 2
- Input:
- source = [4,4,7], target = [7,4,4]
- Output:
- 2
- Explanation:
The 7 has to travel two places to the left past both 4s, which costs 2 swaps.
Example 3
- Input:
- source = [5,5,5], target = [5,5,5]
- Output:
- 0
- Explanation:
The arrays are already identical, so no swap is needed.
Constraints
-
1 ≤ n ≤ 1000, wherenis the length of both arrays -
sourceandtargetcontain the same multiset of values -
-109 ≤ source[i], target[i] ≤ 109
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 log n)
- Space
- O(n)