1361. Validate Binary Tree Nodes

```python class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: “”” tc O(N) sc O(N) 对于一个包含 n 个节点 m 条边的无向图,如果它是一棵树,那么必须满足以下三个条件中的两个: m = n - 1; [Read More]

720. Longest Word in Dictionary

Sort + Set solution class Solution: def longestWord(self, words: List[str]) -> str: """ tc O(NlgL) sc O(N) 1. sort by len 2. check valid word 3. find max length with smallest lexical order """ words.sort(key= lambda x: len(x)) valid = set(['']) for w in words: if w[:-1] in valid: valid.add(w)... [Read More]

909. Snakes and Ladders

```python class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: “”” tc O(NN) sc O(NN) “”” r = c = len(board) q = collections.deque() seen = set() q.append(1) # x,y,val moves = 1 while q: size = len(q) for _ in range(size): cur = q.popleft() for di in range(1,7): nxt =... [Read More]
Tags: BFS Matrix Array

582. Kill Process

class Solution: def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: """tc O(N) sc O(N) main idea: hashmap to record parent -> child relation + BFS get kill process's children """ children = collections.defaultdict(list) # 1. build parent -> child tree, find root for parent, child in zip(ppid,pid): children[parent].append(child)... [Read More]

210. Course Schedule II

class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: """ tc O(V+E) sc O(V+E) main idea: BFS topological sort """ g = [[] for i in range(numCourses)] ingree = [0] * numCourses q = collections.deque() res = [] for snd,fst in prerequisites: g[fst].append(snd) ingree[snd] += 1 for i in... [Read More]