1
+
2
+ # COUNT CONTAINED PERMUTATIONS
3
+
4
+ # O(M * U + N) time and O(U) space, where M -> length of big string,
5
+ # U -> number of unique characters in small string, N -> length
6
+ # of small string.
7
+ # U is actually a constant since it can't be greater than 26. and
8
+ # M > N, so M will dissolve N
9
+ # So, modified complexities:
10
+ # O(M) time and O(1) space, M -> length of big string
11
+ def countContainedPermutations (bigString , smallString ):
12
+ # Write your code here.
13
+ smallCount , bigCount = {}, {}
14
+ for letter in smallString :
15
+ if letter not in smallCount :
16
+ smallCount [letter ] = 0
17
+ smallCount [letter ] += 1
18
+
19
+ bigSize , smallSize = len (bigString ), len (smallString )
20
+ start , end , totalCount = 0 , 0 , 0
21
+
22
+ while end < bigSize :
23
+ letterToAdd = bigString [end ]
24
+ if letterToAdd not in bigCount :
25
+ bigCount [letterToAdd ] = 0
26
+ bigCount [letterToAdd ] += 1
27
+
28
+ if end - start == smallSize :
29
+ letterToRemove = bigString [start ]
30
+ if bigCount [letterToRemove ] == 1 :
31
+ del bigCount [letterToRemove ]
32
+ else :
33
+ bigCount [letterToRemove ] -= 1
34
+
35
+ start += 1
36
+
37
+ if matchCounts (bigCount , smallCount ):
38
+ totalCount += 1
39
+
40
+ end += 1
41
+
42
+ return totalCount
43
+
44
+ def matchCounts (bigCount , smallCount ):
45
+ for letter in smallCount :
46
+ if letter not in bigCount :
47
+ return False
48
+ if smallCount [letter ] != bigCount [letter ]:
49
+ return False
50
+
51
+ return True
0 commit comments