Python BasicsEasy

Replace each element by rank

Detailed guide and Python implementation for the 'Replace each element by rank' problem.

Problem Statement

Easy

Write a function replace_by_rank(arr) that replaces each element in the array with its rank when the array is sorted in ascending order. The smallest element gets rank 1, the second smallest gets rank 2, and so on. If two elements are equal, they get the same rank. Return the array of ranks.

Constraints
  • 1 <= len(arr) <= 10^5
  • -10^9 <= arr[i] <= 10^9

Examples

Example 1
Input
arr = [20, 15, 26, 2, 98, 6]
Output
[4, 3, 5, 1, 6, 2]
Explanation

Sorted: [2,6,15,20,26,98]. Ranks: 2->1, 6->2, 15->3, 20->4, 26->5, 98->6.

Example 2
Input
arr = [10, 10, 10]
Output
[1, 1, 1]
Explanation

All elements are equal, so all get rank 1.

Example 3
Input
arr = [5, 3, 1]
Output
[3, 2, 1]
Explanation

Sorted: [1,3,5]. Ranks: 1->1, 3->2, 5->3.

Need a Hint?
Consider using Arrays-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.