4Sum
LeetCode 18 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Two fixed loops + two pointers, skipping duplicates at each level.
ನಾನು 4Sum (LeetCode 18) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Two Pointers ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Extend 3Sum by one more loop: sort, fix two numbers with nested loops, then use two pointers for the last pair. Skipping equal neighbours at every level keeps the quadruplets unique.
Approach
- 1
Sort.
- 2
Loop i, skipping repeats; loop j > i, skipping repeats.
- 3
Two pointers for the remaining pair; move by comparing the sum to the target.
- 4
On a hit, record it and skip duplicates on both sides.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Sort + 2 loops + two pointersPythonO(n³) time
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
res = []
for i in range(n-3):
if i>0 and nums[i]==nums[i-1]:
continue
for j in range(i+1,n):
if j>i+1 and nums[j]==nums[j-1]:
continue
left = j+1
right = n-1
while left<right:
cur_sum = nums[i]+nums[j]+nums[left]+nums[right]
if cur_sum<target:
left+=1
elif cur_sum>target:
right-=1
else:
res.append([nums[i],nums[j],nums[left],nums[right]])
left+=1
right-=1
while left<right and nums[left]==nums[left-1]:
left+=1
while left<right and nums[right]==nums[right+1]:
right-=1
return res4Sum — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
4Sum ಹಿಂದಿನ intuition ಏನು?
Extend 3Sum by one more loop: sort, fix two numbers with nested loops, then use two pointers for the last pair. Skipping equal neighbours at every level keeps the quadruplets unique.
4Sum (LeetCode 18) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Sort. 2. Loop i, skipping repeats; loop j > i, skipping repeats. 3. Two pointers for the remaining pair; move by comparing the sum to the target. 4. On a hit, record it and skip duplicates on both sides.
4Sum ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n³). Space: O(1) extra. (Accepted approach: Sort + 2 loops + two pointers.)
4Sum ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Skip duplicates for i, j, left and right — missing any produces repeated answers.