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[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[1];
arr[j] = temp;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using arr[i] instead of arr[j] causes no change.
Using an invalid index like j + 1 causes errors.
✗ Incorrect
To swap elements at positions i and j, assign arr[i] = arr[j].
2fill in blank
mediumComplete the code to generate permutations by recursion.
DSA C#
void Permute(int[] arr, int start, int end) {
if (start == end) {
PrintArray(arr);
} else {
for (int i = start; i <= [1]; i++) {
Swap(arr, start, i);
Permute(arr, start + 1, end);
Swap(arr, start, i);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using arr.Length causes index out of range errors.
Using end - 1 misses the last element.
✗ Incorrect
The loop runs from start to end inclusive to cover all permutations.
3fill in blank
hardFix the error in the base case condition to correctly print permutations.
DSA C#
void Permute(int[] arr, int start, int end) {
if (start [1] end) {
PrintArray(arr);
} else {
for (int i = start; i <= end; i++) {
Swap(arr, start, i);
Permute(arr, start + 1, end);
Swap(arr, start, i);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '>' causes infinite recursion or missed base case.
Using '!=' prints permutations too early.
✗ Incorrect
The base case is when start equals end, meaning one permutation is ready to print.
4fill in blank
hardFill both blanks to correctly print the array elements separated by spaces.
DSA C#
void PrintArray(int[] arr) {
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i][1]);
}
Console.WriteLine([2]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using ", " adds commas which are not needed.
Using "\n" in WriteLine adds extra new lines.
✗ Incorrect
We add a space after each element and print a space line break after the loop.
5fill in blank
hardFill all three blanks to call the permutation function correctly for an array.
DSA C#
int[] arr = {1, 2, 3};
int n = arr[1];
Permute(arr, [2], [3]);Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as start index skips the first element.
Using arr.Length as end index causes out of range error.
✗ Incorrect
We get the array length, start from index 0, and end at last index (length - 1).
