Relative Sort Array (LeetCode 1122): Solution and Explanation

Easy
Array
Hash Table
Sorting
Counting Sort

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

  1. Make count, an array of 1001 zeros, and add 1 for every value in arr1.
  2. For each x in arr2, append x to the result count[x] times, then set count[x] = 0.
  3. For x from 0 to 1000, append x count[x] times.
  4. 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]
  1. Counting gives 1:1, 2:3, 3:2, 4:1, 6:1, 7:1, 9:1, 19:1.
  2. Following arr2: write 2,2,2 then 1 then 4 then 3,3 then 9 then 6. Those buckets are now empty.
  3. Buckets 7 and 19 still have one each. Scanning upward writes 7 then 19.
  4. 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 result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Counting sort O(n + m + k)
Custom comparator sort O(n log n)
Hash map counts O(n + m + r log r)
Time

O(n + m + k)

One pass over arr1 (n), one over arr2 (m), and one over the k = 1001 possible values.

Space

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.