Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the inversion count variable.
DSA Java
int countInversions(int[] arr) {
int [1] = 0;
// rest of the code
return 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that is too generic or unclear.
Forgetting to initialize the variable.
✗ Incorrect
The variable 'count' is commonly used to keep track of the number of inversions.
2fill in blank
mediumComplete the code to compare elements for inversion detection.
DSA Java
for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] [1] arr[j]) { count++; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' which counts non-inversions.
Using '==' which does not detect inversions.
✗ Incorrect
An inversion is when a larger number appears before a smaller number, so arr[i] > arr[j].
3fill in blank
hardFix the error in the merge step to count split inversions correctly.
DSA Java
while (i < left.length && j < right.length) { if (left[i] <= right[j]) { merged[k++] = left[i++]; } else { merged[k++] = right[j++]; [1] += (left.length - i); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name causing compilation errors.
Not incrementing the inversion count at all.
✗ Incorrect
The variable 'count' is used to accumulate the number of inversions during merging.
4fill in blank
hardFill both blanks to complete the merge function that counts inversions.
DSA Java
int mergeAndCount(int[] left, int[] right, int[] merged) {
int i = 0, j = 0, k = 0, [1] = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
merged[k++] = left[i++];
} else {
merged[k++] = right[j++];
[2] += (left.length - i);
}
}
while (i < left.length) merged[k++] = left[i++];
while (j < right.length) merged[k++] = right[j++];
return [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for counting and returning.
Forgetting to return the count.
✗ Incorrect
The variable 'count' is used to track and return the number of inversions found during merging.
5fill in blank
hardFill all three blanks to complete the recursive merge sort that counts inversions.
DSA Java
int mergeSortAndCount(int[] arr) {
if (arr.length < 2) return 0;
int mid = arr.length / 2;
int[] left = Arrays.copyOfRange(arr, 0, [1]);
int[] right = Arrays.copyOfRange(arr, [2], arr.length);
int count = mergeSortAndCount(left) + mergeSortAndCount(right);
count += mergeAndCount(left, right, arr);
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices for splitting arrays.
Returning the wrong variable at the end.
✗ Incorrect
The array is split at 'mid', left is from 0 to mid, right is from mid to end, and the total count is returned.
