|
1 | 1 | # [Problem 2053: Kth Distinct String in an Array](https://leetcode.com/problems/kth-distinct-string-in-an-array/description/?envType=daily-question)
|
2 | 2 |
|
3 | 3 | ## Initial thoughts (stream-of-consciousness)
|
| 4 | +- This seems straightforward |
| 5 | +- Let's keep a `set` containing all of the unique strings |
| 6 | +- We'll loop through `arr`, incrementing a counter each time we encounter a new unique string, and then we'll add the unique string to the set |
| 7 | +- Once the counter gets to `k` we'll return that string |
| 8 | +- If we never reach `k` but we run out of elements of `arr`, we return an empty string |
4 | 9 |
|
5 | 10 | ## Refining the problem, round 2 thoughts
|
| 11 | +- I'm not sure if it'd be faster to use a set or hash table to track unique strings...but I'll go with a set |
| 12 | +- I think I'm ready to implement this... |
6 | 13 |
|
7 | 14 | ## Attempted solution(s)
|
8 | 15 | ```python
|
9 |
| -class Solution: # paste your code here! |
10 |
| - ... |
| 16 | +class Solution: |
| 17 | + def kthDistinct(self, arr: List[str], k: int) -> str: |
| 18 | + unique_strings = set() |
| 19 | + counter = 0 |
| 20 | + for s in arr: |
| 21 | + if s not in unique_strings: |
| 22 | + counter += 1 |
| 23 | + if counter == k: |
| 24 | + return s |
| 25 | + unique_strings.add(s) |
| 26 | + return "" |
11 | 27 | ```
|
| 28 | +- Ok, the first test case is failing-- I seem to have read the problem incorrectly. It looks like we also need consider *future* instances of each string (not just the first occurance that is unique *up to that point* in the list). |
| 29 | +- So I think we can just use a hash table to count up the number of occurances of each string in `arr` |
| 30 | +- Then we can loop through `arr` and increment a counter until we hit the `k`th string with only one occurance: |
| 31 | + |
| 32 | + |
| 33 | +```python |
| 34 | +class Solution: |
| 35 | + def kthDistinct(self, arr: List[str], k: int) -> str: |
| 36 | + counts = {} |
| 37 | + for s in arr: |
| 38 | + if s not in counts: |
| 39 | + counts[s] = 1 |
| 40 | + else: |
| 41 | + counts[s] += 1 |
| 42 | + |
| 43 | + counter = 0 |
| 44 | + for s in arr: |
| 45 | + if counts[s] == 1: |
| 46 | + counter += 1 |
| 47 | + if counter == k: |
| 48 | + return s |
| 49 | + return "" |
| 50 | +``` |
| 51 | +- Now the test cases pass |
| 52 | +- I can't think of any useful edge cases off the top of my head, so I'll just submit 🙂 |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | +Solved! |
0 commit comments