Query Kth Smallest Trimmed Number
Here’s an algorithm to implement the described function:
- Iterate through the queries.
- For each query, trim the strings in
nums
to their rightmost trimi
digits. - Sort the trimmed numbers along with their original indices.
- Find the kith smallest number and record its original index.
- Reset the numbers in
nums
to their original length. - Return the collected results.
Python code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| class Solution:
def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]:
answer = []
original_nums = nums.copy() # Copy of original nums for resetting
for k, trim in queries:
# Trim the numbers to the rightmost `trim` digits
trimmed_nums = [int(num[-trim:]) for num in nums]
# Pair trimmed numbers with their original indices
paired_nums = list(zip(trimmed_nums, range(len(nums))))
# Sort the pairs by the trimmed number and then by index
paired_nums.sort()
# Find the index of the kth smallest trimmed number
answer.append(paired_nums[k-1][1])
# Reset the nums to original
nums = original_nums.copy()
return answer
|
This code takes in a list of strings and a list of queries, applies the trimming operation as described, and returns the required results as a list of integers.