From f34ce7e5f84ccff605545a00180828316d14d212 Mon Sep 17 00:00:00 2001 From: subbu4061 Date: Mon, 2 Mar 2026 15:29:31 -0800 Subject: [PATCH] Adding the:swq solutions --- Knapsack.java | 19 +++++++++++++++++++ Problem1.cpp | 0 Problem1.java | 0 Problem2.cpp | 0 Problem2.java | 0 TwoSum.java | 18 ++++++++++++++++++ 6 files changed, 37 insertions(+) create mode 100644 Knapsack.java delete mode 100644 Problem1.cpp delete mode 100644 Problem1.java delete mode 100644 Problem2.cpp delete mode 100644 Problem2.java create mode 100644 TwoSum.java diff --git a/Knapsack.java b/Knapsack.java new file mode 100644 index 00000000..4d617864 --- /dev/null +++ b/Knapsack.java @@ -0,0 +1,19 @@ + // TimeComplexity: O(n x W) + // SpaceComplexity: O(W) + + static int knapsack(int W, int[] val, int[] wt) { + + // Initializing dp array + int[] dp = new int[W + 1]; + + // Taking first i elements + for (int i = 1; i <= wt.length; i++) { + + // Starting from back, so that we also have data of + // previous computation of i-1 items + for (int j = W; j >= wt[i - 1]; j--) { + dp[j] = Math.max(dp[j], dp[j - wt[i - 1]] + val[i - 1]); + } + } + return dp[W]; + } diff --git a/Problem1.cpp b/Problem1.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/Problem1.java b/Problem1.java deleted file mode 100644 index e69de29b..00000000 diff --git a/Problem2.cpp b/Problem2.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/Problem2.java b/Problem2.java deleted file mode 100644 index e69de29b..00000000 diff --git a/TwoSum.java b/TwoSum.java new file mode 100644 index 00000000..dc1ac9d5 --- /dev/null +++ b/TwoSum.java @@ -0,0 +1,18 @@ +// TimeComplexity: O(n) +// SpaceComplexity: O(n) +// Explanation: I am iterating through the array and storing the elemnet in the hashmap with its index if the compliment is not found. If the compliment is found I am returning the compliment index and the current index. + +class Solution { + public int[] twoSum(int[] nums, int target) { + int n = nums.length; + HashMap map = new HashMap<>(); + for(int i=0; i