Sort the Jumbled Numbers - Problem
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 in the integer with mapping[i] for all 0 <= i <= 9.
You are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements.
Note: Elements with the same mapped values should appear in the same relative order as in the input.
Input & Output
Example 1 — Basic Case
$
Input:
mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]
›
Output:
[338,38,991]
💡 Note:
991 maps to 669, 338 maps to 007 (which is 7), 38 maps to 07 (which is 7). Since 7 < 669, both 338 and 38 come before 991. Since 338 and 38 have the same mapped value, they maintain their original relative order.
Example 2 — Different Mapping
$
Input:
mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]
›
Output:
[123,456,789]
💡 Note:
With identity mapping, numbers stay the same: 789→789, 456→456, 123→123. Sorted: [123,456,789].
Example 3 — All Same Mapped Value
$
Input:
mapping = [1,1,1,1,1,1,1,1,1,1], nums = [12,21,3]
›
Output:
[12,21,3]
💡 Note:
All numbers map to same digits (1): 12→11, 21→11, 3→1. Since all mapped values are different (11, 11, 1), sort by mapped values: 3 maps to 1, others to 11, so [3,12,21]. But 12 and 21 both map to 11, so original order preserved.
Constraints
- mapping.length == 10
- 0 ≤ mapping[i] ≤ 9
- All the values of mapping[i] are unique
- 1 ≤ nums.length ≤ 3 × 104
- 0 ≤ nums[i] < 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original array with digit mapping rule
2
Transform
Map each digit to create new values
3
Sort
Sort by mapped values, preserve original order for ties
Key Takeaway
🎯 Key Insight: Transform numbers using digit mapping, then sort by transformed values while maintaining stability for equal mapped values
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code