KatInterview

493. Reverse Pairs

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of "reverse pairs" (i, j) in an array nums such that i 2 * nums[j]. A naive approach using nested loops would be O(N²), which is too slow for the given constraint N <= 5 * 10^4. The condition i < j suggests that algorithms that process elements in order or use divide-and-conquer might be suitable. The structure of this problem is a classic fit for a modified Merge Sort algorithm.

Solution

Reverse Pairs in Python

class Solution:
    def reversePairs(self, nums: List[int]) -> int:
        
        def merge_sort_and_count(l, r):
            # Base case: if the subarray has 0 or 1 element, no reverse pairs.
            if l >= r:
                return 0
            
            # Divide the array into two halves.
            mid = (l + r) // 2
            
            # Recursively count pairs in left and right halves.
            count = merge_sort_and_count(l, mid) + merge_sort_and_count(mid + 1, r)
            
            # Count pairs where one element is in the left half and the other is in the right half.
            j = mid + 1
            for i in range(l, mid + 1):
                while j <= r and nums[i] > 2 * nums[j]:
                    j += 1
                count += j - (mid + 1)
            
            # Merge the two sorted halves.
            # This can be done with a temporary list and pointers, or simply by sorting the slice.
            # Manual merge is more efficient (O(N)) than sorted() (O(N log N)).
            temp = []
            p1, p2 = l, mid + 1
            while p1 <= mid and p2 <= r:
                if nums[p1] <= nums[p2]:
                    temp.append(nums[p1])
                    p1 += 1
                else:
                    temp.append(nums[p2])
                    p2 += 1
            
            while p1 <= mid:
                temp.append(nums[p1])
                p1 += 1
            
            while p2 <= r:
                temp.append(nums[p2])
                p2 += 1
            
            # Copy the merged and sorted elements back to the original array slice.
            for i in range(len(temp)):
                nums[l + i] = temp[i]

            return count

        return merge_sort_and_count(0, len(nums) - 1)

Reverse Pairs in Java

class Solution {
    public int reversePairs(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        return mergeSort(nums, 0, nums.length - 1);
    }

    private int mergeSort(int[] nums, int left, int right) {
        // Base case: if the array has 0 or 1 element, no reverse pairs.
        if (left >= right) {
            return 0;
        }

        // Divide the array into two halves.
        int mid = left + (right - left) / 2;

        // Recursively count pairs in left and right halves.
        int count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right);

        // Count pairs where one element is in the left half and the other is in the right half.
        int j = mid + 1;
        for (int i = left; i <= mid; i++) {
            // Use long to prevent overflow.
            while (j <= right && (long) nums[i] > 2L * nums[j]) {
                j++;
            }
            count += j - (mid + 1);
        }

        // Merge the two sorted halves.
        int[] temp = new int[right - left + 1];
        int p1 = left, p2 = mid + 1, k = 0;
        while (p1 <= mid && p2 <= right) {
            if (nums[p1] <= nums[p2]) {
                temp[k++] = nums[p1++];
            } else {
                temp[k++] = nums[p2++];
            }
        }
        while (p1 <= mid) {
            temp[k++] = nums[p1++];
        }
        while (p2 <= right) {
            temp[k++] = nums[p2++];
        }

        // Copy the merged and sorted elements back to the original array.
        System.arraycopy(temp, 0, nums, left, temp.length);

        return count;
    }
}

Reverse Pairs in C++

class Solution {
public:
    int reversePairs(vector<int>& nums) {
        if (nums.empty()) {
            return 0;
        }
        return mergeSort(nums, 0, nums.size() - 1);
    }

private:
    int mergeSort(vector<int>& nums, int left, int right) {
        // Base case: if the array has 0 or 1 element, no reverse pairs.
        if (left >= right) {
            return 0;
        }

        // Divide the array into two halves.
        int mid = left + (right - left) / 2;

        // Recursively count pairs in left and right halves.
        int count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right);

        // Count pairs where one element is in the left half and the other is in the right half.
        int j = mid + 1;
        for (int i = left; i <= mid; ++i) {
            // Use long long to prevent overflow.
            while (j <= right && (long long)nums[i] > 2LL * nums[j]) {
                j++;
            }
            count += j - (mid + 1);
        }

        // Merge the two sorted halves.
        vector<int> temp;
        int p1 = left, p2 = mid + 1;
        while (p1 <= mid && p2 <= right) {
            if (nums[p1] <= nums[p2]) {
                temp.push_back(nums[p1++]);
            } else {
                temp.push_back(nums[p2++]);
            }
        }
        while (p1 <= mid) {
            temp.push_back(nums[p1++]);
        }
        while (p2 <= right) {
            temp.push_back(nums[p2++]);
        }

        // Copy the merged and sorted elements back to the original array.
        for (int i = 0; i < temp.size(); ++i) {
            nums[left + i] = temp[i];
        }

        return count;
    }
};

Reverse Pairs in TypeScript

function reversePairs(nums: number[]): number {
    if (nums === null || nums.length === 0) {
        return 0;
    }

    function mergeSort(left: number, right: number): number {
        // Base case: if the array has 0 or 1 element, no reverse pairs.
        if (left >= right) {
            return 0;
        }

        // Divide the array into two halves.
        const mid = Math.floor(left + (right - left) / 2);

        // Recursively count pairs in left and right halves.
        let count = mergeSort(left, mid) + mergeSort(mid + 1, right);

        // Count pairs where one element is in the left half and the other is in the right half.
        let j = mid + 1;
        for (let i = left; i <= mid; i++) {
            // JavaScript/TypeScript numbers are 64-bit floats, so overflow is not an issue for typical integer ranges.
            while (j <= right && nums[i] > 2 * nums[j]) {
                j++;
            }
            count += j - (mid + 1);
        }

        // Merge the two sorted halves.
        const temp: number[] = [];
        let p1 = left, p2 = mid + 1;
        while (p1 <= mid && p2 <= right) {
            if (nums[p1] <= nums[p2]) {
                temp.push(nums[p1++]);
            } else {
                temp.push(nums[p2++]);
            }
        }
        while (p1 <= mid) {
            temp.push(nums[p1++]);
        }
        while (p2 <= right) {
            temp.push(nums[p2++]);
        }

        // Copy the merged and sorted elements back to the original array.
        for (let i = 0; i < temp.length; i++) {
            nums[left + i] = temp[i];
        }

        return count;
    }

    return mergeSort(0, nums.length - 1);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.