Leetcode 1122. Relative Sort Array
You are given two arrays arr1
and arr2
, where:
arr2
is a permutation of the unique values in arr1
.arr2
appears 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.
Example:
Input:
arr1 = [2,3,1,3,2,4,6,7,9,2,19]
arr2 = [2,1,4,3,9,6]
Output:
[2,2,2,1,4,3,3,9,6,7,19]
Constraints:
1 <= arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
arr2
are distinct.arr2[i]
is in arr1
.arr1
can have repeated numbers but arr2
contains unique elements.arr2
be sorted?
arr1
.arr1
.arr2
order and then adding the rest in ascending order.arr1
and use the frequency map to build the final array.arr1
.arr2
: O(m) where m is the length of arr2
.arr2
.import java.util.*;
public class RelativeSortArray {
public static int[] relativeSortArray(int[] arr1, int[] arr2) {
int[] result = new int[arr1.length];
Map<Integer, Integer> frequencyMap = new HashMap<>();
// Fill the frequency map for arr1
for (int num : arr1) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int index = 0;
// Add elements of arr2 in the order they appear in arr2
for (int num : arr2) {
if (frequencyMap.containsKey(num)) {
int count = frequencyMap.get(num);
for (int i = 0; i < count; i++) {
result[index++] = num;
}
frequencyMap.remove(num);
}
}
// Get remaining elements and sort them
List<Integer> remainingElements = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
int num = entry.getKey();
int count = entry.getValue();
for (int i = 0; i < count; i++) {
remainingElements.add(num);
}
}
Collections.sort(remainingElements);
// Add remaining sorted elements to result
for (int num : remainingElements) {
result[index++] = num;
}
return result;
}
public static void main(String[] args) {
int[] arr1 = {2,3,1,3,2,4,6,7,9,2,19};
int[] arr2 = {2,1,4,3,9,6};
System.out.println(Arrays.toString(relativeSortArray(arr1, arr2)));
}
}
frequencyMap
: O(n).arr2
: O(m).n
is the length of arr1
and k
is the number of remaining elements not in arr2
.This solution is efficient and adheres to the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?