You are given two integer arrays arr1 and arr2. The elements of arr2 are distinct, and every element of arr2 also appears in arr1.
Sort the elements of arr1 so that the relative ordering of its items is the same as in arr2. Elements that do not appear in arr2 go at the end, in ascending order.
Function Signature
def relative_sort_array(arr1: list[int], arr2: list[int]) -> list[int]:
Rules
-
Return a list with the same elements as
arr1
, each value appearing as many times as it does in
arr1
.
-
Values that appear in
arr2
come first, grouped together and ordered by their position in
arr2
.
-
Values that do not appear in
arr2
follow, sorted in ascending order with their duplicates kept.
Constraints
-
1 <= len(arr1), len(arr2) <= 1000
-
0 <= arr1[i], arr2[i] <= 1000
-
All the elements of
arr2
are distinct.
-
Each
arr2[i]
is in
arr1
.
Examples
Input: arr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], arr2 = [2, 1, 4, 3, 9, 6]
Output: [2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19]
The values from arr2 come out in its order: three 2s, one 1, one 4, two 3s, one 9 and one 6. The remaining values 7 and 19 are appended in ascending order.
Input: arr1 = [28, 6, 22, 8, 44, 17], arr2 = [22, 28, 8, 6]
Output: [22, 28, 8, 6, 17, 44]
After 22, 28, 8 and 6 are placed in that order, the leftover values 44 and 17 are appended sorted as 17, 44.
Input: arr1 = [5, 3, 5, 1, 3, 0], arr2 = [3]
Output: [3, 3, 0, 1, 5, 5]
Both 3s come first. The leftovers 5, 5, 1 and 0 are sorted ascending, and the two 5s both stay in the output.