Relative Sort Array
This problem can be approached using the Python builtin sorting function with a custom comparison method. The approach would be as follows:
 Count the occurrence of each element in
arr1
and store it in a dictionary.  For each element in
arr2
, add that element to the result array as many times as it occurs inarr1
(based on our count from step 1), and remove the element count from the dictionary.  After all elements from
arr2
have been added to the result, there may be remaining elements inarr1
that weren’t inarr2
. Add these to the result in ascending order.
Here is the Python code:


Let’s break it down:
 The
Counter
objectcount
is created fromarr1
, counting the occurrences of each number inarr1
.  We iterate over each number
num
inarr2
. We extend the result list bynum
repeatedcount[num]
times. Then we delete the count ofnum
from thecount
dictionary.  After adding all numbers present in
arr2
to the result list, some numbers may remain incount
(those that were inarr1
but not inarr2
). We sort the remaining numbers and add them to the result list. We repeat each numbercount[num]
times.  Finally, we return the result list.
This approach ensures that the relative ordering in arr2
is preserved, and any extra elements not present in arr2
are added in ascending order at the end.
Alternate Solution
 Because 0 <= arr1[i], arr2[i] <= 1000, we use an array to count every element.
 Go through every element in the second array, and update values of the first array based on the order in the second array.

