Skip to content

2053. Kth Distinct String in an Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  string kthDistinct(vector<string>& arr, int k) {
    unordered_map<string, int> count;

    for (const string& a : arr)
      ++count[a];

    for (const string& a : arr)
      if (count[a] == 1 && --k == 0)
        return a;

    return "";
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public String kthDistinct(String[] arr, int k) {
    Map<String, Integer> count = new HashMap<>();

    for (final String a : arr)
      count.merge(a, 1, Integer::sum);

    for (final String a : arr)
      if (count.get(a) == 1 && --k == 0)
        return a;

    return "";
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def kthDistinct(self, arr: list[str], k: int) -> str:
    count = collections.Counter(arr)

    for a in arr:
      if count[a] == 1:
        k -= 1
        if k == 0:
          return a

    return ''