Skip to main content
Back to problems
#2053
Easy Algorithms

Kth distinct string in an array

Array Hash Table String Counting
82.1% acceptance
Feb 25, 2026
1313
53
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn kth_distinct(arr: Vec<String>, k: i32) -> String {
    use std::collections::HashMap;
    let mut count: HashMap<&str, usize> = HashMap::new();
    for s in &arr {
      *count.entry(s.as_str()).or_insert(0) += 1;
    }
    let mut cnt = 0;
    for s in &arr {
      if count[s.as_str()] == 1 {
        cnt += 1;
        if cnt == k {
          return s.clone();
        }
      }
    }
    String::new()
  }
}