#1122
Relative Sort Array
EasyArrayHash TableSortingCounting SortHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + k log k) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + k log k)Space O(n)
The optimal solution uses a counting sort approach. We count the occurrences of each number in arr1 and then build the result based on the order defined in arr2, followed by sorting the remaining elements.
⚙️
Algorithm
4 steps- 1Step 1: Create a count array to count occurrences of each number in arr1.
- 2Step 2: Initialize an empty result array.
- 3Step 3: Append elements from arr2 to the result based on their counts.
- 4Step 4: Append remaining elements (not in arr2) sorted in ascending order.
solution.py11 lines
1def relativeSortArray(arr1, arr2):
2 count = [0] * 1001
3 for num in arr1:
4 count[num] += 1
5 result = []
6 for num in arr2:
7 result.extend([num] * count[num])
8 for num in range(1001):
9 if count[num] > 0 and num not in arr2:
10 result.extend([num] * count[num])
11 return resultℹ
Complexity note: The time complexity is O(n) for counting and O(k log k) for sorting the remaining elements, where n is the length of arr1 and k is the number of unique elements not in arr2.
- 1Using a counting array is efficient for problems with a limited range of integers.
- 2Maintaining the order of elements based on a reference array is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.