-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpermutation-in-string.py
More file actions
58 lines (47 loc) · 2 KB
/
permutation-in-string.py
File metadata and controls
58 lines (47 loc) · 2 KB
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
# https://leetcode.com/problems/permutation-in-string/
# Related Topics: Two Pointers, Sliding Window, Hash Table
# Difficulty: Medium
# Initial thoughts:
# Creating a frequency table for the characters in s1 we are going to
# have a changing frequency table for s2 that encompasses chracters equal
# to the length of s1. Moving forward with the freq table on s2, we are going
# to compare the two freq tables at each step. If they are identical, we have a
# permutation of s1 in s2.
# Since we are dealing with a predefined set of characters (in this case English
# small letters) the comparision of the freq tables takes constant time (26 at most)
# Creating the freq tables also won't take more than linear time equal to the length
# of s2.
# Time complexity: O(n) where n == len(s2)
# Space complexity: O(1) because the freq tables won't have more than 26 chars
from typing import Dict
from collections import defaultdict, Counter
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
freq_table = Counter(s1)
curr_table = Counter(s2[:len(s1)])
if freq_table == curr_table: return True
for i in range(len(s2)-len(s1)):
curr_table[s2[len(s1)+i]] += 1
curr_table[s2[i]] -= 1
if curr_table[s2[i]] == 0:
del curr_table[s2[i]]
if freq_table == curr_table: return True
return False
def checkInclusion2(self, s1: str, s2: str) -> bool:
def createFreqTable(s: str) -> Dict[str, int]:
dic = defaultdict(int)
for c in s:
dic[c] += 1
return dic
dic1 = createFreqTable(s1)
dic2 = createFreqTable(s2[0:len(s1)])
if dic1 == dic2:
return True
for i in range(len(s1), len(s2)):
dic2[s2[i-len(s1)]] -= 1
if dic2[s2[i-len(s1)]] == 0:
del dic2[s2[i-len(s1)]]
dic2[s2[i]] += 1
if dic2 == dic1:
return True
return False