Skip to content

Commit ed18dfd

Browse files
My solution to 2053
1 parent 9609b77 commit ed18dfd

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

problems/2053/jeremymanning.md

+47-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,56 @@
11
# [Problem 2053: Kth Distinct String in an Array](https://leetcode.com/problems/kth-distinct-string-in-an-array/description/?envType=daily-question)
22

33
## 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
49

510
## 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...
613

714
## Attempted solution(s)
815
```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 ""
1127
```
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+
![Screenshot 2024-08-04 at 9 38 15 PM](https://github.com/user-attachments/assets/5f55ac90-7d67-4a04-8a3f-2cd16b52a3b1)
55+
56+
Solved!

0 commit comments

Comments
 (0)