Skip to content

Commit f811d45

Browse files
authored
Merge pull request #793 from jinah92/main
[jinah92] Week 3
2 parents 4b8f7e0 + 93fe9c3 commit f811d45

File tree

5 files changed

+80
-0
lines changed

5 files changed

+80
-0
lines changed

combination-sum/jinah92.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# O(T) time, O(C^T) space
2+
class Solution:
3+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
4+
results, nums = [], []
5+
6+
def dfs(start, total):
7+
if total > target:
8+
return
9+
if total == target:
10+
results.append(nums[:])
11+
for i in range(start, len(candidates)):
12+
num = candidates[i]
13+
nums.append(num)
14+
dfs(i, total + num)
15+
nums.pop()
16+
17+
dfs(0, 0)
18+
19+
return results

maximum-subarray/jinah92.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def maxSubArray(self, nums: List[int]) -> int:
3+
num_set = {}
4+
result = -math.inf
5+
6+
for idx, num in enumerate(nums):
7+
if idx == 0:
8+
num_set[idx] = max(nums[0], result)
9+
else:
10+
num_set[idx] = max(num, num_set[idx-1] + num)
11+
tmp_sum = num_set[idx]
12+
result = max(result, tmp_sum)
13+
14+
return result
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# O(n) time, O(n) space
2+
class Solution:
3+
def productExceptSelf(self, nums: List[int]) -> List[int]:
4+
non_zero_product = math.prod(filter(lambda x: x != 0, nums))
5+
raw_product = math.prod(nums)
6+
zero_total = nums.count(0)
7+
8+
result = []
9+
10+
for num in nums:
11+
if zero_total > 1:
12+
result.append(0)
13+
elif zero_total == 1:
14+
if num == 0:
15+
result.append(non_zero_product)
16+
else:
17+
result.append(raw_product)
18+
else:
19+
result.append(raw_product // num)
20+
21+
return result

reverse-bits/jinah92.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# O(1) time, O(1) space
2+
class Solution:
3+
def reverseBits(self, n: int) -> int:
4+
stack = []
5+
while len(stack) < 32:
6+
stack.append(n % 2)
7+
n //=2
8+
9+
result, scale = 0, 1
10+
while stack:
11+
result += stack.pop() * scale
12+
scale *= 2
13+
14+
return result

two-sum/jinah92.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# O(n) time, O(n) space
2+
3+
class Solution:
4+
def twoSum(self, nums: List[int], target: int) -> List[int]:
5+
num_set = {}
6+
7+
for idx, num in enumerate(nums):
8+
other_num = target - num
9+
if other_num in num_set:
10+
return [idx, num_set[other_num]]
11+
else:
12+
num_set[num] = idx

0 commit comments

Comments
 (0)