Skip to content

Commit b04be1c

Browse files
Merge pull request #1219 from printjin-gmailcom/main
[printjin-gmailcom] WEEK 02 Solutions
2 parents 237b11a + 0823a9f commit b04be1c

File tree

5 files changed

+64
-0
lines changed

5 files changed

+64
-0
lines changed

3sum/printjin-gmailcom.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def threeSum(self, nums):
3+
triplets = []
4+
nums.sort()
5+
for i in range(len(nums) - 2):
6+
if i > 0 and nums[i - 1] == nums[i]:
7+
continue
8+
low, high = i + 1, len(nums) - 1
9+
while low < high:
10+
three_sum = nums[i] + nums[low] + nums[high]
11+
if three_sum < 0:
12+
low += 1
13+
elif three_sum > 0:
14+
high -= 1
15+
else:
16+
triplets.append([nums[i], nums[low], nums[high]])
17+
while low < high and nums[low] == nums[low + 1]:
18+
low += 1
19+
while low < high and nums[high] == nums[high - 1]:
20+
high -= 1
21+
low, high = low + 1, high - 1
22+
return triplets

climbing-stairs/printjin-gmailcom.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class Solution:
2+
def climbStairs(self, n: int):
3+
if n <= 2:
4+
return n
5+
a, b = 1, 2
6+
for _ in range(3, n+1):
7+
a, b = b, a + b
8+
return b
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def productExceptSelf(self, nums):
3+
n = len(nums)
4+
answer = [1] * n
5+
left = 1
6+
for i in range(n):
7+
answer[i] = left
8+
left *= nums[i]
9+
right = 1
10+
for i in range(n-1, -1, -1):
11+
answer[i] *= right
12+
right *= nums[i]
13+
return answer

valid-anagram/printjin-gmailcom.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from collections import Counter
2+
3+
class Solution:
4+
def isAnagram(self, s: str, t: str):
5+
return Counter(s) == Counter(t)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
def isValidBST(self, root):
3+
max_val = float("-inf")
4+
def dfs(node):
5+
if not node:
6+
return True
7+
nonlocal max_val
8+
if not dfs(node.left):
9+
return False
10+
if max_val >= node.val:
11+
return False
12+
max_val = node.val
13+
if not dfs(node.right):
14+
return False
15+
return True
16+
return dfs(root)

0 commit comments

Comments
 (0)