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
38 changes: 38 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//Problem 1: Two Sum
//Leetcode : https://leetcode.com/problems/two-sum/description/

/*
Time Complexity: O(n)
- We traverse the array 'nums' exactly once.
- Each lookup and insertion in the HashMap takes O(1) on average.

Space Complexity: O(n)
- In the worst case, we store all 'n' elements of the array in the HashMap.

Approach: One-Pass Hash Map
- As we iterate through the array, we check if the 'complement' (target - current number)
already exists in our map.
- If it exists, it means we found the two numbers that add up to the target.
- If not, we store the current number and its index in the map to check against future numbers.
*/

class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] result = new int[2];
for(int i=0; i < nums.length; i++ ){
if(map.containsKey(target - nums[i])){

result[0] = i;
result[1] = map.get(target-nums[i]);
break;

}else{
map.put(nums[i],i);
}
}

return result;

}
}
48 changes: 48 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@

// Problem 2: 0-1-knapsack-problem


public class Main {

/**
* Solves the 0/1 Knapsack problem using Dynamic Programming.
* Approach: 1D Array Space-Optimized Bottom-Up DP.
*
* Time Complexity: O(N)
* where N is the number of items and W is the maximum capacity.
* We iterate through each item and for each item, we iterate through the capacity.
*
* Space Complexity: O(W)
* Optimized from O(N * W) to O(W) by using a 1D array since the current state
* only depends on the previous item's results.
*/

static int knapsack(int W, int[] val, int[] wt) {

// dp[j] stores the maximum value that can be attained with capacity j
int[] dp = new int[W + 1];

for (int i = 1; i <= wt.length; i++) {
/*
* Iterate backwards from W to wt[i-1].
* We go backwards to ensure that each item is only used once (0/1).
* If we went forwards, we might use the same item multiple times (Unbounded Knapsack).
*/
for (int j = W; j >= wt[i - 1]; j--) {
// Decision: Either keep the previous max value for this capacity,
// or include the current item and add it to the max value of the remaining capacity.
dp[j] = Math.max(dp[j], dp[j - wt[i - 1]] + val[i - 1]);
}
}
return dp[W];
}

public static void main(String[] args) {

int[] val = {1, 2, 13, 4 , 7};
int[] wt = {4, 5, 1, 8 , 4};
int W = 10;

System.out.println(knapsack(W, val, wt));
}
}