Skip to content

Commit 227f589

Browse files
authored
Merge pull request #70 from SamTheKorean/solution3
[SAM] Week 3 solutions.
2 parents 6d518d9 + bcf3f63 commit 227f589

File tree

5 files changed

+81
-0
lines changed

5 files changed

+81
-0
lines changed

climbing-stairs/samthekorean.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Time complexity : O(n)
2+
# Space complexity : O(1)
3+
class Solution:
4+
def climbStairs(self, n: int) -> int:
5+
a = 1
6+
b = 2
7+
result = 0
8+
if n == 1:
9+
return a
10+
11+
if n == 2:
12+
return b
13+
14+
for i in range(3, n + 1):
15+
result = a + b
16+
a, b = b, result
17+
18+
return result
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Time complexity : O(n)
2+
# Space complexity : O(n)
3+
class Solution:
4+
def maxDepth(self, root: Optional[TreeNode]) -> int:
5+
if not root:
6+
return 0
7+
8+
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

meeting-rooms/samthekorean.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Time complexity : O(nlog(n))
2+
# Space complexity : O(1)
3+
class Solution:
4+
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
5+
intervals.sort()
6+
for i in range(len(intervals) - 1):
7+
if intervals[i][1] > intervals[i + 1][0]:
8+
return False
9+
return True

same-tree/samthekorean.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Time complexity : O(n)
2+
# Space complexity : O(n)
3+
class Solution:
4+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
5+
if not p and not q:
6+
return True
7+
8+
if not p and q:
9+
return False
10+
11+
if p and not q:
12+
return False
13+
14+
if p.val != q.val:
15+
return False
16+
17+
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time complexity: O(n*m)
2+
# 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.
3+
class Solution:
4+
def isSubtree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
5+
if not q:
6+
return True
7+
8+
if not p:
9+
return False
10+
11+
if self.isSameTree(p, q):
12+
return True
13+
14+
return self.isSubtree(p.left, q) or self.isSubtree(p.right, q)
15+
16+
def isSameTree(self, p, q) -> bool:
17+
if not p and not q:
18+
return True
19+
20+
if not p and q:
21+
return False
22+
23+
if p and not q:
24+
return False
25+
26+
if p.val != q.val:
27+
return False
28+
29+
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

0 commit comments

Comments
 (0)