diff --git a/3sum/printjin-gmailcom.py b/3sum/printjin-gmailcom.py new file mode 100644 index 000000000..26e56d133 --- /dev/null +++ b/3sum/printjin-gmailcom.py @@ -0,0 +1,22 @@ +class Solution: + def threeSum(self, nums): + triplets = [] + nums.sort() + for i in range(len(nums) - 2): + if i > 0 and nums[i - 1] == nums[i]: + continue + low, high = i + 1, len(nums) - 1 + while low < high: + three_sum = nums[i] + nums[low] + nums[high] + if three_sum < 0: + low += 1 + elif three_sum > 0: + high -= 1 + else: + triplets.append([nums[i], nums[low], nums[high]]) + while low < high and nums[low] == nums[low + 1]: + low += 1 + while low < high and nums[high] == nums[high - 1]: + high -= 1 + low, high = low + 1, high - 1 + return triplets diff --git a/climbing-stairs/printjin-gmailcom.py b/climbing-stairs/printjin-gmailcom.py new file mode 100644 index 000000000..2fd5c6761 --- /dev/null +++ b/climbing-stairs/printjin-gmailcom.py @@ -0,0 +1,8 @@ +class Solution: + def climbStairs(self, n: int): + if n <= 2: + return n + a, b = 1, 2 + for _ in range(3, n+1): + a, b = b, a + b + return b diff --git a/product-of-array-except-self/printjin-gmailcom.py b/product-of-array-except-self/printjin-gmailcom.py new file mode 100644 index 000000000..b4226af8e --- /dev/null +++ b/product-of-array-except-self/printjin-gmailcom.py @@ -0,0 +1,13 @@ +class Solution: + def productExceptSelf(self, nums): + n = len(nums) + answer = [1] * n + left = 1 + for i in range(n): + answer[i] = left + left *= nums[i] + right = 1 + for i in range(n-1, -1, -1): + answer[i] *= right + right *= nums[i] + return answer diff --git a/valid-anagram/printjin-gmailcom.py b/valid-anagram/printjin-gmailcom.py new file mode 100644 index 000000000..6be7b9eda --- /dev/null +++ b/valid-anagram/printjin-gmailcom.py @@ -0,0 +1,5 @@ +from collections import Counter + +class Solution: + def isAnagram(self, s: str, t: str): + return Counter(s) == Counter(t) diff --git a/validate-binary-search-tree/printjin-gmailcom.py b/validate-binary-search-tree/printjin-gmailcom.py new file mode 100644 index 000000000..c9bb78f14 --- /dev/null +++ b/validate-binary-search-tree/printjin-gmailcom.py @@ -0,0 +1,16 @@ +class Solution: + def isValidBST(self, root): + max_val = float("-inf") + def dfs(node): + if not node: + return True + nonlocal max_val + if not dfs(node.left): + return False + if max_val >= node.val: + return False + max_val = node.val + if not dfs(node.right): + return False + return True + return dfs(root)