#1331
Easy Algorithms Rank transform of an array
Array Hash Table Sorting
70.8% acceptance
Feb 25, 2026
2374
114
Given an array of integers arr, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
Rank is an integer starting from 1.
The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
Rank should be as small as possible.
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn array_rank_transform(arr: Vec<i32>) -> Vec<i32> {
if arr.is_empty() { return vec![]; }
let mut sorted = arr.clone();
sorted.sort();
sorted.dedup();
let rank: std::collections::HashMap<i32, i32> = sorted.iter().enumerate()
.map(|(i, &v)| (v, i as i32 + 1)).collect();
arr.iter().map(|v| rank[v]).collect()
}
}