EasyNo. 1331

Rank Transform of an Array — LeetCode 1331 Python Solution

Pattern
Sorting
Topics
Array, Hash Table, 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

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

Complexity

Time
O(n × log n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
1338Reduce Array Size to The HalfMedium
0049Group AnagramsMedium
0169Majority ElementEasy
0217Contains DuplicateEasy
0229Majority Element IIMedium
0268Missing NumberEasy

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 × 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.

Free to download. Check it runs on your machine, then pick a plan.