Bird
Raised Fist0
DSA Cprogramming~20 mins

Count Inversions in Array in DSA C - 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
Count inversions in a small array
What is the output of the following C code that counts inversions in the array?
DSA C
#include <stdio.h>

int merge(int arr[], int temp[], int left, int mid, int right) {
    int i = left, j = mid, k = left, inv_count = 0;
    while ((i <= mid - 1) && (j <= right)) {
        if (arr[i] <= arr[j]) {
            temp[k++] = arr[i++];
        } else {
            temp[k++] = arr[j++];
            inv_count += (mid - i);
        }
    }
    while (i <= mid - 1)
        temp[k++] = arr[i++];
    while (j <= right)
        temp[k++] = arr[j++];
    for (i = left; i <= right; i++)
        arr[i] = temp[i];
    return inv_count;
}

int mergeSort(int arr[], int temp[], int left, int right) {
    int mid, inv_count = 0;
    if (right > left) {
        mid = (right + left) / 2;
        inv_count += mergeSort(arr, temp, left, mid);
        inv_count += mergeSort(arr, temp, mid + 1, right);
        inv_count += merge(arr, temp, left, mid + 1, right);
    }
    return inv_count;
}

int main() {
    int arr[] = {2, 4, 1, 3, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int temp[n];
    int result = mergeSort(arr, temp, 0, n - 1);
    printf("%d\n", result);
    return 0;
}
A3
B4
C2
D5
Attempts:
2 left
💡 Hint
Count pairs (i, j) where i < j and arr[i] > arr[j].
🧠 Conceptual
intermediate
1:30remaining
Understanding inversion count concept
Which of the following best describes what an inversion in an array means?
AA pair of elements where the first is smaller and appears before the second.
BA pair of elements where the first is larger and appears before the second.
CA pair of elements that are equal and adjacent.
DA pair of elements where the second is larger and appears before the first.
Attempts:
2 left
💡 Hint
Think about pairs that are out of order.
❓ Predict Output
advanced
2:00remaining
Count inversions in a reversed array
What is the output of the following C code counting inversions in a reversed array?
DSA C
#include <stdio.h>

int merge(int arr[], int temp[], int left, int mid, int right) {
    int i = left, j = mid, k = left, inv_count = 0;
    while ((i <= mid - 1) && (j <= right)) {
        if (arr[i] <= arr[j]) {
            temp[k++] = arr[i++];
        } else {
            temp[k++] = arr[j++];
            inv_count += (mid - i);
        }
    }
    while (i <= mid - 1)
        temp[k++] = arr[i++];
    while (j <= right)
        temp[k++] = arr[j++];
    for (i = left; i <= right; i++)
        arr[i] = temp[i];
    return inv_count;
}

int mergeSort(int arr[], int temp[], int left, int right) {
    int mid, inv_count = 0;
    if (right > left) {
        mid = (right + left) / 2;
        inv_count += mergeSort(arr, temp, left, mid);
        inv_count += mergeSort(arr, temp, mid + 1, right);
        inv_count += merge(arr, temp, left, mid + 1, right);
    }
    return inv_count;
}

int main() {
    int arr[] = {5, 4, 3, 2, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    int temp[n];
    int result = mergeSort(arr, temp, 0, n - 1);
    printf("%d\n", result);
    return 0;
}
A15
B5
C10
D0
Attempts:
2 left
💡 Hint
Count all pairs where a bigger number appears before a smaller one in a reversed array.
🔧 Debug
advanced
2:00remaining
Identify the bug in inversion count code
What error will the following code produce when counting inversions?
DSA C
#include <stdio.h>

int merge(int arr[], int temp[], int left, int mid, int right) {
    int i = left, j = mid, k = left, inv_count = 0;
    while ((i <= mid) && (j <= right)) {
        if (arr[i] <= arr[j]) {
            temp[k++] = arr[i++];
        } else {
            temp[k++] = arr[j++];
            inv_count += (mid - i + 1);
        }
    }
    while (i <= mid)
        temp[k++] = arr[i++];
    while (j <= right)
        temp[k++] = arr[j++];
    for (i = left; i <= right; i++)
        arr[i] = temp[i];
    return inv_count;
}

int mergeSort(int arr[], int temp[], int left, int right) {
    int mid, inv_count = 0;
    if (right > left) {
        mid = (right + left) / 2;
        inv_count += mergeSort(arr, temp, left, mid);
        inv_count += mergeSort(arr, temp, mid + 1, right);
        inv_count += merge(arr, temp, left, mid + 1, right);
    }
    return inv_count;
}

int main() {
    int arr[] = {2, 3, 8, 6, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    int temp[n];
    int result = mergeSort(arr, temp, 0, n - 1);
    printf("%d\n", result);
    return 0;
}
AThe code outputs 4 instead of 5
BThe code causes an infinite loop
CThe code runs correctly and outputs 5
DThe code causes a segmentation fault
Attempts:
2 left
💡 Hint
Check the merge function's loop conditions and indices carefully.
🚀 Application
expert
2:30remaining
Find number of inversions after multiple updates
Given an array and multiple update operations that change elements, which data structure is best suited to efficiently count inversions after each update?
AQueue to process elements in order
BSimple array traversal after each update
CStack to store elements and count inversions
DSegment Tree with Merge Sort Tree or BIT with offline queries
Attempts:
2 left
💡 Hint
Think about data structures that support fast range queries and updates.

Practice

(1/5)
1. What does the term inversion in an array mean?
easy
A. The total number of elements in the array
B. A pair of elements where the first is greater than the second and appears before it
C. A pair of elements where the first is smaller than the second and appears before it
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 definition

    A pair of elements where the first is greater than the second and appears before it matches this definition exactly, others describe different concepts.
  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 = larger before smaller [OK]
Hint: Inversion means bigger number comes before smaller one [OK]
Common Mistakes:
  • Confusing inversion with sorted order
  • Thinking inversion counts equal elements
  • Mixing inversion with total pairs
2. Which of the following C code snippets correctly declares a function to count inversions in an array?
easy
A. int countInversions(int arr[], int n);
B. void countInversions(int arr[], int n);
C. int countInversions(int arr, int n[]);
D. int countInversions(int *arr, int n[]);

Solution

  1. Step 1: Check function signature correctness

    The function should return an integer count and take an integer array and its size as parameters.
  2. Step 2: Analyze each option

    int countInversions(int arr[], int n); correctly uses int return type and parameters as int arr[] and int n. Others have wrong parameter types or return type.
  3. Final Answer:

    int countInversions(int arr[], int n); -> Option A
  4. Quick Check:

    Correct function signature returns int and takes int array and size [OK]
Hint: Function returns int and takes int array plus size [OK]
Common Mistakes:
  • Using void return type instead of int
  • Swapping array and size parameter types
  • Using pointer syntax incorrectly
3. What is the output of the following C code snippet?
int arr[] = {2, 4, 1, 3, 5};
int n = 5;
int count = 0;
for(int i = 0; i < n-1; i++) {
  for(int j = i+1; j < n; j++) {
    if(arr[i] > arr[j]) count++;
  }
}
printf("%d", count);
medium
A. 5
B. 4
C. 3
D. 2

Solution

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

    Pairs where first element is greater than second: (2,1), (4,1), (4,3). Total = 3.
  2. Step 2: Confirm count variable increments correctly

    Nested loops check all pairs; count increments for each inversion found, total 3.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Inversions = 3 [OK]
Hint: Count pairs where left element > right element [OK]
Common Mistakes:
  • Counting pairs where left < right
  • Missing some inversion pairs
  • Off-by-one errors in loops
4. The following code is intended to count inversions but has a bug. What is the bug?
int countInversions(int arr[], int n) {
  int count = 0;
  for(int i = 0; i < n; i++) {
    for(int j = i; j < n; j++) {
      if(arr[i] >= arr[j]) count++;
    }
  }
  return count;
}
medium
A. Inner loop should start from j = i + 1, not j = i
B. The count variable should be initialized outside the function
C. The comparison should be arr[i] < arr[j]
D. The function should return void instead of int

Solution

  1. Step 1: Analyze loop ranges for counting pairs

    Inner loop starts at j = i, so it compares arr[i] with itself, causing incorrect counting.
  2. Step 2: Correct inner loop start index

    Inner loop should start at j = i + 1 to avoid self-comparison.
  3. Final Answer:

    Inner loop should start from j = i + 1, not j = i -> Option A
  4. Quick Check:

    Start inner loop at i+1 to avoid self-comparison [OK]
Hint: Inner loop must start after outer loop index [OK]
Common Mistakes:
  • Starting inner loop at same index as outer
  • Wrong comparison operator
  • Returning wrong type
5. Given the array {8, 4, 2, 1}, what is the total number of inversions? Also, explain why this number represents the worst case for inversion counting.
hard
A. 4
B. 0
C. 3
D. 6

Solution

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

    Pairs: (8,4), (8,2), (8,1), (4,2), (4,1), (2,1) total 6 inversions.
  2. Step 2: Understand why this is worst case

    The array is sorted in descending order, so every pair is inverted, maximum inversions possible for size 4.
  3. Final Answer:

    6 -> Option D
  4. Quick Check:

    Descending order array has max inversions = n(n-1)/2 [OK]
Hint: Descending order array has max inversions n(n-1)/2 [OK]
Common Mistakes:
  • Counting only adjacent inversions
  • Forgetting pairs with elements far apart
  • Confusing inversion count with array length
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