🪙
Leetcode
  • Content
  • Algorithms
    • Linear Search
    • Binary Search
    • Counting Sort
    • Merge Sort
    • Insertion Sort
    • Selection Sort
  • Array and String
    • Introduction to Array
      • Introduction to Array
      • Introduction to Dynamic Array
      • Find Pivot Index
      • Largest Number At Least Twice of Others
      • Plus One
    • Introduction to 2D Array
      • Introduction to 2D Array
      • Diagonal Traverse
      • Spiral Matrix
      • Pascal's Triangle
    • Introduction to String
      • Introduction to String
      • Immutable String - Problems & Solutions
      • Add binary
      • Implement strStr()
      • Longest Common Prefix
    • Two-Pointer Technique
      • Two-pointer Technique - Scenario I
      • Reverse String
      • Array Partition I
      • Two Sum II - Input array is sorted
      • Two-pointer Technique - Scenario II
      • Remove Element
      • Max Consecutive Ones
      • Minimum Size Subarray Sum
    • Conclusion
      • Array-related Techniques
      • Rotate Array
      • Pascal's Triangle II
      • Reverse Words in a String
      • Reverse Words in a String III
      • Remove Duplicates from Sorted Array
      • Move Zeroes
  • Linked List
    • Singly Linked List
      • Introduction - Singly Linked List
      • Add Operation - Singly Linked List
      • Delete Operation - Singly Linked List
      • Design Linked List
    • Two Pointer Technique
      • Two-Pointer in Linked List
      • Linked List Cycle
      • Linked List Cycle II
      • Intersection of Two Linked Lists
      • Remove Nth Node From End of List
      • Summary - Two-Pointer in Linked List
  • Problems
    • 1. Two Sum
    • 2. Add Two Numbers
    • 7. Reverse Integer
    • 9. Palindrome Number
    • 11. Container With Most Water
    • 12. Integer to Roman
    • 13. Roman to Integer
    • 14. Longest Common Prefix
    • 15. 3Sum
    • 21. Merge Two Sorted Lists
    • 26. Remove Duplicates from Sorted Array
    • 27. Remove Element
    • 28. Find the Index of the First Occurrence in a String
    • 34. Find First and Last Position of Element in Sorted Array
    • 35. Search Insert Position
    • 43. Multiply Strings
    • 49. Group Anagrams
    • 50. Pow(x, n)
    • 54. Spiral Matrix
    • 58. Length of Last Word
    • 66. Plus One
    • 67. Add Binary
    • 69. Sqrt(x)
    • 73. Set Matrix Zeroes
    • 75. Sort Colors
    • 88. Merge Sorted Array
    • 104. Maximum Depth of Binary Tree
    • 121. Best Time to Buy and Sell Stock
    • 122. Best Time to Buy and Sell Stock II
    • 136. Single Number
    • 146. LRU Cache
    • 189. Rotate Array
    • 206. Reverse Linked List
    • 217. Contains Duplicate
    • 219. Cotains Duplicate II
    • 226. Invert Binary Tree
    • 238. Product of Array Except Self
    • 242. Valid Anagram
    • 268. Missing Number
    • 283. Move Zeroes
    • 350. Intersection of Two Arrays II
    • 383. Ransom Note
    • 389. Find the Difference
    • 412. Fizz Buzz
    • 414. Third Maximum Number
    • 445. Add Two Numbers II
    • 448. Find All Numbers Disappeared in an Array
    • 459. Repeated Substring Pattern
    • 485. Max Consecutive Ones
    • 509. Fibonacci Number
    • 637. Average of Levels in Binary Tree
    • 657. Robot Return to Origin
    • 682. Baseball Game
    • 704. Binary Search
    • 705. Design HashSet
    • 709. To Lower Case
    • 724. Find Pivot Index
    • 876. Middle of the Linked List
    • 896. Monotonic Array
    • 860. Lemonade Change
    • 905. Sort Array By Parity
    • 916. Word Subsets
    • 941. Valid Mountain Array
    • 976. Largest Perimeter Triangle
    • 977. Squares of a Sorted Array
    • 1041. Robot Bounded In Circle
    • 1051. Height Checker
    • 1089. Duplicate Zeros
    • 1232. Check If It Is a Straight Line
    • 1275. Find Winner on a Tic Tac Toe Game
    • 1295. Find Numbers with Even Number of Digits
    • 1299. Replace Elements with Greatest Element on Right Side
    • 1342. Number of Steps to Reduce a Number to Zero
    • 1346. Check If N and Its Double Exist
    • 1476. Subrectangle Queries
    • 1480. Running Sum of 1d Array
    • 1491. Average Salary Excluding the Minimum and Maximum Salary
    • 1502. Can Make Arithmetic Progression From Sequence
    • 1523. Count Odd Numbers in an Interval Range
    • 1572. Matrix Diagonal Sum
    • 1672. Richest Customer Wealth
    • 1768. Merge Strings Alternately
    • 1752. Check if Array Is Sorted and Rotated
    • 1769. Minimum Number of Operations to Move All Balls to Each Box
    • 1790. Check if One String Swap Can Make Strings Equal
    • 1800. Maximum Ascending Subarray Sum
    • 1822. Sign of the Product of an Array
    • 1930. Unique Length-3 Palindromic Subsequences
    • 1991. Find the Middle Index in Array
    • 2185. Counting Words With a Given Prefix
    • 2235. Add Two Integers
    • 2236. Root Equals Sum of Children
    • 2270. Number of Ways to Split Array
    • 2381. Shifting Letters II
    • 2559. Count Vowel Strings in Ranges
    • 2610. Convert an Array Into a 2D Array With Conditions
    • 2657. Find the Prefix Common Array of Two Arrays
    • 3042. Count Prefix and Suffix Pairs I
    • 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
    • 3151. Special Array I
    • 3223. Minimum Length of String After Operations
