Ctrl K

K-th Code by Its Last Digits

Medium
In a warehouse every item carries a digit code. The codes are in the string array codes; they all have the same length and may start with zeros. You are given queries queries, where queries[i] = [k, t]. To answer one, keep only the last t digits of every code and compare the resulting numbers ("02" is just 2). Find the k-th smallest code (counting from 1) and record its index in codes. When two shortened codes are equal, the one with the lower index counts as smaller. Queries are independent: each one starts from the full codes. Return the answers in query order.
Example 1
codes=['5071', '1203', '9902'], queries=[[1, 2], [3, 1], [2, 4]] → [2, 1, 0]

Using the last two digits we get 71, 03 and 02, so the smallest is index 2. Using the last digit: 1, 3, 2, and the third smallest is index 1. In full: 1203 < 5071 < 9902, and the second is index 0.

Example 2
codes=['40', '30', '10'], queries=[[2, 1]] → [1]

Every code ends in 0, so the indices break the tie: 0, 1, 2. The second one is index 1.

Constraints
  • 1 ≤ codes.length ≤ 100
  • 1 ≤ codes[i].length ≤ 100, all codes have the same length
  • codes[i] consists of digits only
  • 1 ≤ queries.length ≤ 100
  • queries[i].length == 2
  • 1 ≤ k ≤ codes.length
  • 1 ≤ t ≤ codes[i].length
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsK-th Biggest Long Number MediumK-th Highest Score MediumMost Common Values MediumHand-Rolled Sort MediumNearest Points to the Base Medium
loading Python…
Input
codes=['5071', '1203', '9902'], queries=[[1, 2], [3, 1], [2, 4]]
Expected
[2, 1, 0]

Run checks the first 3 tests in your browser. Submit checks all 88 tests on the server, hidden ones included.