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”
3
4
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
+ """
9
8
10
9
def firstduplicate (string : str ) -> str :
11
10
import re
@@ -23,4 +22,26 @@ def firstduplicate(string: str) -> str:
23
22
string = "this is just a wonder, wonder why do I have this in mind"
24
23
firstduplicate (string )
25
24
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
+
26
47
0 commit comments