Relative Sort Array — LeetCode 1122 Python Solution
- Problem
- #1122
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
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]
Python solution
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
pos = {x: i for i, x in enumerate(arr2)}
return sorted(arr1, key=lambda x: pos.get(x, 1000 + x))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n + m) |
| Space | O(n + m) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1122. Relative Sort Array is filed here because LeetCode tags it Sorting and Counting Sort, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1122. Relative Sort Array?
- LeetCode 1122. Relative Sort Array is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1122. Relative Sort Array?
- The Python solution on this page runs in O(n \times \log n + m).
- What is the space complexity of LeetCode 1122. Relative Sort Array?
- The Python solution on this page uses O(n + m) auxiliary space.
- What topics does LeetCode 1122. Relative Sort Array cover?
- LeetCode 1122. Relative Sort Array is tagged Array, Hash Table, Counting Sort and Sorting on LeetCode.