Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints
1 <= arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
- All the elements of
arr2
are distinct. - Each
arr2[i]
is inarr1
.
Solution
We can either use map
+ sorting
, or TreeMap
OR map
+ heap
or bucket to sort this problem. Here is the video explanation:
Method 1 - Using Map and Sorting
- We can use
counts
as frequency map onarr1
. - Then, we loop on
arr2
, and if key is present incounts
, we append to thepresent
list forvalue
number of times - Then, we check
arr2
andcounts
map to find the keys that don’t exist inarr2
and append themvalue
number of times tonotPresent
list - Then, we sort
notPresent
list - Finally, we append
notPresent
list topresent
list and that is our answer.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
- 🧺 Space complexity:
O(n)
Method 2 - Using Bucketsort with array
- Because
0 <= arr1[i], arr2[i] <= 1000
, we use an array to count every element, lets call itcnt
. - Now, we don’t need
arr1
, we can actually fill the sorted array in place. So, we will go througharr2
, from left to right. When, we find frequency of it incnt
, we fill it inarr1
. - Now, we fill in remaining elements in cnt, which are not yet encountered.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
for using the count array