Generate All Combinations Sum K in DSA Java - Time & Space Complexity
We want to understand how the time needed to find all combinations that add up to a target grows as the input changes.
Specifically, how does the number of combinations affect the work done?
Analyze the time complexity of the following code snippet.
public void findCombinations(int[] nums, int target, int start, List<Integer> current, List<List<Integer>> result) {
if (target == 0) {
result.add(new ArrayList<>(current));
return;
}
for (int i = start; i < nums.length; i++) {
if (nums[i] > target) continue;
current.add(nums[i]);
findCombinations(nums, target - nums[i], i + 1, current, result);
current.remove(current.size() - 1);
}
}
This code finds all unique combinations of numbers that sum to the target, using each number once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls exploring combinations.
- How many times: Potentially exploring many subsets, depending on input size and target.
As input size grows, the number of possible combinations grows very fast.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Thousands of recursive calls |
| 20 | Millions of recursive calls |
| 30 | Billions of recursive calls |
Pattern observation: The work grows exponentially as input size increases.
Time Complexity: O(2^n * n)
This means the time grows very fast, roughly doubling with each new element, because we explore many subsets.
[X] Wrong: "The algorithm runs in linear time because it just loops through the array once."
[OK] Correct: The code uses recursion to explore many combinations, not just one pass, so the time grows exponentially, not linearly.
Understanding this complexity helps you explain why some problems need more time and how recursion explores many possibilities.
"What if we allowed using the same number multiple times? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem goal
The problem asks to find all unique sets of numbers that add exactly to the target sum K.Step 2: Clarify what combinations mean
Combinations mean selecting numbers without caring about order, but each combination must sum to K.Final Answer:
All unique combinations of numbers that add up to K -> Option AQuick Check:
Sum of combinations = K [OK]
- Confusing combinations with permutations
- Looking for product instead of sum
- Ignoring uniqueness of combinations
Solution
Step 1: Identify parameters needed for backtracking
We need the array, target sum, current combination list, result list, and start index to avoid duplicates.Step 2: Match method signature with these parameters
public void findCombinations(int[] nums, int target, List<Integer> current, List result, int start) matches all needed parameters and returns void as it fills the result list.Final Answer:
public void findCombinations(int[] nums, int target, List<Integer> current, List result, int start) -> Option AQuick Check:
Correct parameters for backtracking method [OK]
- Missing start index parameter
- Wrong return type for backtracking method
- Incorrect parameter order
List result = new ArrayList<>();
int[] nums = {2, 3, 6, 7};
int target = 7;
findCombinations(nums, target, new ArrayList<>(), result, 0);
System.out.println(result);
Assuming findCombinations correctly finds all unique combinations summing to target.Solution
Step 1: Identify combinations that sum to 7
From nums, 7 alone sums to 7, and 2+2+3 also sums to 7.Step 2: Confirm no other combinations sum to 7
3+6=9, 2+3+6=11, 2+2+2+3=9 (too large), so only [2,2,3] and [7] are valid.Final Answer:
[[2, 2, 3], [7]] -> Option CQuick Check:
Valid combinations sum to 7 [OK]
- Including invalid sums
- Missing repeated elements allowed
- Confusing order of elements
void findCombinations(int[] nums, int target, List<Integer> current, List result, int start) {
if (target == 0) {
result.add(new ArrayList<>(current));
return;
}
for (int i = start; i < nums.length; i++) {
if (nums[i] > target) continue;
current.add(nums[i]);
findCombinations(nums, target - nums[i], current, result, i);
current.remove(current.size());
}
}Solution
Step 1: Check the remove method usage
List indices start at 0, so last element index is current.size() - 1, not current.size().Step 2: Identify correct remove call
Using current.remove(current.size()) causes IndexOutOfBoundsException because index is out of range.Final Answer:
Removing element with current.remove(current.size()) causes IndexOutOfBoundsException -> Option DQuick Check:
List remove index must be size-1 [OK]
- Removing element at wrong index
- Ignoring base case correctness
- Wrong loop start index
nums = {1, 2, 3} and target sum 4, which of the following is the correct set of all unique combinations where numbers can be repeated and sum to 4?Solution
Step 1: List all combinations summing to 4 with repeats allowed
Possible combos: [1,1,1,1], [1,1,2], [1,3], [2,2]. Note [3,1] is same as [1,3] and duplicates are not allowed.Step 2: Check options for duplicates and invalid elements
[[1,1,1,1], [1,1,2], [1,3], [2,2], [3,1]] includes [3,1] duplicate of [1,3]. [[1,1,1,1], [1,1,2], [1,3], [2,2], [4]] includes [4] which is not in nums. [[1,1,1,1], [1,1,2], [2,2], [3,1]] misses [1,3]. [[1,1,1,1], [1,1,2], [1,3], [2,2]] correctly lists unique combinations.Final Answer:
[[1,1,1,1], [1,1,2], [1,3], [2,2]] -> Option BQuick Check:
Unique combos sum to 4 without duplicates [OK]
- Counting duplicates as separate combinations
- Including numbers not in the array
- Ignoring repeated use of numbers
Ready to prove it?
Pass the test and this pattern moves unknown
