Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two elements in the array.
DSA C++
void swap(int &a, int &b) {
int temp = a;
a = [1];
b = temp;
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning 'a' to 'temp' again instead of 'b'.
Forgetting to use reference parameters.
✗ Incorrect
To swap two variables, assign 'a' the value of 'b'.
2fill in blank
mediumComplete the code to generate permutations by swapping elements.
DSA C++
void permute(int arr[], int l, int r) {
if (l == r) {
// print permutation
for (int i = 0; i <= r; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
} else {
for (int i = l; i <= r; i++) {
swap(arr[l], arr[[1]]);
permute(arr, l + 1, r);
swap(arr[l], arr[i]);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with 'l' instead of 'i' causing no change.
Using 'r' which is the end index, not the loop index.
✗ Incorrect
We swap the element at position 'l' with the element at position 'i' to generate permutations.
3fill in blank
hardFix the error in the base case condition to correctly detect when to print a permutation.
DSA C++
void permute(int arr[], int l, int r) {
if (l [1] r) {
for (int i = 0; i <= r; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
} else {
for (int i = l; i <= r; i++) {
swap(arr[l], arr[i]);
permute(arr, l + 1, r);
swap(arr[l], arr[i]);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' which causes printing at wrong times.
Using '<' or '>' which never triggers the base case properly.
✗ Incorrect
The base case is when the left index equals the right index, meaning one permutation is ready to print.
4fill in blank
hardFill both blanks to create a function that prints all permutations of an array.
DSA C++
void printPermutations(int arr[], int n) {
permute(arr, [1], [2]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'n' as last index causes out-of-bounds errors.
Starting from 1 misses the first element.
✗ Incorrect
We start from index 0 and go up to n-1 to cover the whole array.
5fill in blank
hardFill all three blanks to complete the main function that calls permutation printing.
DSA C++
#include <iostream> int main() { int arr[] = {1, 2, 3}; int n = sizeof(arr) / sizeof([1]); printPermutations(arr, [2]); return [3]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '1' instead of '0' in sizeof calculation.
Returning 1 instead of 0 in main.
✗ Incorrect
We calculate size using 'arr[0]', pass 'n' to printPermutations, and return 0 to indicate successful program end.
