Skip to content

Commit ca9e763

Browse files
author
ybenchekroun
authored
Update first_duplicate_word.py
1 parent 726dd41 commit ca9e763

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

HashMaps/first_duplicate_word.py

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
#Problem Statement : Given a string find the first duplicate word,
2-
#example string: “this is just a wonder, wonder why do I have this in mind”
1+
"""
2+
1) Problem Statement : Given a string find the first duplicate word,
3+
example string: “this is just a wonder, wonder why do I have this in mind”
34
4-
5-
6-
#- The right data-structure to check for existence :
7-
# set in Python (order in not preserved) -- NOT HashMap
8-
5+
- The right data-structure to check for existence :
6+
Set in Python (order in not preserved) -- NOT HashMap
7+
"""
98

109
def firstduplicate(string: str) -> str:
1110
import re
@@ -23,4 +22,26 @@ def firstduplicate(string: str) -> str:
2322
string = "this is just a wonder, wonder why do I have this in mind"
2423
firstduplicate(string)
2524

25+
#-------------------------------------------------------------------
26+
27+
"""
28+
1) Problem Statement : What if we wanted to find the first word with more than 2 duplicates in a string?
29+
- The right data-structure is the HashMap to get access in O(1) in Python, use dict()
30+
"""
31+
32+
def first2timesduplicate(string: str) -> str:
33+
import re
34+
cleanStr = re.sub("[^a-zA-Z -]", "", string)
35+
36+
words = cleanStr.lower().split(" ")
37+
seen_words = dict()
38+
for word in words:
39+
previous_count = seen_words.get(word, 0)
40+
seen_words[word] = previous_count + 1
41+
if previous_count >= 2:
42+
return word
43+
return None
44+
45+
first2timesduplicate(string)
46+
2647

0 commit comments

Comments
 (0)