[LeetCode] Kth Distinct String in an Array

2053. Kth Distinct String in an Array

A distinct string is a string that is present only once in an array.

Given an array of strings arr, and an integer k, return the kth *distinct string present in arr. If there are fewer than k distinct strings, return an empty string* "".

Note that the strings are considered in the order in which they appear in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string kthDistinct(vector<string>& arr, int k) {
unordered_map<string, int> freq;
for(auto& s : arr) freq[s]++;
for(auto& s : arr) {
if(freq[s] == 1) {
if(--k == 0) return s;
}
}
return "";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/05/PS/LeetCode/kth-distinct-string-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.