diff --git a/combination-sum/jinah92.py b/combination-sum/jinah92.py new file mode 100644 index 000000000..ba0500ba0 --- /dev/null +++ b/combination-sum/jinah92.py @@ -0,0 +1,19 @@ +# O(T) time, O(C^T) space +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + results, nums = [], [] + + def dfs(start, total): + if total > target: + return + if total == target: + results.append(nums[:]) + for i in range(start, len(candidates)): + num = candidates[i] + nums.append(num) + dfs(i, total + num) + nums.pop() + + dfs(0, 0) + + return results diff --git a/maximum-subarray/jinah92.py b/maximum-subarray/jinah92.py new file mode 100644 index 000000000..dcf0d88b5 --- /dev/null +++ b/maximum-subarray/jinah92.py @@ -0,0 +1,14 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + num_set = {} + result = -math.inf + + for idx, num in enumerate(nums): + if idx == 0: + num_set[idx] = max(nums[0], result) + else: + num_set[idx] = max(num, num_set[idx-1] + num) + tmp_sum = num_set[idx] + result = max(result, tmp_sum) + + return result diff --git a/product-of-array-except-self/jinah92.py b/product-of-array-except-self/jinah92.py new file mode 100644 index 000000000..68bb85e2b --- /dev/null +++ b/product-of-array-except-self/jinah92.py @@ -0,0 +1,21 @@ +# O(n) time, O(n) space +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + non_zero_product = math.prod(filter(lambda x: x != 0, nums)) + raw_product = math.prod(nums) + zero_total = nums.count(0) + + result = [] + + for num in nums: + if zero_total > 1: + result.append(0) + elif zero_total == 1: + if num == 0: + result.append(non_zero_product) + else: + result.append(raw_product) + else: + result.append(raw_product // num) + + return result diff --git a/reverse-bits/jinah92.py b/reverse-bits/jinah92.py new file mode 100644 index 000000000..4d2d8cf5e --- /dev/null +++ b/reverse-bits/jinah92.py @@ -0,0 +1,14 @@ +# O(1) time, O(1) space +class Solution: + def reverseBits(self, n: int) -> int: + stack = [] + while len(stack) < 32: + stack.append(n % 2) + n //=2 + + result, scale = 0, 1 + while stack: + result += stack.pop() * scale + scale *= 2 + + return result diff --git a/two-sum/jinah92.py b/two-sum/jinah92.py new file mode 100644 index 000000000..e8b204155 --- /dev/null +++ b/two-sum/jinah92.py @@ -0,0 +1,12 @@ +# O(n) time, O(n) space + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + num_set = {} + + for idx, num in enumerate(nums): + other_num = target - num + if other_num in num_set: + return [idx, num_set[other_num]] + else: + num_set[num] = idx