703440. Subarray Inversions
Here is the detailed Markdown blog post for the "Subarray Inversions" problem:
Subarray Inversions
Slug: subarray-inversions0512 Difficulty: Medium Id: 703440 Topic Tags: Arrays, Data Structures Company Tags: None
Summary
The Subarray Inversions problem involves finding the number of inversions in a given array. An inversion occurs when an element is smaller than the next element in the array. The goal is to write an efficient algorithm that counts the total number of inversions in a given array.
Detailed Explanation
To solve this problem, we will use a simple and efficient approach called the Merge Sort algorithm. We will modify the merge function to count the number of inversions while merging two sorted subarrays.
Here's a step-by-step breakdown of the solution:
- Start by splitting the input array into two halves until each half contains only one element.
- Merge the two halves, counting the number of inversions as you go.
- Continue this process until the entire array is merged and the inversion count is calculated.
Here's a simple ASCII art diagram to illustrate the merge process:
[1, 3, 5] (left)
|
|
[2, 4, 6] (right)
Merged:
[1, 2, 3, 4, 5, 6]
Time complexity: O(n log n) where n is the number of elements in the array. Space complexity: O(n) for the recursive function calls.
Optimized Solutions
Java
public class SubarrayInversions {
public static int countInversions(int[] arr) {
if (arr.length <= 1) {
return 0;
}
int[] left = Arrays.copyOfRange(arr, 0, arr.length / 2);
int[] right = Arrays.copyOfRange(arr, arr.length / 2, arr.length);
int invCount = countInversions(left) + countInversions(right);
int i = 0;
int j = 0;
int k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
invCount += left.length - i;
}
}
System.arraycopy(left, i, arr, k, left.length - i);
System.arraycopy(right, j, arr, k + (left.length - i), right.length - j);
return invCount;
}
}