Kth Distinct String in an Array - Leetcode 2053 - Python

preview_player
Показать описание


0:00 - Read the problem
0:31 - Drawing Explanation
2:31 - Coding Explanation
5:01 - Drawing Explanation 2
6:32 - Coding Explanation 2

leetcode 2053

#neetcode #leetcode #python
Рекомендации по теме
Комментарии
Автор

lol, your thumbnails are always interesting. you added a guitar cause the problem has "string" in its name xD

gmh
Автор

I just started doing leetcode recently as a beginner. Today I managed to do this problem at the first try and not in the worst way! I'm pretty happy right now :)

yohelln
Автор

Yay, I thought of and coded up the better approach for the first time. Thank you again for making these videos.

jeffhappens
Автор

In python dictionaries are Ordered after 3.7

chrischika
Автор

Yey ;) Happy for teh same solution :D

class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
mapping = Counter(arr)

for key, value in mapping.items():
if value == 1:
k -= 1
if k == 0:
return key

return ""

WhosShamouz
Автор

FYI, dictionaries have a .get() method which takes the default value as a second parameter. So you can use it like count[s] = count.get(s, 0) + 1, if you don't want to use if statement.

IntelliStar_
Автор

i remember when i couldn't solve a hashmap problem in the google dsa course thingy and would always refer to you and be so confused how you knew it's a hashmap problem :) good times

pastori
Автор

LibkedHashMap in Java would keep/ retain the initial order and act like a map. But python 🐍 is easier/ better. I like this one better.

Amy-
Автор

you can iterate on the dictionary because in python the order is preserved

michaelroditis
Автор

For some reason, using two hashsets has a slight better performance than using a hashmap in Java. Can you explain why that?

raphaelboakye
Автор

I guess dicts do keep the order the element was inserted? LOL

class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
count = Counter(arr)

for char, cnt in count.items():
if cnt == 1:
k -= 1
if k == 0:
return char

return ""

juanmacias
Автор

return [i for i in arr if Counter(arr)[i] == 1][k-1] if len([i for i in arr if Counter(arr)[i] == 1]) >= k else ""

hrithikbandaru