Problem 2191

Abstract / Summary

Given jumbled versions of numbers with unique digit patterns, return the sorted order of the original numbers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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) ]
12 lines | 409 bytes | submitted May 22, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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) - zero yields 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.
  • have is 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.15 | σ = 1.20

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
26 links | 12 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 solutions   May 22, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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