Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 18 · Two Pointers

4Sum

LeetCode 18 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Two fixed loops + two pointers, skipping duplicates at each level.

நடுத்தரம்ArrayTwo PointersSorting
LeetCode இல் திற ↗

நான் 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. 1

    Sort.

  2. 2

    Loop i, skipping repeats; loop j > i, skipping repeats.

  3. 3

    Two pointers for the remaining pair; move by comparing the sum to the target.

  4. 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 res
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

4Sum — அடிக்கடி கேட்கப்படும் கேள்விகள்

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.