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
24 changes: 24 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Time Complexity : O(n) because we traverse the array once and HashMap operations take O(1) on average
// Space Complexity : O(n) for storing numbers and their indices in the HashMap
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach in three sentences only
// We use a HashMap to store each number along with its index as we iterate through the array.
// For every number, we calculate the required complement needed to reach the target and check whether it already exists in the map.
// If the complement exists, we return the stored index and current index as the required pair; otherwise, we store the current number and continue.

class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashMap = new HashMap<>();
for (int i=0; i<nums.length; i++) {
int diff = target - nums[i];
if (hashMap.containsKey(diff)) {
return new int[] {hashMap.get(diff), i};
}
hashMap.put(nums[i], i);
}
return new int[] {};
}
}
37 changes: 37 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Time Complexity : O(n * W) where n is number of items and W is the capacity of the knapsack
// Space Complexity : O(n * W)
// Did this code successfully run on GeeksForGeeks : Yes
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach in three sentences only
// We use dynamic programming where dp[i][w] stores the maximum value we can get using the first i items with capacity w.
// For every item, we have two choices: skip it, or take it if its weight is less than or equal to the current capacity.
// The answer is stored in dp[n][W], which represents the best value possible using all items and full capacity.

class Solution {

static int knapSack(int W, int wt[], int val[], int n) {

int[][] dp = new int[n + 1][W + 1];

for (int i = 1; i <= n; i++) {

for (int w = 1; w <= W; w++) {

// skip current item
dp[i][w] = dp[i - 1][w];

// take current item if it fits
if (wt[i - 1] <= w) {
dp[i][w] = Math.max(
dp[i][w],
val[i - 1] + dp[i - 1][w - wt[i - 1]]
);
}
}
}

return dp[n][W];
}
}