1. Nested Double Loop Comparison
Intuition
Exhaustively check every possible pair to verify the inversion condition.
Algorithm
- Step 1: Initialize inversion counter = 0.
- Step 2: Loop i from 0 to n - 2.
- Step 3: Loop j from i + 1 to n - 1.
- Step 4: If arr[i] > arr[j], increment counter by 1.
- Step 5: Return counter.
Nested Double Loop Comparison Trace
2 of 2 questions left todayInput arr = [2, 4, 1, 3, 5]
Input arr = [2, 4, 1, 3, 5]. Initialize inversions = 0. Start outer loop i = 0 (val = 2).
#include <iostream>#include <vector> class Solution {public: long long countInversions(const std::vector<int>& arr) { long long count = 0; int n = arr.size(); for (int i = 0; i < n - 1; ++i) { for (int j = i + 1; j < n; ++j) { if (arr[i] > arr[j]) { count++; } } } return count; }}; int main() { Solution solver; std::vector<int> arr = {2, 4, 1, 3, 5}; std::cout << "Inversions: " << solver.countInversions(arr) << std::endl; // 3 return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Nested Double Loop Comparison. - Space complexity:
O(1)— Space complexity for Nested Double Loop Comparison.
Why Brute Force Doesn't Scale:
For N = 100,000, N2 = 1010 operations, which times out.
Merge Sort Count completes in ~1.7 * 106 operations, executing in ~25 milliseconds.