Relative Sort Array (LeetCode 1122): Solution and Explanation
Reorder arr1 so values follow the order given by arr2, and put every value missing from arr2 at the end in ascending order.
Intuition
All values are between 0 and 1000, so you can count them instead of comparing them. Once you know how many 2s, 3s and so on arr1 holds, writing the answer is just a matter of choosing which bucket to empty next.
arr2 tells you the order for the first buckets. Walk it, and for each value write out all its copies and clear the bucket.
Whatever is still counted after that never appeared in arr2. Walking the buckets from 0 to 1000 writes those leftovers in ascending order for free.
Approach: Counting sort
- Make
count, an array of 1001 zeros, and add 1 for every value in arr1. - For each x in arr2, append x to the result
count[x]times, then setcount[x] = 0. - For x from 0 to 1000, append x
count[x]times. - Return the result.
Step-by-step example
arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
- Counting gives 1:1, 2:3, 3:2, 4:1, 6:1, 7:1, 9:1, 19:1.
- Following arr2: write 2,2,2 then 1 then 4 then 3,3 then 9 then 6. Those buckets are now empty.
- Buckets 7 and 19 still have one each. Scanning upward writes 7 then 19.
- Result: [2,2,2,1,4,3,3,9,6,7,19].
Code: Python, Java, C++
1class Solution:
2 def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
3 count = [0] * 1001
4 for x in arr1:
5 count[x] += 1
6 result = []
7 for x in arr2:
8 result.extend([x] * count[x])
9 count[x] = 0
10 for x in range(1001):
11 result.extend([x] * count[x])
12 return result1class Solution {
2 public int[] relativeSortArray(int[] arr1, int[] arr2) {
3 int[] count = new int[1001];
4 for (int x : arr1) {
5 count[x]++;
6 }
7 int[] result = new int[arr1.length];
8 int k = 0;
9 for (int x : arr2) {
10 while (count[x]-- > 0) result[k++] = x;
11 }
12 for (int x = 0; x <= 1000; x++) {
13 while (count[x]-- > 0) result[k++] = x;
14 }
15 return result;
16 }
17}1class Solution {
2public:
3 vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
4 vector<int> count(1001, 0);
5 for (int x : arr1) {
6 count[x]++;
7 }
8 vector<int> result;
9 for (int x : arr2) {
10 while (count[x]-- > 0) result.push_back(x);
11 }
12 for (int x = 0; x <= 1000; x++) {
13 while (count[x]-- > 0) result.push_back(x);
14 }
15 return result;
16 }
17};Time and space complexity
O(n + m + k)
One pass over arr1 (n), one over arr2 (m), and one over the k = 1001 possible values.
O(k)
The count array has 1001 entries, not counting the output.
Other approaches
Custom comparator sort (time O(n log n), space O(m))
Map each arr2 value to its index, then sort arr1 with a key of (index, value) for values in arr2 and (len(arr2), value) for the rest. Shorter to write, works for any value range.
Hash map counts (time O(n + m + r log r), space O(n))
Use a hash map instead of a fixed array when values are not bounded, then sort only the leftover keys.
Common mistakes
- Forgetting to clear
count[x]after writing arr2 values, which writes them a second time in the leftover pass. - Sorting leftovers in insertion order instead of ascending order.
- Writing each arr2 value once instead of as many times as it appears in arr1.
Frequently asked questions
Why not just sort with a comparator?
That works and is O(n log n). Counting sort is linear because the value range is small and fixed, and it makes the leftover ordering automatic.
Is the result stable?
Equal values are indistinguishable integers, so stability does not matter here.
What if a value in arr2 were missing from arr1?
The constraints rule it out, but the code would just write it zero times.