Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions insert-interval/ppxyn1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# idea: -
# Time Complexity: O(n)
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []

# Ex,. newInterval = [2,5]
for i in range(len(intervals)):
start, end = intervals[i]

# [2,5] > [1,5]

# already passed
if end < newInterval[0]:
res.append(intervals[i])

# not started yet
# (2)
elif newInterval[1] < start:
res.append(newInterval) # [1,5]
for j in range(i, len(intervals)):
res.append(intervals[j])
return res
else:
# (1)
# overlapping
newInterval[0] = min(newInterval[0], start)
newInterval[1] = max(newInterval[1], end)

res.append(newInterval)
return res

30 changes: 30 additions & 0 deletions kth-smallest-element-in-a-bst/ppxyn1.py
Original file line number Diff line number Diff line change
@@ -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

#idea : DFS (inorder)
#Time Complexity: O(n)

class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
cnt = 0
curr = root
if not curr:
return

while curr or stack:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
cnt += 1

if cnt == k:
return curr.val

curr = curr.right

23 changes: 23 additions & 0 deletions lowest-common-ancestor-of-a-binary-search-tree/ppxyn1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

# idea: BST property
# Time Complexity : O(long n)
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
cur = root
while cur:
if p.val > cur.val and q.val > cur.val:
cur = cur.right
elif p.val < cur.val and q.val < cur.val:
cur = cur.left
else:
return cur