bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 15. 3Sum

15. 3Sum

Leetcode Solutions

Two Pointers Approach

  1. Sort the input array nums.
  2. Iterate through the array with a loop using index i as the fixed pointer.
  3. If the current value is greater than zero, break from the loop as remaining values cannot sum to zero.
  4. If the current value is the same as the one before, skip it to avoid duplicates.
  5. Set the low pointer lo to i + 1, and high pointer hi to the last index.
  6. While lo is smaller than hi, check the sum of nums[i] + nums[lo] + nums[hi].
  7. If the sum is less than zero, increment lo.
  8. If the sum is greater than zero, decrement hi.
  9. If the sum is zero, add the triplet to the result and move both pointers, skipping any duplicate values.
  10. Return the result containing all unique triplets.
UML Thumbnail

Hashset Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...