diff --git a/climbing-stairs/Leo.py b/climbing-stairs/Leo.py new file mode 100644 index 000000000..5a268ee13 --- /dev/null +++ b/climbing-stairs/Leo.py @@ -0,0 +1,12 @@ +class Solution: + def climbStairs(self, n: int) -> int: + fast, slow = 1, 1 + + for i in range(n - 1): + tmp = fast + fast = fast + slow + slow = tmp + + return fast + + ## TC: O(n), SC:O(1) diff --git a/maximum-depth-of-binary-tree/Leo.py b/maximum-depth-of-binary-tree/Leo.py new file mode 100644 index 000000000..56b7bd5c6 --- /dev/null +++ b/maximum-depth-of-binary-tree/Leo.py @@ -0,0 +1,14 @@ +# 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: + def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 + + ## TC: O(n), SC: O(n) or O(logn) if it is balanced diff --git a/meeting-rooms/Leo.py b/meeting-rooms/Leo.py new file mode 100644 index 000000000..98524c491 --- /dev/null +++ b/meeting-rooms/Leo.py @@ -0,0 +1,11 @@ +class Solution: + def canAttendMeetings(self, intervals: List[List[int]]) -> bool: + intervals.sort() ## nlogn + + for i in range(len(intervals) - 1): + if intervals[i][1] > intervals[i+1][0]: + return False + + return True + + ## TC: O(nlogn), SC: O(1) diff --git a/same-tree/Leo.py b/same-tree/Leo.py new file mode 100644 index 000000000..a3ba02ead --- /dev/null +++ b/same-tree/Leo.py @@ -0,0 +1,14 @@ +# 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: + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + if p and q: + return p.val == q.val and self.isSameTree(p.right, q.right) and self.isSameTree(p.left, q.left) + else: + return p is None and q is None + + ## TC: O(n), SC: O(n) or O(logn) if it is balanced diff --git a/subtree-of-another-tree/Leo.py b/subtree-of-another-tree/Leo.py new file mode 100644 index 000000000..b65394d0e --- /dev/null +++ b/subtree-of-another-tree/Leo.py @@ -0,0 +1,30 @@ +# 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: + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: + + def dfs(root, subRoot): + if not root and not subRoot: + return True + if not root or not subRoot: + return False + if root.val != subRoot.val: + return False + + return dfs(root.left, subRoot.left) and dfs(root.right, subRoot.right) + + def solve(root): + if not root: + return False + if dfs(root, subRoot): + return True + return solve(root.left) or solve(root.right) + + return solve(root) + + ## TC: O(mn), where m and n denote len(subroot) and len(root) + ## SC: O(m+n)