Leetcode 2343: Query Kth Smallest Trimmed Number

grid47
grid47
Exploring patterns and algorithms
Mar 17, 2024 5 min read

You are given a list nums where each string contains digits of the same length. Additionally, you are provided a list of queries, where each query is represented by two integers [ki, trimi]. For each query, trim each number in nums to its rightmost trimi digits, then find the index of the kith smallest trimmed number. If two numbers are identical after trimming, the one with the lower index is considered smaller. Reset the numbers in nums for the next query.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `nums` of strings and an array `queries` of queries, where each query is a pair `[ki, trimi]`.
Example: nums = ["203", "102", "114", "319"], queries = [[2, 1], [1, 3], [3, 2]]
Constraints:
• 1 <= nums.length <= 100
• 1 <= nums[i].length <= 100
• 1 <= queries.length <= 100
• 1 <= ki <= nums.length
• 1 <= trimi <= nums[i].length
Output: Return an array `answer` where each element corresponds to the answer of the respective query. Each answer should be the index of the `ki`th smallest number in the trimmed list.
Example: [1, 2, 0]
Constraints:
Goal: The goal is to trim the numbers in `nums` according to the query's specification, sort the trimmed numbers, and return the index of the `ki`th smallest number.
Steps:
• For each query, trim all numbers in `nums` to the rightmost `trimi` digits.
• Sort the numbers based on the trimmed version, with ties broken by the original index.
• Find the index of the `ki`th smallest number in the sorted list and add it to the result.
Goal: The constraints ensure that each number in `nums` has the same length and there are at most 100 numbers in `nums`.
Steps:
• 1 <= nums.length <= 100
• 1 <= nums[i].length <= 100
• 1 <= queries.length <= 100
• 1 <= ki <= nums.length
• 1 <= trimi <= nums[i].length
Assumptions:
• The input `nums` consists of valid strings representing numbers.
• Each query consists of two integers: `ki` and `trimi`.
Input: nums = ["203", "102", "114", "319"], queries = [[2, 1], [1, 3], [3, 2]]
Explanation: For the first query, after trimming the numbers to the last digit, we get ["3", "2", "4", "9"]. The second smallest number is 2, which is at index 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus