-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanagramIndexOf.py
89 lines (60 loc) · 2.11 KB
/
anagramIndexOf.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Return the index of the first occurrence of an anagram of needed in a haystack, or -1 if needle is not part of haystack.
# "actor", "cat" => return 0
# "act" is an anagram of "cat"
#==== Solution using a helper function comparing two dictionaries each time
def anagrammedIndexOf_helper(haystack, needle):
if len(needle) > len(haystack):
return -1
if not needle or not haystack:
return -1
# Create a needle dictionary
nDict = {}
for c in needle:
nDict[c] = nDict.get(c, 0) + 1
for i in range(len(haystack)-len(needle)+1):
if haystack[i] in nDict:
subStr = haystack[i:i+len(needle)]
if helper(subStr, nDict):
return i
return -1
def helper (subStr, nDict):
for c in subStr:
if c not in nDict:
return False
else:
nDict[c] -= 1
if nDict[c] == 0:
nDict.pop(c)
if not nDict:
return True
return False
#==== Solutions using 2 pointers and have a rolling dictionary. However, it still requires comparing the dictionaries
def anagrammedIndexOf(haystack, needle):
if len(needle) > len(haystack):
return -1
if not needle or not haystack:
return -1
# Create a needle dictionary
nDict = {}
for c in needle:
nDict[c] = nDict.get(c, 0) + 1
l = 0
r = len(needle)-1
rollingWindow = {}
for c in haystack[l:r+1]:
rollingWindow[c] = rollingWindow.get(c, 0) + 1
while r < len(haystack):
if rollingWindow == nDict:
return l
else:
rollingWindow.pop(haystack[l])
l += 1
r += 1
if r < len(haystack):
rollingWindow[haystack[r]] = rollingWindow.get(haystack[r], 0) + 1
return -1
print(anagrammedIndexOf("actor", "cate")) #-1
print(anagrammedIndexOf("actor", "cat")) #0
print(anagrammedIndexOf("hell", "ll")) #2
print(anagrammedIndexOf("cbaebabacd", "abc")) #0
assert anagrammedIndexOf("actor", "cat") == 0