🔥💯🔥Detailed explanation of approach as well as code || ✅ c++ || ✅ java || ✅ python
Problem Statement:\nGiven an array mapping of length 10 where each index i maps to a digit, and an array nums of integers, you need to sort the nums array based
# Problem Statement:\nGiven an array `mapping` of length 10 where each index `i` maps to a digit, and an array `nums` of integers, you need to sort the `nums` array based on the values formed by mapping each digit of the numbers using the `mapping` array. \n\n# Intuition Behind the Solution:\n\n1. **Mapping Digits to New Values:**\n   - Each digit in a number needs to be mapped to a new digit using the `mapping` array. For example, if `mapping[0] = 2`, then the digit `0` should be replaced by `2`.\n\n2. **Transform Each Number:**\n   - For each number in `nums`, convert it to its mapped equivalent. For instance, if the number is `123` and `mapping` is `{2, 1, 4, 8, 6, 3, 0, 9, 7, 5}`, then:\n     - `1` becomes `1` (from `mapping[1]`)\n     - `2` becomes `4` (from `mapping[2]`)\n     - `3` becomes `8` (from `mapping[3]`)\n   - Thus, `123` is transformed to `148`.\n\n3. **Sort by Transformed Values:**\n   - Sort the original numbers based on their transformed values. However, if two numbers have the same transformed value, they should retain their original relative order (this is known as stable sorting).\n\n### Detailed Steps and Intuition:\n\n1. **Convert and Store Mapped Values:**\n   - Create a list of arrays where each array holds the original number, its mapped value, and its original index. This helps in:\n     - Easily sorting by the mapped values.\n     - Maintaining the original order for numbers with identical mapped values.\n\n2. **Sort the List:**\n   - Sort the list primarily by the mapped values. If two numbers have the same mapped value, use their original indices to retain their initial order (stable sorting).\n\n3. **Construct the Result:**\n   - After sorting, extract the original numbers in the new order and store them in the result array.\n\n### Example to Illustrate:\n\nGiven:\n```java\nint[] mapping = {2, 1, 4, 8, 6, 3, 0, 9, 7, 5};\nint[] nums = {990, 332, 981, 330};\n```\n\n1. **Transform Each Number:**\n   - `990` becomes `255` (`9->5`, `9->5`, `0->2`)\n   - `332` becomes `884` (`3->8`, `3->8`, `2->4`)\n   - `981` becomes `577` (`9->5`, `8->7`, `1->1`)\n   - `330` becomes `882` (`3->8`, `3->8`, `0->2`)\n\n2. **List Before Sorting:**\n   ```java\n   [ {990, 255, 0}, {332, 884, 1}, {981, 577, 2}, {330, 882, 3} ]\n   ```\n\n3. **List After Sorting:**\n   ```java\n   [ {990, 255, 0}, {981, 577, 2}, {330, 882, 3}, {332, 884, 1} ]\n   ```\n\n4. **Result:**\n   - The sorted array based on mapped values: `[990, 981, 330, 332]`\n\n# Approach\n### 1. Class and Method Definition\n\n```java\nimport java.util.*;\n\nclass Solution {\n    public int[] sortJumbled(int[] mapping, int[] nums) {\n```\n\n- **Imports:** Importing the necessary classes from the `java.util` package.\n- **Class Declaration:** Declaring the `Solution` class.\n- **Method Declaration:** Defining the `sortJumbled` method which takes two parameters: an array `mapping` and an array `nums`, and returns an array of integers.\n\n### 2. Create a List to Store Original Numbers and Their Mapped Values\n\n```java\n        List<int[]> mappedList = new ArrayList<>();\n        for (int i = 0; i < nums.length; i++) {\n            String s = Integer.toString(nums[i]);\n            StringBuilder n = new StringBuilder();\n            for (char ch : s.toCharArray()) {\n                n.append(mapping[ch - \'0\']);\n            }\n            mappedList.add(new int[]{nums[i], Integer.parseInt(n.toString()), i});\n        }\n```\n\n- **List Initialization:** `mappedList` is an `ArrayList` that will store arrays of integers. Each array will contain the original number, its mapped value, and its original index.\n- **Loop Through `nums`:** Iterate over each number in the `nums` array.\n  - **Convert to String:** Convert the current number to a string to process each digit.\n  - **Map Each Digit:** Create a new string `n` by mapping each digit of the original number using the `mapping` array.\n  - **Add to List:** Add an array containing the original number, its mapped value, and its original index to the `mappedList`.\n\n### 3. Sort the List Based on Mapped Values and Original Indices\n\n```java\n        mappedList.sort((a, b) -> {\n            if (a[1] != b[1]) {\n                return Integer.compare(a[1], b[1]);\n            } else {\n                return Integer.compare(a[2], b[2]);\n            }\n        });\n```\n\n- **Custom Sort:** Sort the `mappedList` using a lambda function:\n  - **Primary Sort by Mapped Value:** If the mapped values (`a[1]` and `b[1]`) are different, sort by these values.\n  - **Secondary Sort by Original Index:** If the mapped values are the same, sort by the original indices (`a[2]` and `b[2]`) to preserve the order of duplicates.\n\n### 4. Create and Fill the Result Array\n\n```java\n        int[] sortedNums = new int[nums.length];\n        for (int i = 0; i < mappedList.size(); i++) {\n            sortedNums[i] = mappedList.get(i)[0];\n        }\n```\n\n- **Initialize Result Array:** `sortedNums` is an array that will store the sorted original numbers.\n- **Fill Result Array:** Iterate over the `mappedList` and extract the original numbers (stored at index `0` of each array) to fill the `sortedNums` array.\n\n### 5. Return the Sorted Array\n\n```java\n        return sortedNums;\n    }\n}\n```\n\n- **Return Statement:** Return the `sortedNums` array from the `sortJumbled` method.\n# Full Code with Explanation\n\n\n```C++ []\nclass Solution {\npublic:\n    vector<int> sortJumbled(vector<int>& mapping, vector<int>& nums) {\n        // Step 1: Create a vector to store original nums and their mapped values\n        vector<tuple<int, int, int>> mappedList;\n        for (int i = 0; i < nums.size(); i++) {\n            string s = to_string(nums[i]);\n            string n = "";\n            for (char ch : s) {\n                n += to_string(mapping[ch - \'0\']);\n            }\n            mappedList.push_back(make_tuple(nums[i], stoi(n), i));\n        }\n\n        // Step 2: Sort the vector based on the mapped values and original indices for stability\n        sort(mappedList.begin(), mappedList.end(), [](const auto& a, const auto& b) {\n            if (get<1>(a) != get<1>(b)) {\n                return get<1>(a) < get<1>(b);\n            } else {\n                return get<2>(a) < get<2>(b);\n            }\n        });\n\n        // Step 3: Create a result vector and fill it with the sorted original nums\n        vector<int> sortedNums(nums.size());\n        for (int i = 0; i < mappedList.size(); i++) {\n            sortedNums[i] = get<0>(mappedList[i]);\n        }\n\n        return sortedNums;\n    }\n};\n\nint main() {\n    Solution sol;\n    vector<int> mapping = {2, 1, 4, 8, 6, 3, 0, 9, 7, 5};\n    vector<int> nums = {990, 332, 981, 330};\n    vector<int> sortedNums = sol.sortJumbled(mapping, nums);\n    for (int num : sortedNums) {\n        cout << num << " ";\n    }\n    // Output should be sorted based on mapped values, preserving order for duplicates\n    return 0;\n}\n\n```\n\n```java []\nclass Solution {\n    public int[] sortJumbled(int[] mapping, int[] nums) {\n        // Step 1: Create a list to store original nums and their mapped values\n        List<int[]> mappedList = new ArrayList<>();\n        for (int i = 0; i < nums.length; i++) {\n            String s = Integer.toString(nums[i]);\n            StringBuilder n = new StringBuilder();\n            for (char ch : s.toCharArray()) {\n                n.append(mapping[ch - \'0\']);\n            }\n            mappedList.add(new int[]{nums[i], Integer.parseInt(n.toString()), i});\n        }\n\n        // Step 2: Sort the list based on the mapped values and original indices for stability\n        mappedList.sort((a, b) -> {\n            if (a[1] != b[1]) {\n                return Integer.compare(a[1], b[1]);\n            } else {\n                return Integer.compare(a[2], b[2]);\n            }\n        });\n\n        // Step 3: Create a result array and fill it with the sorted original nums\n        int[] sortedNums = new int[nums.length];\n        for (int i = 0; i < mappedList.size(); i++) {\n            sortedNums[i] = mappedList.get(i)[0];\n        }\n\n        return sortedNums;\n    }\n}\n```\n```python []\nclass Solution:\n    def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n        # Step 1: Create a list to store original nums and their mapped values\n        mapped_list = []\n        for i, num in enumerate(nums):\n            s = str(num)\n            n = \'\'.join(str(mapping[int(ch)]) for ch in s)\n            mapped_list.append((num, int(n), i))\n\n        # Step 2: Sort the list based on the mapped values and original indices for stability\n        mapped_list.sort(key=lambda x: (x[1], x[2]))\n\n        # Step 3: Create a result list and fill it with the sorted original nums\n        sorted_nums = [t[0] for t in mapped_list]\n\n        return sorted_nums\n\n# Example usage\nsol = Solution()\nmapping = [2, 1, 4, 8, 6, 3, 0, 9, 7, 5]\nnums = [990, 332, 981, 330]\nsorted_nums = sol.sortJumbled(mapping, nums)\nprint(sorted_nums)  # Output should be sorted based on mapped values, preserving order for duplicates\n\n```\n\n![UP.png](https://assets.leetcode.com/users/images/47ffc4eb-9750-4c91-b51e-8dec6d98674f_1721786991.361689.png)\n
['Array', 'Hash Table', 'Sorting', 'Python', 'C++', 'Java']