diff --git a/climbing-stairs/samthekorean.py b/climbing-stairs/samthekorean.py index e69de29bb..eecbe2969 100644 --- a/climbing-stairs/samthekorean.py +++ b/climbing-stairs/samthekorean.py @@ -0,0 +1,18 @@ +# Time complexity : O(n) +# Space complexity : O(1) +class Solution: + def climbStairs(self, n: int) -> int: + a = 1 + b = 2 + result = 0 + if n == 1: + return a + + if n == 2: + return b + + for i in range(3, n + 1): + result = a + b + a, b = b, result + + return result diff --git a/maximum-depth-of-binary-tree/samthekorean.py b/maximum-depth-of-binary-tree/samthekorean.py index e69de29bb..c9fbfb73b 100644 --- a/maximum-depth-of-binary-tree/samthekorean.py +++ b/maximum-depth-of-binary-tree/samthekorean.py @@ -0,0 +1,8 @@ +# Time complexity : O(n) +# Space complexity : O(n) +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) diff --git a/meeting-rooms/samthekorean.py b/meeting-rooms/samthekorean.py index e69de29bb..0ad9d2dbc 100644 --- a/meeting-rooms/samthekorean.py +++ b/meeting-rooms/samthekorean.py @@ -0,0 +1,9 @@ +# Time complexity : O(nlog(n)) +# Space complexity : O(1) +class Solution: + def canAttendMeetings(self, intervals: List[List[int]]) -> bool: + intervals.sort() + for i in range(len(intervals) - 1): + if intervals[i][1] > intervals[i + 1][0]: + return False + return True diff --git a/same-tree/samthekorean.py b/same-tree/samthekorean.py index e69de29bb..077cef932 100644 --- a/same-tree/samthekorean.py +++ b/same-tree/samthekorean.py @@ -0,0 +1,17 @@ +# Time complexity : O(n) +# Space complexity : O(n) +class Solution: + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + if not p and not q: + return True + + if not p and q: + return False + + if p and not q: + return False + + if p.val != q.val: + return False + + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) diff --git a/subtree-of-another-tree/samthekorean.py b/subtree-of-another-tree/samthekorean.py index e69de29bb..89c507cb6 100644 --- a/subtree-of-another-tree/samthekorean.py +++ b/subtree-of-another-tree/samthekorean.py @@ -0,0 +1,29 @@ +# Time complexity: O(n*m) +# Space complexity: O(r + s) isSubtree() method is internally calling isSameTree() so the total depth of the stack is sum of isSubtree() call stacks and isSameTree()'s call stacks. +class Solution: + def isSubtree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + if not q: + return True + + if not p: + return False + + if self.isSameTree(p, q): + return True + + return self.isSubtree(p.left, q) or self.isSubtree(p.right, q) + + def isSameTree(self, p, q) -> bool: + if not p and not q: + return True + + if not p and q: + return False + + if p and not q: + return False + + if p.val != q.val: + return False + + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)