From 81c2999399790cbded86f9897cceb475147c9efa Mon Sep 17 00:00:00 2001 From: nikhylw <1.nikhil.wani+nikhly@gmail.com> Date: Mon, 11 May 2026 01:20:52 +0530 Subject: [PATCH] adding interview-2 solutions --- W2_01knapsack.py | 30 ++++++++++++++++++++++++++++++ W2_two_sum.py | 19 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 W2_01knapsack.py create mode 100644 W2_two_sum.py diff --git a/W2_01knapsack.py b/W2_01knapsack.py new file mode 100644 index 00000000..45a62f36 --- /dev/null +++ b/W2_01knapsack.py @@ -0,0 +1,30 @@ +def knapsack(W, val, wt): + n = len(wt) + dp = [[0 for _ in range(W + 1)] for _ in range(n + 1)] + + for i in range(n + 1): + for j in range(W + 1): + + # If there are no items or capacity is 0 + if i == 0 or j == 0: + dp[i][j] = 0 + else: + choose = 0 + + # Choice 1: choose the current item + if wt[i - 1] <= j: + choose = val[i - 1] + dp[i - 1][j - wt[i - 1]] + + # Choice 2: don't choose the current item + dont_choose = dp[i - 1][j] + + dp[i][j] = max(choose, dont_choose) + + return dp[n][W] + + +# Time complexity: O(n * W), where n is the number of items and W is the knapsack capacity. +# We fill a DP table of size (n + 1) * (W + 1), and each cell takes O(1) time. + +# Space complexity: O(n * W), because we store a 2D DP table with +# (n + 1) rows and (W + 1) columns. \ No newline at end of file diff --git a/W2_two_sum.py b/W2_two_sum.py new file mode 100644 index 00000000..4d030220 --- /dev/null +++ b/W2_two_sum.py @@ -0,0 +1,19 @@ +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + result = [] + hashmap = {} + + for i in range(len(nums)): + complement = target - nums[i] + + if complement not in hashmap: + hashmap[nums[i]] = i + else: + result.append(i) + result.append(hashmap[complement]) + + return result + +# Time complexity: O(N), we visit each element once. +# Space complexity: O(N), if the pair is found at the last index, then the hashmap will have n-1 keys worst case +