Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two integers using a temporary variable.
DSA C++
void swap(int &a, int &b) {
int temp = [1];
a = b;
b = temp;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'b' instead of 'a' for the temporary variable.
Not using a temporary variable and losing data.
✗ Incorrect
We store the value of 'a' in 'temp' before overwriting 'a' with 'b'. This preserves the original value of 'a' to assign to 'b'.
2fill in blank
mediumComplete the code to merge two sorted arrays without extra space by comparing elements.
DSA C++
for (int i = 0; i < n; i++) { if (arr1[i] > [1]) { swap(arr1[i], arr2[0]); // After swap, sort arr2 again } }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with the last element of arr2 instead of the first.
Comparing with elements of arr1 instead of arr2.
✗ Incorrect
We compare arr1[i] with the first element of arr2 because arr2 is sorted, so the smallest element is at index 0.
3fill in blank
hardFix the error in the code that sorts the second array after swapping.
DSA C++
void sortSecondArray(int arr2[], int n) {
for (int i = 1; i < n && arr2[i] < arr2[i - 1]; i++) {
std::swap(arr2[i], arr2[[1]]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with the next element instead of the previous.
Swapping with a fixed index like 0 or n-1.
✗ Incorrect
We swap the current element arr2[i] with the previous element arr2[i - 1] to move the smaller element leftwards.
4fill in blank
hardFill both blanks to complete the function that merges two sorted arrays without extra space.
DSA C++
void merge(int arr1[], int arr2[], int n, int m) {
for (int i = 0; i < n; i++) {
if (arr1[i] > [1]) {
std::swap(arr1[i], arr2[0]);
int first = 0;
int second = 1;
while (second < m && arr2[second] < arr2[[2]]) {
std::swap(arr2[first], arr2[second]);
first++;
second++;
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices for comparison causing incorrect sorting.
Confusing array indices with array values.
✗ Incorrect
We compare arr1[i] with the smallest element arr2[0]. Then, in the while loop, we compare arr2[second] with arr2[0] to bubble the swapped element to correct position.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps elements to their counts if count is greater than zero.
DSA C++
std::map<int, int> countMap; // Assume countMap is filled with counts std::map<int, int> filteredMap = { [1], [2]: [3] for (auto const& [key, val] : countMap) if (val > 0) };
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping key and val positions.
Using incorrect syntax for map comprehension.
✗ Incorrect
We map key to val for all entries where val > 0. The comprehension syntax uses key and val accordingly.
