#2191

Sort the Jumbled Numbers

Medium
ArraySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution efficiently maps and sorts the numbers in a single pass using a custom sort function. This approach minimizes the number of passes over the data and leverages Python's built-in sorting capabilities, ensuring we maintain the original order for equal mapped values.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a function to map each digit of a number using the mapping array.
  2. 2Step 2: Use the built-in sort function with a custom key that maps the numbers and maintains their original indices.
  3. 3Step 3: Return the sorted numbers based on their mapped values.
solution.py12 lines
1# Full working Python code
2
3def map_number(num, mapping):
4    return int(''.join(str(mapping[int(digit)]) for digit in str(num)))
5
6def sort_jumbled_numbers(mapping, nums):
7    return sorted(nums, key=lambda x: (map_number(x, mapping), nums.index(x)))
8
9# Example usage
10mapping = [8,9,4,0,2,1,3,5,7,6]
11nums = [991,338,38]
12print(sort_jumbled_numbers(mapping, nums))

Complexity note: The time complexity is O(n log n) due to the sorting step. The mapping of each number is O(n), but since sorting dominates the complexity, the overall complexity is O(n log n).

  • 1Mapping digits correctly is crucial for accurate sorting.
  • 2Maintaining relative order for equal mapped values can be achieved using indices.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.