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 ki-th 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 i-th 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.

Input & Output

Example 1 — Basic Trimming
$ Input: nums = ["102","473","251","814"], queries = [[1,1],[2,3],[4,2],[1,2]]
Output: [2,2,1,0]
💡 Note: Query [1,1]: trim=1 gives ["2","3","1","4"], 1st smallest is "1" at index 2. Query [2,3]: trim=3 gives ["102","473","251","814"], 2nd smallest is "251" at index 2. Query [4,2]: trim=2 gives ["02","73","51","14"], 4th smallest is "73" at index 1. Query [1,2]: trim=2 gives ["02","73","51","14"], 1st smallest is "02" at index 0.
Example 2 — Leading Zeros
$ Input: nums = ["24","37","96","04"], queries = [[2,1],[2,2]]
Output: [3,0]
💡 Note: Query [2,1]: trim=1 gives ["4","7","6","4"], sorted: ["4","4","6","7"]. Second smallest "4" is at index 3 (lower index wins tiebreaker). Query [2,2]: trim=2 gives ["24","37","96","04"], sorted: ["04","24","37","96"]. Second smallest is "24" at index 0.

Constraints

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

Visualization

Tap to expand
Query Kth Smallest Trimmed Number ProblemInput: nums = ["102", "473", "251", "814"], query = [2, 1]Step 1: Original Numbers with Indices"102""473""251""814"index 0index 1index 2index 3↓ Trim to rightmost 1 digit (trim=1) ↓"2""3""1""4"↓ Sort by trimmed value, preserve indices ↓"1""2""3""4"idx 2idx 0idx 1idx 3k=2nd smallest → Answer: index 0
Understanding the Visualization
1
Input
Array of equal-length digit strings and queries [k, trim]
2
Process
Trim each string to rightmost 'trim' digits, sort with indices
3
Output
Return original index of k-th smallest trimmed number
Key Takeaway
🎯 Key Insight: Trim strings to specified length, then sort while tracking original indices for the answer
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen