Reverse Pairs
LeetCode 493 · కఠినం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Merge sort; count cross pairs before each merge.
నేను Reverse Pairs (LeetCode 493) ను ఇలా పరిష్కరించాను — Advanced / Mixed ప్యాటర్న్లోని ఒక కఠినం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Like counting inversions with merge sort. Before merging two sorted halves, count pairs with left[i] > 2·right[j] using two pointers — because both halves are sorted, once left[i] qualifies, every later left element does too.
Approach
- 1
Split recursively and sort each half.
- 2
Two pointers: if left[i] > 2·right[j], add len(left) − i and advance j; else advance i.
- 3
Then merge normally.
నేను ఎలా పరిష్కరించాను
Merge sort countingPythonO(n log n) time
class Solution:
def merge(self, left, right, obj):
result = []
l = r = 0
i = j = 0
while i < len(left) and j < len(right):
if left[i] > 2 * right[j]:
obj["count"] += len(left) - i
j += 1
else:
i += 1
while l < len(left) and r < len(right):
if left[l] < right[r]:
result.append(left[l]); l += 1
else:
result.append(right[r]); r += 1
return result + left[l:] + right[r:]
def mergeSort(self, arr, obj):
length = len(arr)
if length < 2:
return arr
midPoint = length // 2
left = arr[:midPoint]
right = arr[midPoint:]
return self.merge(self.mergeSort(left, obj), self.mergeSort(right, obj), obj)
def reversePairs(self, arr):
obj = {"count": 0}
self.mergeSort(arr, obj)
return obj["count"]Reverse Pairs — తరచూ అడిగే ప్రశ్నలు
Reverse Pairs వెనుక ఉన్న intuition ఏమిటి?
Like counting inversions with merge sort. Before merging two sorted halves, count pairs with left[i] > 2·right[j] using two pointers — because both halves are sorted, once left[i] qualifies, every later left element does too.
Reverse Pairs (LeetCode 493) ను ఎలా పరిష్కరించాలి?
1. Split recursively and sort each half. 2. Two pointers: if left[i] > 2·right[j], add len(left) − i and advance j; else advance i. 3. Then merge normally.
Reverse Pairs యొక్క time, space complexity ఎంత?
Time: O(n log n). Space: O(n). (Accepted approach: Merge sort counting.)
Reverse Pairs లో సాధారణ పొరపాట్లు ఏమిటి?
Count before merging — the halves must still be separate.