
Problem Statement
In this problem, you are provided with two arrays, mapping
and nums
. The array mapping
illustrates a new rule for digit representation, essentially creating a shuffled numeral system. For a given index i
in this array, mapping[i] = j
indicates that digit i
is represented as digit j
in this modified system.
The challenge involves calculating the "mapped value" of each integer in the nums
array. The mapped value is derived by replacing each digit in the number based on the mapping
provided. For example, if a digit 2
in a number should be mapped to 5
according to mapping
, all occurrences of 2
in numbers from nums
will be replaced by 5
.
Once all numbers in nums
have their corresponding mapped values calculated, your task is to return the nums
array sorted based on these mapped values. It's crucial to note that the sorting is based only on these mapped values, and the original numbers in nums
are not altered in the output; they are merely reordered. Moreover, if several numbers have the same mapped value, they need to maintain the same relative order as they appeared in the input.
Examples
Example 1
Input:
mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]
Output:
[338,38,991]
Explanation:
Map the number 991 as follows: 1. mapping[9] = 6, so all occurrences of the digit 9 will become 6. 2. mapping[1] = 9, so all occurrences of the digit 1 will become 9. Therefore, the mapped value of 991 is 669. 338 maps to 007, or 7 after removing the leading zeros. 38 maps to 07, which is also 7 after removing leading zeros. Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38. Thus, the sorted array is [338,38,991].
Example 2
Input:
mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]
Output:
[123,456,789]
Explanation:
789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789].
Constraints
mapping.length == 10
0 <= mapping[i] <= 9
- All the values of
mapping[i]
are unique. 1 <= nums.length <= 3 * 104
0 <= nums[i] < 109
Approach and Intuition
The sorting process involves several steps, each of which aligns with a critical understanding of how data is transformed and utilized:
Mapping Transformation: Convert every integer in
nums
into its corresponding mapped value based onmapping
. This involves transforming each digit of the number individually.- For instance, for
mapping = [8,9,4,0,2,1,3,5,7,6]
and a number991
fromnums
, each9
becomes6
and1
becomes9
, yielding the mapped value669
.
- For instance, for
Stability in Sorting: Because the problem specifies that multiple elements with the same mapped values should have the same relative order, a stable sorting algorithm is essential. Python's sort, for example, retains the relative order of equal elements, which can be utilized here.
Sort by Mapped Value: Once each number has been mapped, sort the list of numbers based on these new values. To sort the numbers without changing them but solely based on their mapped values:
- Pair each original number with its mapped value.
- Implement the sorting based on these paired mapped values.
- Extract and return the list containing only the original numbers, now sorted according to their mapped values.
Efficient Mapping of Digits: To convert a number quickly to its mapped form, treat the number as a string to iteratively transform each digit according to
mapping
, then convert it back to an integer for comparison purposes.
This approach guarantees that nums
is sorted according to the mapped values while adhering to any constraints related to stability and uniqueness prescribed by the problem.
Solutions
- C++
class Solution {
public:
vector<int> reorderNumbers(vector<int>& map, vector<int>& numList) {
vector<pair<int, int>> mappedNumbers;
for (int i = 0; i < numList.size(); ++i) {
int newNumber = 0;
int currentNum = numList[i];
int multiplier = 1;
if (currentNum == 0) {
mappedNumbers.push_back({map[0], i});
continue;
}
while (currentNum != 0) {
newNumber += multiplier * map[currentNum % 10];
multiplier *= 10;
currentNum /= 10;
}
mappedNumbers.push_back({newNumber, i});
}
sort(mappedNumbers.begin(), mappedNumbers.end());
vector<int> sortedNumbers;
for (auto &numPair : mappedNumbers) {
sortedNumbers.push_back(numList[numPair.second]);
}
return sortedNumbers;
}
};
This summary explains the C++ solution for sorting a list of jumbled numbers based on a given mapping. The reorderNumbers
function accepts two vectors: map
(maps each digit to a new digit) and numList
(contains the numbers to be sorted). The function implements the following steps:
- Start by creating a
vector
of pairs,mappedNumbers
, to store the mapped numbers and their original indices. - Traverse each number in
numList
:- For each number, compute its new representation using the mapping provided by
map
. - If the number is zero, directly append
{map[0], index}
tomappedNumbers
. - If not zero, decompose the number into its digits and reconstruct a new number using the mapped digits.
- Append this mapped number along with the original index to
mappedNumbers
.
- For each number, compute its new representation using the mapping provided by
- Sort
mappedNumbers
based on the mapped numbers. - Create a
vector
,sortedNumbers
, and populate it with numbers fromnumList
using the sorted order of indices frommappedNumbers
. - Finally, return
sortedNumbers
.
This solution uses straightforward number manipulation and sorting mechanism to rearrange the original numbers as per the mapping sequence, ensuring they are sorted correctly as per the transformed values.
- Java
public class Solution {
public int[] rearrangeDigits(int[] map, int[] originalArray) {
List<int[]> pairedList = new ArrayList<int[]>();
for (int idx = 0; idx < originalArray.length; idx++) {
int transformed = 0;
int number = originalArray[idx];
int weight = 1;
if (number == 0) {
pairedList.add(new int[] { map[0], idx });
continue;
}
while (number != 0) {
transformed = weight * map[number % 10] + transformed;
weight *= 10;
number /= 10;
}
pairedList.add(new int[] { transformed, idx });
}
Collections.sort(pairedList, (x, y) -> x[0] - y[0]);
int[] sortedArray = new int[originalArray.length];
for (int j = 0; j < pairedList.size(); j++) {
sortedArray[j] = originalArray[pairedList.get(j)[1]];
}
return sortedArray;
}
}
This Java solution involves sorting an array of integers according to a transformation defined by a given map
array. Here, the map
array dictates how each digit of the numbers must be transformed during sorting. Follow these steps in the code to understand the method being implemented:
- Initialize
pairedList
, a list that holds pairs consisting of the transformed number and its original index. - Iterate through each number in the
originalArray
:- Initialize variables for the transformed number (
transformed
) and its weight (weight
). - Handle the special case where the number is zero by directly mapping it to its mapped value and continue to the next iteration.
- For non-zero numbers, decompose the number digit by digit, transform each digit according to the
map
, and combine them to formtransformed
. - Add the pair of the
transformed
value and the original index to thepairedList
.
- Initialize variables for the transformed number (
- Sort
pairedList
based on the transformed values. - Extract the numbers from
originalArray
using the sorted indices intosortedArray
.
This approach rearranges the original numbers so that they follow an order dictated by the map
's transformation of their digits, effectively customizing the sorting criteria.
- Python
class Solution:
def reorder(self, mapList: List[int], elements: List[int]) -> List[int]:
mapped_pairs = []
for idx in range(len(elements)):
new_value = 0
current_element = elements[idx]
decimal_place = 1
if current_element == 0:
mapped_pairs.append((mapList[0], idx))
continue
while current_element != 0:
new_value = decimal_place * mapList[current_element % 10] + new_value
decimal_place *= 10
current_element //= 10
mapped_pairs.append((new_value, idx))
mapped_pairs.sort()
result = [elements[p[1]] for p in mapped_pairs]
return result
In the provided Python code, the task is to sort a list of numbers based on a customized mapping of digits. Below is a concise breakdown of the approach used:
- Define a class
Solution
with a methodreorder
, which accepts two lists:mapList
that contains the mapping for each digit, andelements
which is the list of numbers to be sorted. - Initiate an empty list
mapped_pairs
to store tuples of new mapped values and original indices of elements. - Iterate through each number in the
elements
list:- Calculate a new value for each number by mapping its individual digits according to
mapList
. Digits are processed from least significant to most significant due to the way integers are handled. - Utilize the modulo operator to isolate each digit of the number and the integer division to reduce the number by a factor of ten after each iteration.
- Collect the newly computed value and the original index of the number in a tuple, and append it to
mapped_pairs
.
- Calculate a new value for each number by mapping its individual digits according to
- Sort
mapped_pairs
primarily by the new mapped value. - Extract the elements in their new order, creating a sorted list based on the custom digit mapping.
- Return the sorted list, concluding the method.
This technique effectively reorders the initial list of numbers by translating each number into a new form via the provided mapping, then sorting and reversing this process to achieve the desired order. This method can be specifically useful when the sort order needs to be determined by unconventional numerical representations.
No comments yet.