Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2343: Query Kth Smallest Trimmed Number

In this guide, we solve Leetcode #2343 Query Kth Smallest Trimmed Number in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

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].

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, String, Divide and Conquer, Quickselect, Radix Sort, Sorting, Heap (Priority Queue)

Intuition

We need to repeatedly access the smallest or largest element as the input changes.

A heap provides fast insertions and removals while keeping order.

Approach

Push candidates into the heap as you scan, and pop when you need the best element.

Keep the heap size bounded if the problem requires a top-k structure.

Steps:

  • Push candidates into a heap.
  • Pop the best candidate when needed.
  • Maintain heap size or invariants.

Example

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.

Python Solution

class Solution: def smallestTrimmedNumbers( self, nums: List[str], queries: List[List[int]] ) -> List[int]: ans = [] for k, trim in queries: t = sorted((v[-trim:], i) for i, v in enumerate(nums)) ans.append(t[k - 1][1]) return ans

Complexity

The time complexity is O(m×n×log⁡n×s)O(m \times n \times \log n \times s)O(m×n×logn×s), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy