Skip to main content
Back to problems
#2231
Easy Algorithms

Largest number after digit swaps by parity

Sorting Heap (Priority Queue)
65.0% acceptance
Feb 25, 2026
691
311
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn largest_integer(num: i32) -> i32 {
    let mut digits: Vec<u32> = num.to_string().chars().map(|c| c.to_digit(10).unwrap()).collect();
    let mut odds: Vec<u32> = digits.iter().filter(|&&d| d % 2 == 1).cloned().collect();
    let mut evens: Vec<u32> = digits.iter().filter(|&&d| d % 2 == 0).cloned().collect();
    odds.sort_unstable_by(|a, b| b.cmp(a));
    evens.sort_unstable_by(|a, b| b.cmp(a));
    let mut oi = 0;
    let mut ei = 0;
    for d in &mut digits {
      if *d % 2 == 1 {
        *d = odds[oi];
        oi += 1;
      } else {
        *d = evens[ei];
        ei += 1;
      }
    }
    digits.iter().fold(0i32, |acc, &d| acc * 10 + d as i32)
  }
}