712345. Count Reverse Pairs

Hard

Count Reverse Pairs

Summary

The problem "Count Reverse Pairs" involves counting the number of reverse pairs in an array of integers. A pair is considered reverse if its elements are reversed. For example, (1, 2) and (2, 1) are reverse pairs. This problem requires us to write a program that counts the total number of reverse pairs present in the given array.

Detailed Explanation

To solve this problem, we can use a two-pointer technique. The idea is to sort the input array and then count the number of reverse pairs as we iterate through it. Here's how it works:

  1. First, we create an empty list to store the counted reverse pairs.
  2. Then, we sort the input array in ascending order using the sort() function.
  3. Next, we initialize two pointers, left and right, at the beginning and end of the sorted array respectively.
  4. We enter a loop that continues until the left pointer meets the right pointer.
  5. Inside the loop, we count the reverse pairs by checking if the elements at the left and right pointers are in reverse order. If they are, we increment our count and move both pointers towards each other.
  6. We continue this process until all possible reverse pairs have been counted.

The time complexity of this solution is O(n log n) due to the sorting step, where n is the number of elements in the input array. The space complexity is O(1) as we only use a constant amount of extra space to store our count.

Here's an ASCII art diagram illustrating the two-pointer technique:

  +-----------+       +-----------+
  |          |       |          |
  |  left    |  right   |          |
  +-----------+       +-----------+
  |         (1, 2)     |         (3, 4)
  |         (1, 2)     |         (3, 4)
  +-----------+       +-----------+

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println(countReversePairs(arr));
    }

    public static int countReversePairs(int[] arr) {
        Arrays.sort(arr);
        int count = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = arr.length - 1; j > i; j--) {
                if (arr[i] > arr[j]) {
                    count++;
                }
            }
        }
        return count;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.