A string is distinct if it appears exactly once in the array. The simplest approach is to check each string against all other strings. For each position, we scan the entire array to see if that string appears anywhere else. If not, it's distinct, and we decrement our counter until we find the k-th one.
i.j to see if there's a duplicate.k.k reaches 0, return the current string.k distinct ones, return an empty string.Instead of repeatedly scanning the array, we can count occurrences upfront using a hash map. In the first pass, we count how many times each string appears. In the second pass, we iterate in order and check if each string has a count of exactly 1. This reduces time complexity from O(n^2) to O(n).
1, decrement k.k becomes 0, or return an empty string if not found.We can use two sets instead of a counting map. One set tracks strings that are currently distinct (seen exactly once), and another tracks strings we've already identified as duplicates. When we encounter a string, if it's in the distinct set, we move it to the seen set (it's no longer distinct). If it's not in either set, we add it to distinct. This achieves the same result with a slightly different data structure.
distinct for unique strings and seen for duplicates.distinct, move it to seen (it's now a duplicate).seen, add it to distinct.distinct set, decrement k.k reaches 0.class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
distinct, seen = set(), set()
for s in arr:
if s in distinct:
distinct.remove(s)
seen.add(s)
elif s not in seen:
distinct.add(s)
for s in arr:
if s in distinct:
k -= 1
if k == 0:
return s
return ""The k-th distinct string must be found in the original array order, not in any arbitrary order. A common mistake is collecting all distinct strings into a set and then trying to find the k-th one, but sets do not preserve insertion order in all languages. Always iterate through the original array in order when finding the k-th distinct string.
If there are fewer than k distinct strings in the array, the function should return an empty string. Forgetting to handle this edge case or returning the last found distinct string instead of an empty string leads to incorrect results. Always check if k reaches zero before returning, and return empty string if the loop completes without finding enough distinct strings.