Back to Practice Dashboard
Python BasicsEasy
Replace each element by rank
Learn how to solve the 'Replace each element by rank' problem. This detailed resource details brute force and optimized approaches.
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?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.