#2343
Query Kth Smallest Trimmed Number
MediumApproaches
💡
Intuition
Time O(n² log n)Space O(n)
The brute force approach involves trimming the numbers for each query, sorting them, and then finding the k-th smallest trimmed number. It's straightforward but inefficient for larger inputs.
⚙️
Algorithm
4 steps- 1Step 1: For each query, trim each number in nums to the specified number of rightmost digits.
- 2Step 2: Pair each trimmed number with its original index.
- 3Step 3: Sort the pairs based on the trimmed numbers, and if they are equal, sort by the original index.
- 4Step 4: Retrieve the index of the k-th smallest trimmed number from the sorted list.
solution.py7 lines
1def smallestTrimmedNumbers(nums, queries):
2 result = []
3 for k, trim in queries:
4 trimmed = [(num[-trim:], i) for i, num in enumerate(nums)]
5 trimmed.sort()
6 result.append(trimmed[k-1][1])
7 return resultℹ
Complexity note: The complexity arises from sorting the trimmed numbers for each query, leading to O(n log n) for sorting and O(n) for creating the list, repeated for each query.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.