Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Count Inversions in Array in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
šŸŽ–ļø
Inversion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ā“ Predict Output
intermediate
2:00remaining
Output of inversion count for a small array
What is the output of the following JavaScript code that counts inversions in an array?
DSA Javascript
function countInversions(arr) {
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] > arr[j]) count++;
    }
  }
  return count;
}

console.log(countInversions([2, 4, 1, 3, 5]));
A3
B5
C2
D4
Attempts:
2 left
šŸ’” Hint
Count pairs where a number appears before a smaller number.
ā“ Predict Output
intermediate
2:00remaining
Output of inversion count using merge sort method
What is the output of this JavaScript code that counts inversions using a merge sort approach?
DSA Javascript
function mergeSort(arr) {
  if (arr.length <= 1) return {sorted: arr, count: 0};
  const mid = Math.floor(arr.length / 2);
  const left = mergeSort(arr.slice(0, mid));
  const right = mergeSort(arr.slice(mid));
  const merged = [];
  let i = 0, j = 0, count = left.count + right.count;
  while (i < left.sorted.length && j < right.sorted.length) {
    if (left.sorted[i] <= right.sorted[j]) {
      merged.push(left.sorted[i++]);
    } else {
      merged.push(right.sorted[j++]);
      count += left.sorted.length - i;
    }
  }
  while (i < left.sorted.length) merged.push(left.sorted[i++]);
  while (j < right.sorted.length) merged.push(right.sorted[j++]);
  return {sorted: merged, count};
}

const result = mergeSort([8, 4, 2, 1]);
console.log(result.count);
A7
B6
C4
D5
Attempts:
2 left
šŸ’” Hint
Count how many elements from left remain when picking from right during merge.
🧠 Conceptual
advanced
1:30remaining
Understanding inversion count complexity
What is the time complexity of counting inversions using the merge sort based method for an array of size n?
AO(n log n)
BO(n^2)
CO(log n)
DO(n)
Attempts:
2 left
šŸ’” Hint
Think about how merge sort divides and merges the array.
šŸ”§ Debug
advanced
2:00remaining
Identify the error in inversion count code
What error will this code produce when run?
DSA Javascript
function countInversions(arr) {
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] > arr[j]) count++;
    }
  }
  return count;
}

console.log(countInversions([1, 3, 2]));
AOutput: 1
BSyntaxError: Unexpected token
CTypeError: Cannot read property of undefined
DOutput: 0
Attempts:
2 left
šŸ’” Hint
Check the loop boundary for j.
šŸš€ Application
expert
2:30remaining
Count inversions in a large array efficiently
You have an array of 100,000 integers. Which approach is best to count inversions efficiently?
ASort the array and count inversions by comparing sorted positions (O(n log n))
BUse a nested loop to compare all pairs (O(n^2))
CUse a hash map to count inversions in O(n)
DUse merge sort based counting (O(n log n))
Attempts:
2 left
šŸ’” Hint
Consider time complexity for large n.

Practice

(1/5)
1. What does the term inversion mean in the context of an array?
easy
A. A pair of elements where the first is smaller than the second and appears before it
B. A pair of elements where the first is greater than the second and appears before it
C. The total number of elements in the array
D. The sum of all elements in the array

Solution

  1. Step 1: Understand the definition of inversion

    An inversion is when a larger number appears before a smaller number in the array.
  2. Step 2: Compare options with the definition

    A pair of elements where the first is greater than the second and appears before it correctly describes this as a pair where the first element is greater and comes before the second.
  3. Final Answer:

    A pair of elements where the first is greater than the second and appears before it -> Option B
  4. Quick Check:

    Inversion = pair (i, j) with i < j and arr[i] > arr[j] [OK]
Hint: Inversion means bigger number comes before smaller one [OK]
Common Mistakes:
  • Confusing inversion with sorted order
  • Thinking inversion counts pairs where first is smaller
  • Mixing inversion with total elements count
2. Which of the following JavaScript code snippets correctly initializes a variable to count inversions?
easy
A. int count = 0;
B. count := 0;
C. let count = 0;
D. var count == 0;

Solution

  1. Step 1: Identify correct JavaScript syntax for variable initialization

    JavaScript uses let or var with = for assignment.
  2. Step 2: Check each option

    let count = 0; uses let count = 0; which is correct. count := 0; uses ':=' which is not JavaScript. int count = 0; uses 'int' which is not JavaScript. var count == 0; uses '==' which is a comparison, not assignment.
  3. Final Answer:

    let count = 0; -> Option C
  4. Quick Check:

    Variable assignment in JS uses =, not := or == [OK]
Hint: Use let or var with = for assignment in JavaScript [OK]
Common Mistakes:
  • Using ':=' instead of '='
  • Using 'int' keyword from other languages
  • Using '==' instead of '=' for assignment
3. What is the number of inversions in the array [2, 4, 1, 3, 5]?
medium
A. 3
B. 2
C. 4
D. 5

Solution

  1. Step 1: Identify all inversion pairs in the array

    Check pairs where first element is greater and appears before second:
    - (2,1), (4,1), (4,3)
  2. Step 2: Count the total inversions

    There are 3 such pairs.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Pairs (2,1), (4,1), (4,3) = 3 inversions [OK]
Hint: Count pairs where earlier number is bigger than later [OK]
Common Mistakes:
  • Counting pairs where first is smaller
  • Missing some inversion pairs
  • Counting total pairs instead of inversions
4. Consider this code snippet to count inversions:
function countInversions(arr) {
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] < arr[j]) {
        count++;
      }
    }
  }
  return count;
}
What is the error in this code?
medium
A. The function should return arr.length instead of count
B. The inner loop should start from j = 0
C. The count variable should be initialized inside the loops
D. The comparison should be arr[i] > arr[j] to count inversions

Solution

  1. Step 1: Understand the inversion condition

    An inversion is when arr[i] > arr[j] and i < j, but code checks arr[i] < arr[j].
  2. Step 2: Identify the fix

    The comparison should be changed to arr[i] > arr[j] to count inversions correctly.
  3. Final Answer:

    The comparison should be arr[i] > arr[j] to count inversions -> Option D
  4. Quick Check:

    Inversion means first element bigger, so use > [OK]
Hint: Use > to detect inversion pairs, not < [OK]
Common Mistakes:
  • Using < instead of > in condition
  • Starting inner loop from 0 instead of i+1
  • Resetting count inside loops
5. Given the array [8, 4, 2, 1], which approach will efficiently count the number of inversions?
hard
A. Sort the array and count inversions during merge (O(n log n) time)
B. Count inversions by summing all elements
C. Use a nested loop to compare all pairs (O(n²) time)
D. Use a hash map to store counts of elements

Solution

  1. Step 1: Understand the problem size and efficiency

    For larger arrays, nested loops (O(n²)) are slow. Merge sort based counting is efficient (O(n log n)).
  2. Step 2: Identify the best approach

    Counting inversions during merge sort is a classic efficient method.
  3. Final Answer:

    Sort the array and count inversions during merge (O(n log n) time) -> Option A
  4. Quick Check:

    Merge sort inversion count = efficient O(n log n) [OK]
Hint: Use merge sort to count inversions efficiently [OK]
Common Mistakes:
  • Using nested loops for large arrays causing slow performance
  • Trying to sum elements instead of counting pairs
  • Using hash maps which don't help count inversions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard