Leetcode 2191: Sort the Jumbled Numbers

grid47
grid47
Exploring patterns and algorithms
Apr 1, 2024 7 min read

You are given a mapping array where each index represents a digit, and the value at each index represents the mapped digit in a shuffled decimal system. You are also given an integer array ’nums’. Your task is to sort the array ’nums’ in non-decreasing order based on the mapped values of each element. While sorting, the original integers in ’nums’ should not be changed, only their mapped values should be considered for sorting.
Problem
Approach
Steps
Complexity
Input: The input consists of two arrays: an integer array 'mapping' and an integer array 'nums'.
Example: Input: mapping = [2,4,0,7,1,9,6,3,8,5], nums = [352,124,718]
Constraints:
• mapping.length == 10
• 0 <= mapping[i] <= 9
• All values of mapping[i] are unique.
• 1 <= nums.length <= 3 * 10^4
• 0 <= nums[i] < 10^9
Output: Return the array 'nums' sorted in non-decreasing order based on the mapped values of the elements.
Example: Output: [124,352,718]
Constraints:
• The elements in 'nums' should be sorted based on their mapped values and not be replaced by them.
Goal: The goal is to sort the numbers in 'nums' by their mapped values, where each digit of a number is replaced by the corresponding value in the 'mapping' array.
Steps:
• For each number in 'nums', generate its mapped value by replacing each digit according to the 'mapping' array.
• Store the mapped values along with the original numbers and their indices.
• Sort the numbers based on their mapped values while preserving their original relative order when mapped values are the same.
• Return the sorted array based on the original numbers.
Goal: Conditions that the solution must meet.
Steps:
• The length of the 'mapping' array is fixed to 10.
• All values in 'mapping' are unique.
• The length of 'nums' can be up to 30,000 elements.
• Each number in 'nums' is less than 10^9.
Assumptions:
• The mapping array has unique digits, meaning no digit maps to the same value.
• The numbers in 'nums' are valid integers that follow the constraints.
Input: Input: mapping = [2,4,0,7,1,9,6,3,8,5], nums = [352,124,718]
Explanation: For each number in 'nums', the digits are mapped according to the 'mapping' array. After mapping, we get the values 822 for 352, 214 for 124, and 278 for 718. Sorting these mapped values results in the order [214,822,278], corresponding to the original numbers [124,352,718].

Input: Input: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]
Explanation: In this case, the mapping does not change the digits because mapping[i] = i. Thus, 789 maps to 789, 456 maps to 456, and 123 maps to 123. Sorting the values results in [123, 456, 789], which is the correct output.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus