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

3Sum

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

Fix one, two-sum the rest with a hash set; dedupe via sorted tuples.

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

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

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

Intuition

Fix the first number, then the problem becomes two-sum for −nums[i] on the rest. A hash set finds each partner in one pass, and storing each triplet sorted inside a set removes duplicate answers.

Approach

  1. 1

    Skip a first element value already tried.

  2. 2

    For each later nums[j], the needed third value is −nums[i] − nums[j].

  3. 3

    If it was seen earlier in this inner loop, record the sorted triplet.

  4. 4

    Add nums[j] to the inner set and continue.

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

Fix one + hash-set two-sumPythonO(n²) time · O(n) space
"""
nums = [-1, -1, 0, 1]

nums[0]=-1 => [-1,0,1]
nums[1]=-1 => [-1,0,1]

So to optimize this we can check the fist element before taking it again
"""
class Solution:
    def threeSum(self, nums: list[int]) -> list[list[int]]:
      first_element_seen = set()
      seen = set()
      n = len(nums)
      res = set()
      for i in range(n):
            if nums[i] not in first_element_seen:
                first_element_seen.add(nums[i])
                hashset_2sum = set()
                for j in range(i+1,n):
                    remaining = 0 - nums[i]-nums[j]
                    if remaining in hashset_2sum:
                        triplet = tuple(sorted([nums[i],nums[j],remaining]))
                        res.add(triplet)
                    hashset_2sum.add(nums[j])
      return [list(item) for item in res]
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

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

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

Fix the first number, then the problem becomes two-sum for −nums[i] on the rest. A hash set finds each partner in one pass, and storing each triplet sorted inside a set removes duplicate answers.

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

1. Skip a first element value already tried. 2. For each later nums[j], the needed third value is −nums[i] − nums[j]. 3. If it was seen earlier in this inner loop, record the sorted triplet. 4. Add nums[j] to the inner set and continue.

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

Time: O(n²). Space: O(n). (Accepted approach: Fix one + hash-set two-sum.)

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

Without deduplication the same triplet appears many times. The sort-plus-two-pointers version avoids the result set.