Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start backtracking from the first position.
DSA C#
void Backtrack(int pos) {
if (pos == n) {
PrintSolution();
return;
}
for (int i = 0; i < choices; i++) {
if (IsValid(pos, i)) {
solution[pos] = i;
Backtrack([1]);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pos - 1 causes infinite recursion backward.
Using 0 resets position incorrectly.
Using choices as position is out of range.
✗ Incorrect
In backtracking, after choosing an option at position pos, we move to the next position pos + 1 to continue exploring.
2fill in blank
mediumComplete the code to check if the current choice is valid at position pos.
DSA C#
bool IsValid(int pos, int choice) {
for (int i = 0; i < pos; i++) {
if (solution[i] == [1]) {
return false;
}
}
return true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing solution[i] with pos is incorrect.
Comparing solution[i] with i is meaningless here.
✗ Incorrect
We check if the current choice conflicts with any previous choice stored in solution[i]. So we compare solution[i] with choice.
3fill in blank
hardFix the error in the backtracking base case to stop recursion correctly.
DSA C#
void Backtrack(int pos) {
if (pos [1] n) {
PrintSolution();
return;
}
// rest of code
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pos < n causes premature stopping.
Using pos > n is incorrect as pos never exceeds n.
Using pos <= n causes extra calls.
✗ Incorrect
The base case should check if pos equals n, meaning all positions are filled, then print the solution and stop.
4fill in blank
hardFill both blanks to generate all subsets of a set using backtracking.
DSA C#
void GenerateSubsets(int index, List<int> current) {
if (index == n) {
PrintSubset(current);
return;
}
// Include element
current.Add([1]);
GenerateSubsets(index [2] 1, current);
current.RemoveAt(current.Count - 1);
// Exclude element
GenerateSubsets(index + 1, current);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using index - 1 moves backward incorrectly.
Using n as element index causes out of range.
Not incrementing index causes infinite recursion.
✗ Incorrect
To include the current element, add it using index as the element's position. Then move to next index by index + 1.
5fill in blank
hardFill all three blanks to implement backtracking for generating permutations.
DSA C#
void Permute(List<int> nums, int start) {
if (start == nums.Count) {
PrintPermutation(nums);
return;
}
for (int i = [1]; i < nums.Count; i++) {
Swap(nums, start, i);
Permute(nums, [2]);
Swap(nums, start, i);
}
}
void Swap(List<int> list, int a, int b) {
int temp = list[a];
list[a] = list[b];
list[b] = [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop at 0 causes duplicate permutations.
Not incrementing start causes infinite recursion.
Swapping back incorrectly breaks the list.
✗ Incorrect
The loop starts at start to swap elements. After swapping, recurse with start + 1. Swap back using temp to restore order.
