Leetcode 2053. Kth Distinct String in an Array
Given an array of strings arr
and an integer k
, return the k-th distinct string in the array. If there are fewer than k
distinct strings, return an empty string.
A distinct string is a string that appears only once in the array.
arr
can vary, but for the problem constraints, assume it can be up to 1000.k
is greater than the number of distinct strings?
k
guaranteed to be a positive integer?
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
std::string kthDistinct(std::vector<std::string>& arr, int k) {
std::unordered_map<std::string, int> frequency;
// Counting the frequency of each string in the array
for (const std::string &str : arr) {
frequency[str]++;
}
// Finding the k-th distinct string
int distinct_count = 0;
for (const std::string &str : arr) {
if (frequency[str] == 1) {
++distinct_count;
if (distinct_count == k) {
return str;
}
}
}
// If there are fewer than k distinct strings
return "";
}
int main() {
std::vector<std::string> arr = {"a", "b", "a", "c", "b", "d"};
int k = 2;
std::string result = kthDistinct(arr, k);
std::cout << "The " << k << "-th distinct string is: " << result << std::endl;
return 0;
}
Thus, the overall time complexity is O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?