Python Basics簡単

Replace each element by rank

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

問題提起

簡単

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

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

解決する準備はできましたか?

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

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。