Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 16 · Two Pointers

3Sum Closest

LeetCode 16 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Sort + two pointers, tracking the smallest |target − sum|.

ಮಧ್ಯಮArrayTwo PointersSorting
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 3Sum Closest (LeetCode 16) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Two Pointers ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Sort, fix the first element, and run two pointers over the rest. Each step tells you whether the sum is below or above the target, so you know which pointer to move to get closer — and you track the closest sum seen.

Approach

  1. 1

    Sort the array.

  2. 2

    For each i, set left = i+1 and right = n−1.

  3. 3

    Update the best sum when |target − sum| improves; an exact hit returns immediately.

  4. 4

    Sum too small → left++, too big → right−−.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Sort + two pointersPythonO(n²) time · O(1) space
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        #sorting and two pointer technique
        #we need to minimize the difference
        #One loop will go -> i from 0- n-2
        #Another loop with two pointers - left ->i+1, right = n-1
        #have diff, compare and set it to minimum possible we found 
        #if the current difference at any point gets more then we need to increase the pointer from left else decrement from right
        nums.sort()
        diff = float("inf")
        n = len(nums)
        target_sum =0
        for i in range(n-2):
            left = i+1
            right=n-1
            while left<right:
                three_sum = nums[i]+nums[left]+nums[right]
                cur_diff = target-three_sum
                if cur_diff==0:
                    return target
                if abs(cur_diff)<diff:
                    diff = abs(cur_diff)
                    target_sum=three_sum
                
                if cur_diff>0:
                    left+=1
                else:
                    right-=1
        return target_sum
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

3Sum Closest — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

3Sum Closest ಹಿಂದಿನ intuition ಏನು?

Sort, fix the first element, and run two pointers over the rest. Each step tells you whether the sum is below or above the target, so you know which pointer to move to get closer — and you track the closest sum seen.

3Sum Closest (LeetCode 16) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Sort the array. 2. For each i, set left = i+1 and right = n−1. 3. Update the best sum when |target − sum| improves; an exact hit returns immediately. 4. Sum too small → left++, too big → right−−.

3Sum Closest ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n²). Space: O(1). (Accepted approach: Sort + two pointers.)

3Sum Closest ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Return the sum, not the difference.