Skip to content

Commit 3d52010

Browse files
authored
Merge pull request #2311 from ppxyn1/main
[ppxyn1] WEEK 13 solutions
2 parents 9fc8c9e + dc29245 commit 3d52010

3 files changed

Lines changed: 85 additions & 0 deletions

File tree

insert-interval/ppxyn1.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# idea: -
2+
# Time Complexity: O(n)
3+
class Solution:
4+
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
5+
res = []
6+
7+
# Ex,. newInterval = [2,5]
8+
for i in range(len(intervals)):
9+
start, end = intervals[i]
10+
11+
# [2,5] > [1,5]
12+
13+
# already passed
14+
if end < newInterval[0]:
15+
res.append(intervals[i])
16+
17+
# not started yet
18+
# (2)
19+
elif newInterval[1] < start:
20+
res.append(newInterval) # [1,5]
21+
for j in range(i, len(intervals)):
22+
res.append(intervals[j])
23+
return res
24+
else:
25+
# (1)
26+
# overlapping
27+
newInterval[0] = min(newInterval[0], start)
28+
newInterval[1] = max(newInterval[1], end)
29+
30+
res.append(newInterval)
31+
return res
32+
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
8+
#idea : DFS (inorder)
9+
#Time Complexity: O(n)
10+
11+
class Solution:
12+
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
13+
stack = []
14+
cnt = 0
15+
curr = root
16+
if not curr:
17+
return
18+
19+
while curr or stack:
20+
while curr:
21+
stack.append(curr)
22+
curr = curr.left
23+
curr = stack.pop()
24+
cnt += 1
25+
26+
if cnt == k:
27+
return curr.val
28+
29+
curr = curr.right
30+
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
# idea: BST property
9+
# Time Complexity : O(long n)
10+
class Solution:
11+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
12+
cur = root
13+
while cur:
14+
if p.val > cur.val and q.val > cur.val:
15+
cur = cur.right
16+
elif p.val < cur.val and q.val < cur.val:
17+
cur = cur.left
18+
else:
19+
return cur
20+
21+
22+
23+

0 commit comments

Comments
 (0)