Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the inversion count to zero.
DSA Javascript
let inversionCount = [1];Attempts:
3 left
š” Hint
Common Mistakes
Initializing inversionCount to 1 or null instead of 0.
Forgetting to initialize inversionCount before counting.
ā Incorrect
The inversion count should start at zero because initially no pairs are counted.
2fill in blank
mediumComplete the code to loop through the array elements for counting inversions.
DSA Javascript
for (let i = 0; i [1] arr.length - 1; i++) {
Attempts:
3 left
š” Hint
Common Mistakes
Using <= causes index out of range in inner loop.
Using > or >= causes the loop not to run correctly.
ā Incorrect
The loop should run while i is less than arr.length - 1 to avoid out-of-bound errors.
3fill in blank
hardFix the error in the inner loop condition to correctly count inversions.
DSA Javascript
for (let j = i + 1; j [1] arr.length; j++) {
Attempts:
3 left
š” Hint
Common Mistakes
Using <= causes index out of range error.
Using > or >= causes the loop to not run properly.
ā Incorrect
The inner loop should run while j is less than arr.length to cover all pairs after i.
4fill in blank
hardFill both blanks to correctly check and count an inversion pair.
DSA Javascript
if (arr[i] [1] arr[j]) { inversionCount [2]; }
Attempts:
3 left
š” Hint
Common Mistakes
Using '<' instead of '>' reverses the inversion logic.
Using '--' decreases the count incorrectly.
ā Incorrect
An inversion is when arr[i] is greater than arr[j], so we check '>' and increment the count with '++'.
5fill in blank
hardFill all three blanks to complete the function that counts inversions in an array.
DSA Javascript
function countInversions(arr) {
let inversionCount = [1];
for (let i = 0; i [2] arr.length - 1; i++) {
for (let j = i + 1; j [3] arr.length; j++) {
if (arr[i] > arr[j]) {
inversionCount++;
}
}
}
return inversionCount;
}Attempts:
3 left
š” Hint
Common Mistakes
Using <= in loops causes index errors.
Starting count at 1 or other values causes wrong results.
ā Incorrect
Initialize count to 0, loop i while less than length-1, and loop j while less than length.