Powered by GitBook
On this page
  • Example 1
  • Example 2
  • Example 3
  • Hint-1
  • Hint-2
  • Hint-3
  • Constraints
  • Solution
  • Optimal Solution
  • Approach Analysis
  • Visualization of Both Approaches
  • Complexity Analysis
  • Why Solution Works
  • When to Use
  • Common Patterns & Applications
  • Interview Tips

Was this helpful?

Edit on GitHub
  1. Problems

15. 3Sum

🟧 Medium

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1

Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter.

Example 2

Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0.

Example 3

Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0.

Hint-1

So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand!

Hint-2

For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y, which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster?

Hint-3

The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?

Constraints

  • 3 <= nums.length <= 3000

  • -10^5 <= nums[i] <= 10^5

Solution

My Solution

func threeSum(nums []int) [][]int {
    sort.Ints(nums)
    res := [][]int{}

    for i, num := range nums {
        if i > 0 && num == nums[i-1] {
            continue
        }

        l,r := i+1, len(nums) - 1
        for l < r {
            threeSum := num + nums[l] + nums[r]
            if threeSum > 0 {
                r -=1
            } else if threeSum < 0 {
                l+=1
            } else {
                res = append(res, []int{num, nums[l], nums[r]})
                l+=1

                for nums[l] == nums[l-1] && l < r {
                    l+=1
                }
            }
        }
    }


    return res
}

Optimal Solution

The optimal solution uses two key techniques:

  1. Sorting for duplicate handling and efficient searching

  2. Two-pointer technique for finding pairs that sum to target

Here's an optimized version with improved readability and performance:

