LC54 Spiral Matrix

class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: # time O(RC) space O(RC) if not matrix: return [] R,C = len(matrix),len(matrix[0]) # here is to optimize #if not C: # return res seen = [[False]*C for _ in range(R)] res = [] dd = [(0,1),(1,0),(0,-1),(-1,0)] r = c = di... [Read More]
Tags: Array

LC283 Move Zeroes

class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. main idea: by default set idx =0 as non-zero val; loop through whole array, if find non zero val, assign it to idx=0 ; idx ++; then fill out the rest start from... [Read More]

LC1022 Sum of Root To Leaf Binary Numbers

```python Definition for a binary tree node. class TreeNode: def init(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: #time O(N) space O(H) H:since the stack for recursion def sumRootToLeaf(self, root: TreeNode) -> int: self.res = 0 self.preorder(root,0) return self.res def preorder(self,node,cur): if node:... [Read More]
Tags: Tree

LC835 Image Overlap

```python class Solution: def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int: “”” # time O(N^4) space O(N^2) step1, cache W,H and create two list for A, B respectively; create a dictionary step2, loop through whole image, find coordinate where value = 1 in both A, B, and store them into... [Read More]
Tags: Array

LC1305 All Elements in Two Binary Search Trees

```python Definition for a binary tree node. class TreeNode: def init(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: # time O(N) space O(N) “”” main idea: use inorder traversal to get all value from each node in both trees. use feature of queue... [Read More]
Tags: Tree Sort