Skip to main content
Back to problems
#2191
Medium Algorithms

Sort the jumbled numbers

Array Sorting
60.0% acceptance
Feb 25, 2026
957
140
You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system. The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i with mapping[i]. Return the array nums sorted in non-decreasing order based on the mapped values of its elements. Elements with the same mapped values should appear in the same relative order as in the input.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn sort_jumbled(mapping: Vec<i32>, nums: Vec<i32>) -> Vec<i32> {
    let map_num = |mut n: i32| -> i32 {
      if n == 0 {
        return mapping[0];
      }
      let mut result = 0i64;
      let mut mul = 1i64;
      while n > 0 {
        result += mapping[(n % 10) as usize] as i64 * mul;
        mul *= 10;
        n /= 10;
      }
      result as i32
    };
    let mut indexed: Vec<(i32, usize)> = nums.iter().enumerate().map(|(i, &v)| (map_num(v), i)).collect();
    indexed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    indexed.iter().map(|&(_, i)| nums[i]).collect()
  }
}