Rank Transform of an Array — LeetCode 1331 Python Solution

EasyArrayHash TableSorting
Problem
#1331
Pattern
Sorting
Reading time
2 min

The problem

Given an array of integers arr, replace each element with its rank. The rank represents how large the element is.

Example

Input
arr = [40,10,20,30]
Output
[4,1,2,3]
Explanation
40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.

Python solution

Python
class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        t = sorted(set(arr))
        return [bisect_right(t, x) for x in arr]

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1331. Rank Transform of an Array is filed here because LeetCode tags it Sorting, 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 1331. Rank Transform of an Array?
LeetCode 1331. Rank Transform of an Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 1331. Rank Transform of an Array?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1331. Rank Transform of an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1331. Rank Transform of an Array cover?
LeetCode 1331. Rank Transform of an Array is tagged Array, Hash Table 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