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.