diff --git a/3sum/sangbeenmoon.py b/3sum/sangbeenmoon.py index 8181cfdf1..e82e32c0b 100644 --- a/3sum/sangbeenmoon.py +++ b/3sum/sangbeenmoon.py @@ -30,3 +30,36 @@ def threeSum(self, nums: list[int]) -> list[list[int]]: left = left + 1 right = right - 1 return answer + + +# TC : O(n^2) +# SC : O(n) + +class Solution: + def threeSum(self, nums: list[int]) -> list[list[int]]: + + nums.sort() + + answer_map = {} + answer = [] + + for i in range(len(nums)): + target = -1 * nums[i] + + left = i + 1 + right = len(nums) - 1 + + while left < right: + if nums[left] + nums[right] == target: + candidate = (target * -1, nums[left], nums[right]) + if candidate not in answer_map: + answer_map[candidate] = True + answer.append([target * -1, nums[left], nums[right]]) + left += 1 + right -= 1 + elif nums[left] + nums[right] < target: + left += 1 + else: + right -= 1 + return answer + diff --git a/validate-binary-search-tree/sangbeenmoon.py b/validate-binary-search-tree/sangbeenmoon.py index c29810b48..8f8faa4a7 100644 --- a/validate-binary-search-tree/sangbeenmoon.py +++ b/validate-binary-search-tree/sangbeenmoon.py @@ -38,3 +38,38 @@ def go_right(self, cur:TreeNode, mm:int, MM:int): if cur.right: self.go_right(cur.right, cur.val, MM) + + + +# --------- + + +# Definition for a binary tree node. + +# TC: O(n) +# SC: O(h) + +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + + def isValid(min_val, max_val, cur: TreeNode) -> bool: + + + if cur is None: + return True + + if min_val is not None and cur.val <= min_val: + return False + + if max_val is not None and cur.val >= max_val: + return False + + return isValid(min_val, cur.val, cur.left) and isValid(cur.val, max_val, cur.right) + + return isValid(None, None ,root) +