Skip to main content
Back to problems
#1636
Easy Algorithms

Sort array by increasing frequency

Array Hash Table Sorting
80.7% acceptance
Feb 25, 2026
3702
179
Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

impl Solution {
  pub fn frequency_sort(mut nums: Vec<i32>) -> Vec<i32> {
    let mut freq: HashMap<i32, i32> = HashMap::new();
    for &n in &nums { *freq.entry(n).or_insert(0) += 1; }
    nums.sort_by(|a, b| {
      let fa = freq[a];
      let fb = freq[b];
      fa.cmp(&fb).then(b.cmp(a))
    });
    nums
  }
}