Relative Sort Array — LeetCode 1122 Python Solution

EasyArrayHash TableCounting SortSorting
Problem
#1122
Pattern
Sorting
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n \times \log n + m)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview