Problem Description
Given two arrays arr1 and arr2 where arr2 contains distinct elements and every element in arr2 is also in arr1, sort arr1 so that the relative ordering of elements in arr2 is preserved in arr1. Any elements in arr1 that do not appear in arr2 should be placed at the end of arr1 in ascending order.
Key Insights
- Use a hash table (or array for counting given the value constraints) to count the occurrences of each element in arr1.
- Iterate through arr2 and for each element, append it to the result based on its count from the hash table.
- Remove the used elements from the hash table.
- Sort the remaining elements (those not in arr2) in ascending order and append them to the result.
Space and Time Complexity
Time Complexity: O(n + m log m) where n is the length of arr1 and m is the number of leftover elements not in arr2. Given that element values are bounded (0 to 1000), a counting sort can make this nearly O(n). Space Complexity: O(n) for storing the frequency counts and the result array.
Solution
The solution leverages a frequency counter (hash table) to count how many times each element appears in arr1. We then process arr2 to add each number in its given order according to its frequency. Finally, we sort the remaining numbers that are not in arr2 and append them to the result array. This approach ensures that the relative order specified by arr2 is maintained and that the other elements are sorted in ascending order.