567. Permutation in String (Medium)
Algorithm
- count each occurrence in s1.
- while i := sliding window along s2:
- increment count[s2[i - len(s1)]]
- decrement count[s2[i]]
- if all count.values() are zero, return True.
- return False.
Python code
from collections import Counter
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
ns1, ns2 = len(s1), len(s2)
if ns1 > ns2:
return False
count = Counter(s1)
def isZero():
for val in count.values():
if val != 0:
return False
return True
for i in range(ns1):
count[s2[i]] -= 1
if isZero():
return True
for i in range(ns1, ns2):
count[s2[i - ns1]] += 1
count[s2[i]] -= 1
if isZero():
return True
return False
102. Binary Tree Level Order Traversal (Medium)
Python code
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root == None:
return []
orders = list()
o = list()
queue = [(root, 0)]
level = 0
while queue:
node, lev = queue.pop(0)
if level != lev:
level = lev
orders.append(o)
o = list()
o.append(node.val)
if node.left:
queue.append((node.left, lev + 1))
if node.right:
queue.append((node.right, lev + 1))
orders.append(o)
return orders
121. Best Time to Buy and Sell Stock (Easy)
409. Longest Palindrome (Easy)
589. N-ary Tree Preorder Traversal (Easy)