func threeSum(nums []int) [][]int {
    // Sort the array first for efficient duplicate handling
    sort.Ints(nums)
    result := make([][]int, 0)
    n := len(nums)
    
    // Fix the first number and use two pointers for the remaining sum
    for i := 0; i < n-2; i++ {
        // Skip duplicates for first number
        if i > 0 && nums[i] == nums[i-1] {
            continue
        }
        
        // Early termination optimization
        if nums[i] > 0 {
            break // Since array is sorted, no three numbers can sum to 0
        }
        
        target := -nums[i]
        left := i + 1
        right := n - 1
        
        for left < right {
            currentSum := nums[left] + nums[right]
            
            if currentSum == target {
                result = append(result, []int{nums[i], nums[left], nums[right]})
                
                // Skip duplicates for second number
                for left < right && nums[left] == nums[left+1] {
                    left++
                }
                // Skip duplicates for third number
                for left < right && nums[right] == nums[right-1] {
                    right--
                }
                
                left++
                right--
            } else if currentSum < target {
                left++
            } else {
                right--
            }
        }
    }
    
    return result
}

Approach Analysis

The solution employs three main techniques:

  1. Sorting:

    • Makes duplicate handling efficient

    • Enables two-pointer technique

    • Allows for early termination

  2. Two-Pointer Technique:

    • Uses sorted array property

    • Efficiently finds pairs summing to target

    • Reduces time complexity from O(n²) to O(n)

  3. Duplicate Handling:

    • Skip duplicates for first number

    • Skip duplicates for second and third numbers

    • Ensures unique triplets

Visualization of Both Approaches

Input array: [-1, 0, 1, 2, -1, -4]
After sorting: [-4, -1, -1, 0, 1, 2]

Step 1: First number = -4
[-4, -1, -1, 0, 1, 2]
 ^   L           R
Target sum = 4
Move L right as sum is too small

Step 2: First number = -1
[-4, -1, -1, 0, 1, 2]
     ^   L        R
Found triplet: [-1, -1, 2]

Step 3: Skip duplicate -1
[-4, -1, -1, 0, 1, 2]
         ^   L    R
Found triplet: [-1, 0, 1]

Final result: [[-1, -1, 2], [-1, 0, 1]]

Complexity Analysis

Time Complexity:

  • Sorting: O(n log n)

  • Two pointers: O(n²)

  • Overall: O(n²)

Space Complexity:

  • Result array: O(k) where k is number of valid triplets

  • Sorting space: O(log n) to O(n) depending on sort implementation

  • Overall: O(k)

Optimizations:

  • Early termination when first number > 0

  • Skip duplicates to avoid redundant calculations

  • Two-pointer technique instead of nested loops

Why Solution Works

  1. Sorting Enables Efficiency:

    • Makes duplicate detection simple

    • Allows two-pointer technique

    • Enables early termination

  2. Two-Pointer Logic:

    • If sum too small, increase left pointer

    • If sum too large, decrease right pointer

    • Guarantees finding all valid pairs

  3. Duplicate Handling:

    • Sorting puts duplicates adjacent

    • Skip duplicates for all three positions

    • Ensures unique triplets in result

When to Use

This approach is ideal when:

  1. Need to find all combinations summing to target

  2. Duplicates need to be handled

  3. Order of triplets doesn't matter

  4. Input array can be modified

Common variations:

  • 4Sum problem

  • K-sum problem

  • Two-pointer problems

  • Combination sum problems

Common Patterns & Applications

  1. Two-Pointer Pattern:

    • Sorted array traversal

    • Meeting in middle

    • Opposite direction movement

  2. Sorting + Two Pointers:

    • Finding combinations

    • Handling duplicates

    • Range-based problems

  3. Sum Problems:

    • TwoSum variations

    • KSum problems

    • Target sum problems

Interview Tips

  1. Key Discussion Points:

    • Why sorting first?

    • How to handle duplicates?

    • Time/space complexity tradeoffs

    • Optimization techniques

  2. Common Follow-up Questions:

    • How to handle 4Sum?

    • Can we do it without sorting?

    • How to optimize for specific input patterns?

    • How to handle negative targets?

  3. Edge Cases to Consider:

    • Empty array

    • Array with < 3 elements

    • All zeros

    • All same numbers

    • No valid triplets

  4. Optimization Opportunities:

    • Early termination

    • Duplicate skipping

    • Memory management

    • Input validation

Previous14. Longest Common PrefixNext21. Merge Two Sorted Lists

Last updated 5 months ago

Was this helpful?

Leetcode:

link
result