LeetCode 493: Reverse Pairs Solution
Master LeetCode problem 493 (Reverse Pairs), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
493. Reverse Pairs
Problem Explanation
Explanation
To solve this problem efficiently, we can use a modified merge sort algorithm. The idea is to count the number of reverse pairs while merging the two sorted halves of the array. When we compare elements from the left half with elements from the right half, if we find a pair (i, j) such that nums[i] > 2 * nums[j], then we increment the count of reverse pairs by the number of elements remaining in the left half. This is because if nums[i] is greater than 2 * nums[j], then it's also greater than 2 * nums[j+1], 2 * nums[j+2], and so on.
Algorithm:
- Define a recursive function
mergeSortAndCountthat takes the arraynums, start indexstart, and end indexend. - If
start >= end, return 0. - Calculate the mid index as
(start + end) / 2and recursively callmergeSortAndCounton the left and right halves. - Merge the two sorted halves and count the reverse pairs while merging.
- Return the total count of reverse pairs.
Time Complexity:
- The time complexity of this approach is O(n log n), where n is the number of elements in the array.
Space Complexity:
- The space complexity is O(n) due to the extra space used for merging.
Solution Code
class Solution {
public int reversePairs(int[] nums) {
return mergeSortAndCount(nums, 0, nums.length - 1);
}
private int mergeSortAndCount(int[] nums, int start, int end) {
if (start >= end) return 0;
int mid = start + (end - start) / 2;
int count = mergeSortAndCount(nums, start, mid) + mergeSortAndCount(nums, mid + 1, end);
int j = mid + 1;
for (int i = start; i <= mid; i++) {
while (j <= end && nums[i] > 2L * nums[j]) j++;
count += j - (mid + 1);
}
Arrays.sort(nums, start, end + 1);
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 493 (Reverse Pairs)?
This page provides optimized solutions for LeetCode problem 493 (Reverse Pairs) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 493 (Reverse Pairs)?
The time complexity for LeetCode 493 (Reverse Pairs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 493 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 493 in Java, C++, or Python.