Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the inversion count variable.
DSA Go
func countInversions(arr []int) int {
inversions := [1]
// rest of the code
return inversions
}Attempts:
3 left
š” Hint
Common Mistakes
Initializing inversions to 1 or length of array instead of 0.
ā Incorrect
We start counting inversions from zero because initially, no pairs are counted.
2fill in blank
mediumComplete the code to compare elements for inversion detection.
DSA Go
for i := 0; i < len(arr); i++ { for j := i + 1; j < len(arr); j++ { if arr[i] [1] arr[j] { inversions++ } } }
Attempts:
3 left
š” Hint
Common Mistakes
Using '<' instead of '>' to compare elements.
ā Incorrect
An inversion is when a larger element appears before a smaller one, so arr[i] > arr[j].
3fill in blank
hardFix the error in the merge function to count cross inversions correctly.
DSA Go
func merge(arr []int, temp []int, left, mid, right int) int {
i, j, k := left, mid+1, left
invCount := 0
for i <= mid && j <= right {
if arr[i] <= arr[j] {
temp[k] = arr[i]
i++
k++
} else {
temp[k] = arr[j]
invCount += [1]
j++
k++
}
}
// rest of merge code
return invCount
}Attempts:
3 left
š” Hint
Common Mistakes
Using wrong indices to count inversions in merge step.
ā Incorrect
When arr[i] > arr[j], all elements from i to mid form inversions with arr[j].
4fill in blank
hardFill both blanks to complete the recursive merge sort call and inversion count addition.
DSA Go
func mergeSort(arr []int, temp []int, left, right int) int {
invCount := 0
if left < right {
mid := (left + right) / 2
invCount += mergeSort(arr, temp, left, [1])
invCount += mergeSort(arr, temp, [2], right)
invCount += merge(arr, temp, left, mid, right)
}
return invCount
}Attempts:
3 left
š” Hint
Common Mistakes
Using mid+1 for left half or mid for right half incorrectly.
ā Incorrect
Left half is from left to mid, right half is from mid+1 to right.
5fill in blank
hardFill all three blanks to complete the merge function copying remaining elements.
DSA Go
for i <= mid { temp[[1]] = arr[[2]] i++ [3]++ } for j <= right { temp[k] = arr[j] j++ k++ }
Attempts:
3 left
š” Hint
Common Mistakes
Mixing indices i and k incorrectly while copying.
ā Incorrect
Copy remaining left elements from arr[i] to temp[k], increment i and k.
