-
Notifications
You must be signed in to change notification settings - Fork 0
/
kthDistinct.py
52 lines (39 loc) · 1.48 KB
/
kthDistinct.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
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.
Example 1:
Input: arr = ["d","b","c","b","c","a"], k = 2
Output: "a"
> Explanation:
The only distinct strings in arr are "d" and "a".
"d" appears 1st, so it is the 1st distinct string.
"a" appears 2nd, so it is the 2nd distinct string.
Since k == 2, "a" is returned.
Example 2:
Input: arr = ["aaa","aa","a"], k = 1
Output: "aaa"
> Explanation:
All strings in arr are distinct, so the 1st string "aaa" is returned.
Example 3:
Input: arr = ["a","b","a"], k = 3
Output: ""
> Explanation:
The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "".
*My solution stats*
Runtime: 72 ms, faster than 83.31% of Python3 online submissions for Kth Distinct String in an Array.
Memory Usage: 14.2 MB, less than 64.97% of Python3 online submissions for Kth Distinct String in an Array.
"""
class Solution:
def kthDistinct(self, arr: list[str], k: int) -> str:
memo = {}
for i in arr:
if i in memo:
memo[i] += 1
else:
memo[i] = 1
output = [j for j in memo if memo[j] == 1]
if len(output) < k:
return ""
return output[k - 1]