#2053
Kth Distinct String in an Array
EasyArrayHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a HashMap to count occurrences of each string allows us to efficiently determine which strings are distinct. We can then iterate through the array a second time to collect the distinct strings in order.
⚙️
Algorithm
5 steps- 1Step 1: Create a HashMap to count occurrences of each string.
- 2Step 2: Iterate through the array and populate the HashMap with counts.
- 3Step 3: Initialize an empty list for distinct strings.
- 4Step 4: Iterate through the array again, adding strings with a count of 1 to the distinct list.
- 5Step 5: Return the k-th distinct string if it exists, otherwise return an empty string.
solution.py6 lines
1from collections import Counter
2
3def kthDistinct(arr, k):
4 count = Counter(arr)
5 distinct = [s for s in arr if count[s] == 1]
6 return distinct[k-1] if len(distinct) >= k else ''ℹ
Complexity note: The time complexity is O(n) because we traverse the array twice: once for counting and once for collecting distinct strings. The space complexity is O(n) due to the HashMap storing counts.
- 1Distinct strings are those that appear only once.
- 2The order of appearance matters when determining the k-th distinct string.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.