oneby7

Heaps Top K

412. Rank Transform of an Array

Easy

You are given an array of integers arr. Replace each element with its rank, and return the array of ranks. The answer keeps the order of arr: its element i is the rank of arr[i].

The rank of an element says where its value sits among the different values in arr, from smallest to largest. The smallest value has rank 1, the next larger value has rank 2, and so on. Equal elements share one rank, and the ranks have no gaps: after two elements of rank 1, the next larger value has rank 2.

If arr is empty, return an empty array.

Example 1

Input: arr = [40, -5, 12, 40, 0]

Output: [4,1,3,4,2]

Explanation: The different values, from smallest to largest, are −5, 0, 12 and 40. So −5 has rank 1, 0 has rank 2, 12 has rank 3, and both 40s have rank 4.

Example 2

Input: arr = [-8, 1000000000, -8, -1000000000]

Output: [2,3,2,1]

Explanation: −109 is the smallest value, so it has rank 1. The two −8s share rank 2, and 109 has rank 3.

Example 3

Input: arr = [6, 6, 6]

Output: [1,1,1]

Explanation: Every element is 6, so every element has rank 1.

Check your understanding

Work out the answer for this input before you write any code.

arr = [9, 2, 9, 5, 2]

Constraints

  • 0 ≤ arr.length ≤ 105
  • -109 ≤ arr[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.