πDay 3. Count Inversions π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
Given an array of integers arr[]. Find the Inversion Count in the array.
Two elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.
Inversion Count indicates how far (or close) the array is from being sorted:
If the array is already sorted, the inversion count is 0.
If the array is sorted in reverse order, the inversion count is maximum.
π Example Walkthrough:
Input:
arr[] = [2, 4, 1, 3, 5]
Output:
3
Explanation:
The sequence 2, 4, 1, 3, 5 has three inversions: (2, 1), (4, 1), (4, 3).
Input:
arr[] = [2, 3, 4, 5, 6]
Output:
0
Explanation: The array is already sorted, so there are no inversions.
Input:
arr[] = [10, 10, 10]
Output:
0
Explanation: All elements of the array are the same, so there are no inversions.
Constraints:
$
1 β€ arr.size() β€ 10^5$$
1 β€ arr[i] β€ 10^4$
π― My Approach:
Merge Sort-Based Counting:
The problem can be efficiently solved using a modified Merge Sort algorithm.
During the merge step, count the number of inversions based on the positions of elements in the two halves.
Steps:
Divide: Recursively divide the array into two halves.
Merge: Merge the two halves while counting inversions.
Count Inversions: For every pair
(i, j)wherearr[i] > arr[j]andi < j, increment the count.
Advantages:
This approach efficiently counts inversions with a time complexity of O(n log n), compared to the naive O(n^2) method.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n), as the algorithm performs a logarithmic number of merge steps, with each step taking linear time.
Expected Auxiliary Space Complexity: O(n), as we use an additional array for temporary storage during the merge process.
π Solution Code
Code (C)
Code (Cpp)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated