2191. Sort the Jumbled Numbers - Explanation
Description
Replace each decimal digit d of a number with mapping[d] to obtain its mapped value. Leading zeros in this new value do not affect its numeric value. Sort nums by these mapped values in nondecreasing order and return the original numbers in that order. When mapped values are equal, preserve the numbers' original relative order. Treat the number 0 as a single digit, so its mapped value is mapping[0].
Example 1:
Input: mapping = [1,0,2,3,4,5,6,7,8,9]
nums = [10,0,1,100]
Output: [1,10,0,100]Explanation: The mapped values of 10, 0, 1, and 100 are 1, 1, 0, and 11. Put 1 first, keep 10 before 0 because their mapped values tie, and put 100 last.
Example 2:
Input: mapping = [9,8,7,6,5,4,3,2,1,0]
nums = [9,99,999,0]
Output: [9,99,999,0]Explanation: The values 9, 99, and 999 all map to zero, so their original order is preserved. The original number 0 maps to 9 and comes last.
Example 3:
Input: mapping = [0,1,2,3,4,5,6,7,8,9]
nums = [12,3,12,0]
Output: [0,3,12,12]Explanation: Every digit maps to itself, so this is ordinary numeric sorting. The repeated value 12 is retained twice.
Constraints:
mappingis a permutation of the digits from0through9.1 <= nums.length <= 300000 <= nums[i] < 1000000000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Custom Comparators - Writing comparison functions to define custom sorting orders
- Digit Manipulation - Extracting and transforming individual digits using modulo and division
- Stable Sorting - Understanding that stable sorts preserve relative order of equal elements
- String/Number Conversion - Converting between numeric and string representations
1. Convert To Strings + Sorting
Intuition
We need to sort numbers based on their "mapped" values, where each digit is replaced according to a mapping array. By converting each number to a string, we can easily iterate through its digits and build the mapped value. We store each mapped value along with the original index to preserve relative ordering for equal mapped values, then sort by the mapped values.
Algorithm
- For each number in the input array, convert it to a string.
- Build the
mappedvalue by iterating through each character, looking up its mapped digit, and constructing the new number. - Store pairs of (
mappedvalue, original index) for each number. - Sort the pairs by
mappedvalue. Since the sort is stable, equalmappedvalues will maintain their original relative order. - Construct the result array by extracting the original numbers using the stored indices.
class Solution:
def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:
pairs = []
for i, n in enumerate(nums):
n = str(n)
mapped_n = 0
for c in n:
mapped_n *= 10
mapped_n += mapping[int(c)]
pairs.append((mapped_n, i))
pairs.sort()
return [nums[p[1]] for p in pairs]Time & Space Complexity
- Time complexity:
- Space complexity:
2. Iterate On Numbers + Sorting
Intuition
Instead of converting numbers to strings, we can extract digits directly using arithmetic operations. We repeatedly take the last digit using modulo, map it, and accumulate the mapped value by multiplying by the appropriate power of 10. This avoids the overhead of string conversion while achieving the same result.
Algorithm
- For each number, initialize a
mappedvalue of0and abasemultiplier of1. - Handle the special case where the number is
0by directly using the mapped value of digit0. - Otherwise, repeatedly extract the last digit using modulo
10, map it, multiply by the currentbase, and add to themappedvalue. Then divide the number by10and multiply thebaseby10. - Store pairs of (
mappedvalue, original index). - Sort pairs by
mappedvalue and construct the result using the stored indices.
class Solution:
def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:
pairs = []
for i, n in enumerate(nums):
mapped_n = 0
base = 1
if n == 0:
mapped_n = mapping[0]
else:
while n > 0:
digit = n % 10
n //= 10
mapped_n += base * mapping[digit]
base *= 10
pairs.append((mapped_n, i))
pairs.sort()
return [nums[p[1]] for p in pairs]Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Not Handling Zero as a Special Case
When using arithmetic to extract digits, the number zero requires special handling. The while loop while (n > 0) never executes for zero, leaving the mapped value uninitialized. You must explicitly handle n == 0 by directly using mapping[0].
Using an Unstable Sort Without Preserving Original Order
The problem requires that elements with equal mapped values maintain their original relative order. Using an unstable sort without tracking original indices will produce incorrect results when multiple numbers map to the same value.
Integer Overflow When Building Mapped Values
For very large numbers, the mapped value can potentially overflow. While this is less common in languages with arbitrary precision integers like Python, in languages like Java or C++ you should be aware of the maximum input constraints to ensure the mapped value fits within the integer type.
Sign in to join the discussion