Skip to main content

Query Kth Smallest Trimmed Number - Solution & Explanation

MediumArrayStringDivide and ConquerSorting17 min readAsked at: De Shaw
Practice this problem

Problem Statement

You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits.

You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to:

  • Trim each number in nums to its rightmost trimi digits.
  • Determine the index of the kith smallest trimmed number in nums. If two trimmed numbers are equal, the number with the lower index is considered to be smaller.
  • Reset each number in nums to its original length.

Return an array answer of the same length as queries, where answer[i] is the answer to the ith query.

Note:

  • To trim to the rightmost x digits means to keep removing the leftmost digit, until only x digits remain.
  • Strings in nums may contain leading zeros.

 

Example 1:

Input: nums = ["102","473","251","814"], queries = [[1,1],[2,3],[4,2],[1,2]]
Output: [2,2,1,0]
Explanation:
1. After trimming to the last digit, nums = ["2","3","1","4"]. The smallest number is 1 at index 2.
2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2.
3. Trimmed to the last 2 digits, nums = ["02","73","51","14"]. The 4th smallest number is 73.
4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.
   Note that the trimmed number "02" is evaluated as 2.

Example 2:

Input: nums = ["24","37","96","04"], queries = [[2,1],[2,2]]
Output: [3,0]
Explanation:
1. Trimmed to the last digit, nums = ["4","7","6","4"]. The 2nd smallest number is 4 at index 3.
   There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.
2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.

 

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i].length <= 100
  • nums[i] consists of only digits.
  • All nums[i].length are equal.
  • 1 <= queries.length <= 100
  • queries[i].length == 2
  • 1 <= ki <= nums.length
  • 1 <= trimi <= nums[i].length

 

Follow up: Could you use the Radix Sort Algorithm to solve this problem? What will be the complexity of that solution?

Approach Overview

Problem Overview: You are given an array of equal-length numeric strings. Each query asks you to trim every number to its last trim digits, then return the index of the k-th smallest trimmed value. If two trimmed numbers are equal, the smaller original index wins. Each query works independently, so the challenge is efficiently comparing many trimmed substrings.

Approach 1: Simple Sorting Approach (O(q · n log n) time, O(n) space)

The direct approach processes every query independently. For a query [k, trim], iterate through the array and extract the last trim digits from each string using substring operations. Store pairs of (trimmed_value, index). Sort this list lexicographically by the trimmed value, and break ties using the index. The answer for the query is the index at position k-1 after sorting.

This method relies on standard sorting and works well when the number of queries or numbers is small. The downside is repeated work: the same trims may be recomputed many times. If there are q queries and n numbers, sorting for each query leads to O(q · n log n) time. Still, the logic is straightforward and easy to implement in any language.

Approach 2: Optimized Bucket Sort Method (Radix Style) (O(m · n) time, O(n) space)

A faster solution observes that trimming always keeps the suffix of the number. Instead of recomputing trims for every query, process digits from right to left using a radix-style technique. Maintain an ordered list of indices representing numbers sorted by their last t digits. For each additional digit position, perform a stable bucket/counting sort based on the next digit to the left.

Because digits range from 0–9, each step distributes indices into 10 buckets, preserving previous order. After processing t digits, the list represents numbers sorted by their last t digits. Store this ordering so queries asking for that trim length can directly access the k-1 position. This technique is essentially a specialized radix sort applied to numeric strings.

The preprocessing runs for at most the number length m, and each pass processes all n numbers, giving O(m · n) time. Query answers become constant time lookups. The idea combines properties of arrays and stable bucket sorting to avoid repeated comparisons.

Recommended for interviews: Start by describing the simple sorting approach. It demonstrates understanding of trimming logic, lexicographic comparison, and tie-breaking with indices. Then explain the radix-style bucket optimization. Interviewers typically expect the optimized idea because it avoids redundant sorting and shows familiarity with digit-based sorting techniques.

Approach 1: Simple Sorting Approach

The simple approach involves trimming the numbers based on each query and then sorting them to find the k-th smallest element. We will trim each number, pair it with its original index, sort the list of pairs, and select the k-th smallest element by considering the first k elements of the sorted list.

