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 do not appear in arr2 should be placed at the end of arr1 in ascending order.
The sort key is the relative order in \(\textit{arr2}\); values absent from \(\textit{arr2}\) follow, sorted by themselves. A map stores each \(\textit{arr2}\) index; the comparator uses that index if present and \(1000+x\) otherwise, so one sort handles both groups. Values in \(\textit{arr2}\) are unique, so indices are a stable order.
First, we use a hash table \(\textit{pos}\) to record the position of each element in array \(\textit{arr2}\). Then, we map each element in array \(\textit{arr1}\) to a tuple \((\textit{pos}.\textit{get}(x, 1000 + x), x)\), and sort these tuples. Finally, we take out the second element of all tuples and return it.
The time complexity is \(O(n \log n + m)\), and the space complexity is \(O(n + m)\), where \(n\) and \(m\) are the lengths of arrays \(\textit{arr1}\) and \(\textit{arr2}\), respectively.
Method 1's comparison sort is \(O(n \log n)\). When the value range is small, count frequencies in \(\textit{arr1}\), emit values in \(\textit{arr2}\) order, then scan the leftovers by value, which is linear.
We can use the idea of counting sort. First, count the occurrence of each element in array \(\textit{arr1}\). Then, according to the order in array \(\textit{arr2}\), put the elements in \(\textit{arr1}\) into the answer array \(\textit{ans}\) according to their occurrence. Finally, we traverse all elements in \(\textit{arr1}\) and put the elements that do not appear in \(\textit{arr2}\) in ascending order at the end of the answer array \(\textit{ans}\).
The time complexity is \(O(n + m)\), and the space complexity is \(O(n)\), where \(n\) and \(m\) are the lengths of arrays \(\textit{arr1}\) and \(\textit{arr2}\) respectively.