Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""
TC: O(N * 2^T) {where N is the number of candidates and T is the target. This is a rough upper bound as pruning significantly reduces the search space.}
SC: O(T/min_val) {The space required for the recursion stack, where T is the target and min_val is the smallest candidate.}

Approach:

This problem is solved using a **backtracking** algorithm to find all unique combinations. We begin by sorting the `candidates` array, which is a crucial step for **pruning** the search space. The core of the solution is a recursive function that explores combinations by adding a candidate and making a recursive call. The function's `pivot` index allows for the same number to be used multiple times. If adding a candidate causes the sum to exceed the target, we stop exploring that branch. When a valid combination is found (sum equals target), we add it to our result list. After each recursive call, we backtrack by removing the last element, allowing us to explore other possibilities.

The problem ran successfully on LeetCode.
"""
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:

def backtrack(pivot, curr_sum, path):
#base case
if curr_sum == target:
res.append(path[:])
return

#logic
for i in range(pivot, len(candidates)):
if curr_sum + candidates[i] > target:
break
path.append(candidates[i])
backtrack(i, curr_sum + candidates[i], path)
path.pop()

candidates.sort()
res = []
backtrack(pivot = 0, curr_sum = 0, path=[])
return res
50 changes: 50 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""
TC: O(3^N) {where N is the length of `num`. The branching factor is at most 3 at each position (+, -, *), leading to an exponential search space.}
SC: O(N) {The space required is dominated by the recursion stack depth and the `path` list, which are both proportional to the length of the input string.}

Approach:

This problem is solved using a **backtracking** algorithm to explore all possible valid expressions. The recursive function builds an expression by iterating through the input string `num` and trying to place an operator (`+`, `-`, `*`) or no operator between numbers. A crucial aspect of this approach is handling the order of operations for multiplication. To do this, we maintain the `curr_sum` and the `prev_num` (the last number added or subtracted) in our recursive state. When we encounter a multiplication, we must subtract the `prev_num` from the `curr_sum` and add `prev_num * curr_num` to correctly evaluate the expression. The recursion continues until all characters of the input string have been used. At the base case, if the final `curr_sum` equals the `target`, we add the constructed expression to our results. We also include a check to avoid invalid numbers with leading zeros (e.g., "05").

The problem ran successfully on LeetCode.
"""
from typing import List
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:

def backtrack(idx, path, curr_sum, prev_num):
nonlocal res
#base case
if idx >= len(num):
if curr_sum == target:
res.append("".join(path))
return

#logic
for i in range(idx, len(num)):
curr_str = num[idx:i+1]
curr_num = int(curr_str)

if not path:
#skip operation/add curr_num to path
backtrack(i+1, [curr_str], curr_num, curr_num)

else:
# +
backtrack(i+1, path+["+"]+[curr_str], curr_sum + curr_num, curr_num)

# -
backtrack(i+1, path+["-"]+[curr_str], curr_sum - curr_num, -curr_num)

# *
backtrack(i+1, path+["*"]+[curr_str], curr_sum - prev_num + prev_num*curr_num, curr_num*prev_num)

if num[idx] == "0":
break




res = []
backtrack(idx = 0, path = [], curr_sum = 0, prev_num=0)
return res