This C solution works by first trimming the numbers based on the given number of digits specified in each query, then sorting the resultant numbers while keeping track of their original positions. We use the qsort function for sorting the trimmed numbers with their original indices, ensuring any ties during sorting are resolved using the original indices.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(Q * N * log(N)), where Q is the number of queries, and N is the number of numbers in the input list.
Space Complexity: O(N), which is needed to store the trimmed numbers for comparison and the original indices.

Try this approach in the editor →

Approach 2: Optimized Bucket Sort Method

For this approach, we leverage the Radix Sort when nums is restricted by the constraints given the uniformity and limited set size, specifically using the properties of counting sort, given that precision can be limited to 10 digits (0-9). We'll create buckets to sort the numbers efficiently for each trim and query.

In this C example, we use radix sort, which is a non-comparison-based sorting algorithm that groups numbers (or strings) based on digits. The solution applies a counting sort for each digit position, starting from the least significant digit. Although radix sort typically operates efficiently with integer representations, constraints on string lengths allow this adaptation.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(D * (N + B)), where D is the maximum number of digits in nums, N is the number of strings, and B is the maximum value within a single bucket.
Space Complexity: O(N), for storing temporary ordering.

Try this approach in the editor →

Approach 3: Simulation

According to the problem description, we can simulate the cropping process, then sort the cropped strings, and finally find the corresponding number based on the index.

The time complexity is O(m times n times log n times s), and the space complexity is O(n). Here, m and n are the lengths of nums and queries respectively, and s is the length of the string nums[i].

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Simple Sorting Approach

Time Complexity: O(Q * N * log(N)), where Q is the number of queries, and N is the number of numbers in the input list.
Space Complexity: O(N), which is needed to store the trimmed numbers for comparison and the original indices.

Optimized Bucket Sort Method

Time Complexity: O(D * (N + B)), where D is the maximum number of digits in nums, N is the number of strings, and B is the maximum value within a single bucket.
Space Complexity: O(N), for storing temporary ordering.

Simulation

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Simple SortingO(q · n log n)O(n)Best for quick implementation or when constraints are small
Bucket Sort (Radix Style)O(m · n)O(n)Preferred for large inputs or many queries; avoids repeated sorting

Video Solution

Leetcode Weekly contest 302 - Medium - Query Kth Smallest Trimmed NumberPrakhar Agrawal1,131 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Query Kth Smallest Trimmed Number easy or hard?
Query Kth Smallest Trimmed Number is generally rated Medium. The brute-force sorting idea is straightforward, but recognizing that multiple queries share overlapping trims and can be optimized with radix-style sorting makes the problem more challenging.
Query Kth Smallest Trimmed Number Python/Java solution
In Python or Java, the basic solution builds a list of (trimmed_string, index) pairs and sorts them using built-in sorting functions. The optimized solution implements counting or bucket sort on digits while storing index order for each trim length.
How to solve Query Kth Smallest Trimmed Number in O(n)?
Use a radix-style approach with bucket or counting sort on digits. Starting from the rightmost digit, repeatedly group indices by digit values (0–9) while maintaining stable order. After processing t digits, the array is sorted by the last t digits, allowing constant-time lookup for queries with trim = t.
What is the best approach for Query Kth Smallest Trimmed Number?
The most efficient approach uses a radix-style bucket sort. Process digits from right to left and maintain the order of indices using stable counting sort. After computing sorted orders for each trim length, every query can be answered by directly selecting the k-1 index. This reduces repeated sorting and runs in O(m · n) time.
Is Query Kth Smallest Trimmed Number asked at Google/Amazon/Meta?
This problem reflects patterns commonly asked in large tech interviews, especially questions involving sorting strings, radix sort, and query preprocessing. Similar problems appear in companies like Amazon and Google where candidates must optimize repeated queries over arrays.
What data structure is used in Query Kth Smallest Trimmed Number?
The problem primarily uses arrays and sorting techniques. The optimized solution relies on bucket arrays for counting sort and maintains ordered lists of indices. These structures help simulate radix sort over numeric strings.
What is the time complexity of Query Kth Smallest Trimmed Number?
The straightforward solution sorts the trimmed numbers for every query, giving O(q · n log n) time and O(n) space. The optimized radix-style bucket method processes digits incrementally and runs in O(m · n) time, where m is the length of each number string.

Ready to solve this problem?

Practice Query Kth Smallest Trimmed Number with our built-in code editor and test cases.

Practice on FleetCode