[LeetCode] Query Kth Smallest Trimmed Number

2343. Query Kth Smallest Trimmed Number

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int helper(vector<string>& A, int k, int cut) {
vector<pair<string, int>> B;
for(int i = 0; i < A.size(); i++) {
B.push_back({A[i].substr(A[i].length() - cut), i});
}
sort(begin(B), end(B));
return B[k-1].second;
}
public:
vector<int> smallestTrimmedNumbers(vector<string>& nums, vector<vector<int>>& queries) {
vector<int> res;
for(auto& q : queries) {
res.push_back(helper(nums, q[0], q[1]));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/18/PS/LeetCode/query-kth-smallest-trimmed-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.