Python 2191.py
class Solution:
def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:
result = []
zero = ord("0")
for i, n in enumerate(nums):
have = 0
for c in str(n):
have *= 10
have += mapping[ord(c) - zero]
result.append(( have, i, n ))
return [ n for have, i, n in sorted(result) ]
Difficulty
and has an acceptance rate of about 60% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method sortJumbled. The method receives a digit-to-digit mapping and a list of integers. It transforms each integer by replacing every digit with its mapped counterpart, then returns the original integers ordered by the value of their transformed representation. The algorithm preserves the relative order of numbers that map to the same transformed value.
Key Steps
Preparing the transformation environment
zero = ord("0")
The ASCII code of the character '0' is stored once in the variable zero. By reusing this value, the code avoids repeated calls to ord("0") inside the inner loop, reducing the overhead of character-to-integer conversion.
Iterating over the input numbers
for i, n in enumerate(nums):
enumerate supplies both the current index i and the number n. The index is later used to break ties when two numbers produce identical transformed values, ensuring a stable ordering without an extra pass.
Building the transformed value
have = 0
for c in str(n):
have *= 10
have += mapping[ord(c) - zero]
Each integer n is converted to its string representation, allowing digit-wise processing. For every character c:
ord(c) - zeroyields the numeric digit (0-9) by subtracting the ASCII code of'0'.- The digit is used as an index into
mapping, retrieving the mapped digit. haveis multiplied by 10 and the mapped digit is added, constructing the transformed integer in base-10 order.
The loop naturally handles numbers with any number of digits, including the single-digit case and the value 0. When a digit maps to 0, the multiplication-and-addition sequence correctly inserts the zero without affecting the positional value of subsequent digits.
Recording the transformation result
result.append(( have, i, n ))
A tuple containing the transformed value have, the original index i, and the original number n is appended to result. Storing the index alongside the transformed value enables the subsequent sort to be stable: if two transformed values are equal, the tuple ordering falls back to the index, preserving the input order.
Sorting and extracting the final list
return [ n for have, i, n in sorted(result) ]
The built-in sorted function orders the list of tuples lexicographically. Because the tuple’s first element is the transformed value, the primary sort key is exactly the required ordering. The second element (the original index) automatically resolves ties. The list comprehension then extracts only the original numbers n from the sorted tuples, producing the final ordered list.
Edge Cases Handled
When a digit maps to 0, the construction of have still respects positional significance because each iteration multiplies the accumulator by 10 before adding the mapped digit. Consequently, leading zeros in the transformed representation do not affect the numeric value, but the original index ensures that numbers with identical transformed values retain their original relative order.
The conversion str(n) works for the integer 0, yielding the single character '0'. The inner loop processes this single character, resulting in a transformed value that correctly reflects the mapping for zero.
Duplicate numbers in nums are treated individually: each occurrence receives its own index, so the sorting step can differentiate them even when both the original and transformed values are identical. This guarantees that the output list contains the same multiplicity of each number as the input.
Performance Optimizations
The code minimizes repeated work by caching the ASCII code of '0' in the variable zero. This eliminates the need to compute the offset for each digit conversion, a small but measurable saving when processing large lists.
Tuple construction (have, i, n) leverages Python’s native tuple comparison for sorting, which is highly optimized in the interpreter. By placing the primary sort key first, the algorithm avoids the need for a custom comparator or additional data structures.
Using enumerate provides the original position without a separate pass over the list, and the final list comprehension extracts the desired values in a single, concise expression, avoiding an explicit loop for the result assembly.
Overall, the implementation combines straightforward digit manipulation with Python’s built-in sorting and data structures to achieve an efficient solution while maintaining clear and readable logic.
ELI5 - Simplified Explanation
Imagine you have a box of magic crayons where each color is labeled with a new name. If you want to use the color red, you have to look at your map to see what the map says red now represents.
This code acts like a translator for a list of numbers. When a number from the list comes along, the computer looks at every single digit in that number and checks the map to see what the new secret digit should be. If the map says the number nine should actually look like a two, the computer swaps it for the two.
Once every digit in the original number has been turned into its new secret digit, the number takes on a brand new value. The computer keeps track of the new value, where the number was sitting in the starting line, and what the original number looked like. After looking at all of the numbers in the list, the computer lines them all up based on their new secret values from smallest to biggest and puts them into a fresh row. The numbers that were smallest according to the magic map get to go to the front, and the ones that became biggest move to the back.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | JS | C# | Go | Rust | TS | |
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 677: Map Sum Pairs
Solved On The Same Day
- problem 2033: Minimum Operations to Make a Uni-Value Grid
- problem 2212: Maximum Points in an Archery Competition
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality