File tree Expand file tree Collapse file tree 4 files changed +110
-0
lines changed Expand file tree Collapse file tree 4 files changed +110
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ this solution is O(n),
3+ but it requires extra space for 2 lists
4+ '''
5+
6+ def anagramDetection (string1 , string2 ):
7+ l1 = [0 ] * 26
8+ l2 = [0 ] * 26
9+
10+ pos1 = 0
11+ while pos1 < len (string1 ):
12+ character = string1 [pos1 ]
13+ index = ord (character ) - ord ("a" )
14+ l1 [index ] = l1 [index ] + 1
15+ pos1 += 1
16+
17+ pos2 = 0
18+ while pos2 < len (string2 ):
19+ character = string2 [pos2 ]
20+ index = ord (character ) - ord ("a" )
21+ l2 [index ] = l2 [index ] + 1
22+ pos2 += 1
23+
24+ pos = 0
25+ isAnagram = True
26+ while pos < len (l1 ) and isAnagram :
27+ if l1 [pos ] != l2 [pos ]:
28+ isAnagram = False
29+ else :
30+ pos += 1
31+
32+ return isAnagram
33+
34+ print (anagramDetection ("python" , "typhon" ))
35+ print (anagramDetection ("baba" , "abba" ))
36+ print (anagramDetection ("babb" , "abba" ))
Original file line number Diff line number Diff line change 1+
2+ # loop inside loop - O(n2)
3+
4+ def anagramDetection (string1 , string2 ):
5+ l2 = list (string2 )
6+ isAnagram = True
7+ pos1 = 0
8+ while pos1 < len (string1 ) and isAnagram :
9+ character = string1 [pos1 ]
10+
11+ characterFound = False
12+ pos2 = 0
13+ while pos2 < len (l2 ) and not characterFound :
14+ if character == l2 [pos2 ]:
15+ l2 [pos2 ] = None
16+ characterFound = True
17+ else :
18+ pos2 += 1
19+
20+ if not characterFound :
21+ isAnagram = False
22+ else :
23+ pos1 += 1
24+
25+ return isAnagram
26+
27+ print (anagramDetection ("python" , "typhon" ))
28+ print (anagramDetection ("baba" , "abba" ))
29+ print (anagramDetection ("babb" , "abba" ))
Original file line number Diff line number Diff line change 1+ '''
2+ you might think that this algorithm is O(n) but,
3+ sorting is dominant part of algorithm and
4+ sorting is typically either O(n2) or O(nlogn)
5+ '''
6+
7+
8+ def anagramDetection (string1 , string2 ):
9+ l1 = list (string1 )
10+ l2 = list (string2 )
11+
12+ l1 .sort ()
13+ l2 .sort ()
14+
15+ isAnagram = True
16+ pos = 0
17+ while pos < len (l1 ) and isAnagram :
18+ if l1 [pos ] == l2 [pos ]:
19+ pos += 1
20+ else :
21+ isAnagram = False
22+
23+
24+ return isAnagram
25+
26+ print (anagramDetection ("python" , "typhon" ))
27+ print (anagramDetection ("baba" , "abba" ))
28+ print (anagramDetection ("babb" , "abba" ))
Original file line number Diff line number Diff line change 1+
2+ # iterative solution
3+ def sumOfNumbersIterative (number ):
4+ sum = 0
5+ for item in range (number + 1 ):
6+ sum += item
7+ return sum
8+
9+
10+ print (sumOfNumbersIterative (5 ))
11+
12+ # non-iterative solution
13+ def sumOfNumbersNonIterative (number ):
14+ return number * (number + 1 ) / 2
15+
16+ print (sumOfNumbersNonIterative (5 ))
17+
You can’t perform that action at this time.
0 commit comments