need to consider test cases: (1) n=1 edges: [] (2) root point is not always start with 0 (but usually it returns False) DFS solution with Hashmap + stack (iterative) ```python class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: “”” time O(E+V) space O(E+V) 1.build graph (adjacency list)...
[Read More]
LC485. Max Consecutive Ones
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: """ O(N)/O(1) """ cnt = 0 ans = 0 for x in nums: if x == 1 : cnt += 1 else: ans = max(ans,cnt) cnt = 0 # be aware of case when ptr reach the last cnt is not reset....
[Read More]
LC89. Gray Code
```python class Solution: def grayCode(self, n: int) -> List[int]: “”” O(2^N)/O(1) main idea: initialized number is all 0s with length of size n. change from lower digit to higher digit, start “”” res = [0] for i in range(n): for j in range(len(res)-1,-1,-1): # since there are one bit differ...
[Read More]
LC212. Word Search II
define TrieNode, Trie build Trie based on words loop whole board, start with random i,j to search Trie using dfs(backtracking) if a word exist, update res and reset mark into None (avoid duplicate). then continue backtracking ```python class Trie: def init(self,val=None): self.val = val self.children = {} self.isWord = False...
[Read More]
LC811. Subdomain Visit Count
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: """??O(N*W*L) /O(N*L) L: longest length of subdomain; W: longest length of subdomain 1. split domain into cnt and domain, note cnt need to be convert into int 2. further split domain into different subdomain 3. loop through subdomain accumutively and update dictionary...
[Read More]