Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start the backtracking with an empty list.
DSA Java
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<>();
backtrack(1, k, n, new ArrayList<>(), result);
return result;
}
private void backtrack(int start, int k, int n, List<Integer> tempList, List<List<Integer>> result) {
if (tempList.size() == k && n == 0) {
result.add(new ArrayList<>(tempList));
return;
}
for (int i = start; i <= 9; i++) {
tempList.add(i);
backtrack(i + 1, k, n - i, tempList, result);
tempList.remove(tempList.size() - 1);
}
}
// Call the method with [1]Attempts:
3 left
💡 Hint
Common Mistakes
Choosing wrong parameters for k and n in the initial call.
Not starting the backtracking with the correct parameters.
✗ Incorrect
The method combinationSum3(3, 7) starts the search for combinations of 3 numbers that sum to 7.
2fill in blank
mediumComplete the code to check if the current combination is valid.
DSA Java
private void backtrack(int start, int k, int n, List<Integer> tempList, List<List<Integer>> result) {
if (tempList.size() == k && [1]) {
result.add(new ArrayList<>(tempList));
return;
}
for (int i = start; i <= 9; i++) {
tempList.add(i);
backtrack(i + 1, k, n - i, tempList, result);
tempList.remove(tempList.size() - 1);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking if n > 0 instead of n == 0.
Not checking the sum condition at all.
✗ Incorrect
The combination is valid only if the sum left (n) is zero when the size matches k.
3fill in blank
hardFix the error in the for-loop condition to avoid invalid numbers.
DSA Java
for (int i = start; i [1] 9; i++) { tempList.add(i); backtrack(i + 1, k, n - i, tempList, result); tempList.remove(tempList.size() - 1); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using < excludes 9, missing valid combinations.
Using > or >= causes infinite loops or no iterations.
✗ Incorrect
The loop should include 9, so the condition must be i <= 9.
4fill in blank
hardFill both blanks to correctly remove the last added number after backtracking.
DSA Java
tempList.[1](tempList.[2]() - 1);
Attempts:
3 left
💡 Hint
Common Mistakes
Using add instead of remove.
Using get instead of size for index.
✗ Incorrect
We remove the element at index size() - 1 to backtrack correctly.
5fill in blank
hardFill all three blanks to correctly start backtracking and add valid combinations.
DSA Java
if (tempList.size() == [1] && [2] == 0) { result.[3](new ArrayList<>(tempList)); return; }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking wrong variables for size or sum.
Using wrong method to add to result.
✗ Incorrect
Check if size equals k and sum left (n) is zero, then add the combination to result.
