InterviewHubPRO
Section Overview
Q21

Question 21 of 100

Part 3: Two Pointers & Sliding Window (19 - 28)

21%
DSA Patterns (Multi-Lang)•Part 3: Two Pointers & Sliding Window (19 - 28)

3Sum.

In Simple Words: Sort the array. Fix element $i$ (skipping duplicates). Run Two Sum II with two pointers on the remainder to find nums[l] + nums[r] === -nums[i].

  • Time: $O(N^2)$ | Space: $O(1)$ auxiliary
Multi-Language Solutions
Switch tabs or choose All
def threeSum(nums: list[int]) -> list[list[int]]:
    nums.sort()
    res = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        l, r = i + 1, len(nums) - 1
        while l < r:
            total = nums[i] + nums[l] + nums[r]
            if total == 0:
                res.append([nums[i], nums[l], nums[r]])
                while l < r and nums[l] == nums[l + 1]: l += 1
                while l < r and nums[r] == nums[r - 1]: r -= 1
                l += 1; r -= 1
            elif total < 0:
                l += 1
            else:
                r -= 1
    return res