2191. Sort the Jumbled Numbers
UnknownView on LeetCode
Time: O(n log n)
Space: O(n)
Problem Overview
Sort the Jumbled Numbers (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Map each number through digit mapping; stable sort by mapped value.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Map each number through digit mapping; stable sort by mapped value.
Related patterns: Array, Hash Table, Sorting
2191.cs
C#
// Approach: Map each number through digit mapping; stable sort by mapped value.
// Time: O(n log n) Space: O(n)
public class Solution
{
public int[] SortJumbled(int[] mapping, int[] nums)
{
int n = nums.Length;
int[] ans = new int[n];
List<int[]> pair = new List<int[]>();
for (int i = 0; i < n; i++)
pair.Add(new int[] { GetMapped(nums[i], mapping), i, nums[i] });
pair.Sort((a, b) => a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
return pair.Select(x => x[2]).ToArray();
}
private int GetMapped(int val, int[] mapping)
{
var sb = new StringBuilder();
foreach (char c in val.ToString())
sb.Append(mapping[c - '0']);
return int.Parse(sb.ToString());
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)