Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don’t appear in arr2 should be placed at the end of arr1 in ascending order.
Solution #1: Frequency Count
Solution #2: Sort with a custom compare function
Because arr2’s elements all are contained in arr1, we can build a rank based on the index of elements.
The true challenge is how to reorder the elements in
arr1. To achieve this we need to custom a sort function base on these rules:
- If values in listed in arr2, compare based on the rank build based on arr2
- If value is not in arr2, it will be left in latter part of final result
- If two values are not listed in arr2, compare based on the values of them.
Preparing for an interview? Check out this!
Join my Email List for more insights, It's Free!😋