Replace each element by rank
Detailed guide and Python implementation for the 'Replace each element by rank' problem.
Problem Statement
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.
- •1 <= len(arr) <= 10^5
- •-10^9 <= arr[i] <= 10^9
Examples
arr = [20, 15, 26, 2, 98, 6]
[4, 3, 5, 1, 6, 2]
Sorted: [2,6,15,20,26,98]. Ranks: 2->1, 6->2, 15->3, 20->4, 26->5, 98->6.
arr = [10, 10, 10]
[1, 1, 1]
All elements are equal, so all get rank 1.
arr = [5, 3, 1]
[3, 2, 1]
Sorted: [1,3,5]. Ranks: 1->1, 3->2, 5->3.
Need a Hint?
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.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Replace Characters in a String in Python
Learn how to replace characters or substrings in Python strings. Master the replace() method, count limits, and using translate for multiple characters.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs Ruby: Scripting, Web Frameworks, and Philosophy
Compare Python and Ruby. Learn the subtle differences in their philosophies, syntax elegancy, web frameworks (Django vs Rails), and execution styles.