-
Notifications
You must be signed in to change notification settings - Fork 19.9k
Optimised Space Complexity To O(sum) #5651
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## master #5651 +/- ##
============================================
- Coverage 58.94% 58.93% -0.02%
+ Complexity 3773 3771 -2
============================================
Files 556 556
Lines 15945 15942 -3
Branches 3040 3038 -2
============================================
- Hits 9399 9395 -4
- Misses 6143 6144 +1
Partials 403 403 ☔ View full report in Codecov by Sentry. |
src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java
Outdated
Show resolved
Hide resolved
src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java
Outdated
Show resolved
Hide resolved
Hey @alxkm Thanks for the feedback. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for your contribution.
fixes #5600
Problem:
This PR implements a solution to the "Subset Sum Equals to K" problem using dynamic programming while optimizing space complexity from O(n * sum) to O(sum). The problem is to determine whether there is a subset of a given array whose sum is exactly equal to a target integer
K
.Approach:
The standard DP approach for the subset sum problem involves creating a 2D table where each entry dp[i][j] represents whether a subset of the first
i
elements of the array can sum toj
. This has a space complexity of O(n * sum), wheren
is the number of elements in the array andsum
is the target sum.To optimize space complexity, we can use a 1D array of size
sum + 1
instead of the 2D table. The key idea is that the current state of the DP table only depends on the previous row (i.e., whether the sum was possible with or without the current element). Thus, we can update the DP array in reverse order, ensuring that we do not overwrite values that are still needed.Space Optimization:
The space-optimized approach reduces the space complexity to O(sum) by reusing a 1D DP array. At each iteration, we update the DP array from right to left to ensure we only use the previous values from the last iteration.
clang-format -i --style=file path/to/your/file.java