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
20 changes: 20 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#https://leetcode.com/problems/two-sum/description/
# Time Complexity : O(n),single loop through the array
# Space Complexity : O(n),HashMap stores up to n elements
# LeetCode Status : Accepted
# Problems Faced : None

class Solution:
def twoSum(self, nums, target):

map = {} # Create an empty HashMap to store {number: index}


for i in range(len(nums)): # Loop through each number one by one

complement = target - nums[i] # Calculate what number we need to complete the pair

if complement in map: # Check if that number already exists in our map
return [map[complement], i] # If found, return the stored index of complement and the current index i

map[nums[i]] = i # If not found, store current number and its index
24 changes: 24 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#https://www.geeksforgeeks.org/dsa/0-1-knapsack-problem-dp-10/
# Time Complexity : O(W), where W is the capacity of the knapsack. We traverse the dp array of size W once for each item.
# Space Complexity : O(W), as we use a 1D array of size W+1

# Problems Faced : None
def knapsack(W, val, wt):
i = len(wt) # total number of items
dp = [0] * (W + 1) # 1D array of size W+1, initialized to 0

for row in range(1, i + 1): # loop through each item
for j in range(W, wt[row - 1] - 1, -1): # traverse capacity right to left, stop at item's weight

pick = dp[j - wt[row-1]] + val[row-1] # pick current item: add its value + best with remaining capacity
notPick = dp[j] # skip current item: keep existing best value

dp[j] = max(pick, notPick) # store the better choice

return dp[W] # answer: max value at full capacity

if __name__ == "__main__":
val = [1, 2, 3] # values of items
wt = [4, 5, 1] # weights of items
W = 4 # max capacity of knapsack
print(knapsack(W, val, wt)) # output: 3