Leetcode: 567, 121, 121, 409, 589

3 Easy, 2 Medium

·

2 min read

567. Permutation in String (Medium)

Algorithm

  1. count each occurrence in s1.
  2. while i := sliding window along s2:
    1. increment count[s2[i - len(s1)]]
    2. decrement count[s2[i]]
    3. if all count.values() are zero, return True.
  3. 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 each occurence
        count = Counter(s1)
        def isZero():
            for val in count.values():
                if val != 0:
                    return False
            return True

        # init
        for i in range(ns1):
            count[s2[i]] -= 1        
        if isZero():
            return True

        # sliding window        
        for i in range(ns1, ns2):
            count[s2[i - ns1]] += 1 # recover
            count[s2[i]] -= 1       # update
            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)