Given two integer arrays, reorder elements of the first array by the order of elements defined by the second array.

The elements that are not present in the second array but present in the first array should be appended at the end sorted. The second array can contain some extra elements which are not part of the first array.

 
For example,

Input:
 
first = [5, 8, 9, 3, 5, 7, 1, 3, 4, 9, 3, 5, 1, 8, 4]
second = [3, 5, 7, 2]
 
Output: [3, 3, 3, 5, 5, 5, 7, 1, 1, 4, 4, 8, 8, 9, 9]

Practice this problem

1. Using Hashing

The idea is to count the frequency of each element of the first array and store it in a hash table. Now for each element of the second array, check if the element is present on the map or not. If it is present on the map, print the element n number of times, where n is the frequency of that element in the first array. We also remove that element from the map so that we are only left with only present elements in the first array (but not present in the second array). To append them at the end, they need to be sorted.

Note that keys are already ordered in std::map or TreeMap, but we get O(log(n)) insertion and retrieval time. If we use std::unordered_map or HashMap, we get O(1) insertion and retrieval time, but will require sorting since its keys are unordered.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The array after sorting is 3 3 3 5 5 5 7 1 1 4 4 8 8 9 9

Java


Download  Run Code

Output:

The array after sorting is [3, 3, 3, 5, 5, 5, 7, 1, 1, 4, 4, 8, 8, 9, 9]

Python


Download  Run Code

Output:

The array after sorting is [3, 3, 3, 5, 5, 5, 7, 1, 1, 4, 4, 8, 8, 9, 9]

The time complexity of the above solution is O(m.log(m) + n), where m and n are the total number of elements in the first and second array, respectively.

2. Using Comparator

We can also write a custom comparison method to solve this problem. Let the two elements to be compared are x and y. Then

  1. If both x and y are present in the second array, then the lower index element in the second array should come first.
  2. If only one of x or y is present in the second array, then the second array element should come first.
  3. If both elements are not present in the second array, then the default ordering will be considered.

The algorithm can be implemented as follows in Java:

Java


Download  Run Code

Output:

[3, 3, 3, 5, 5, 5, 7, 1, 1, 4, 4, 8, 8, 9, 9]