LeetCode 15: 3Sum Solution

Master LeetCode problem 15 (3Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can use the two-pointer technique along with sorting the input array. The idea is to fix one element and then find the other two elements using two pointers. We need to handle duplicates properly to avoid duplicate triplets in the result.

  1. Sort the input array nums.
  2. Iterate through the array, fixing one element at a time.
  3. Use two pointers (left and right) to find the other two elements that sum up to the target (0 - nums[i]).
  4. Handle duplicates by skipping equal elements while moving the pointers.
  5. Add the triplet to the result if found.
  6. Repeat the process until all possible triplets are checked.

Time complexity: O(n^2) where n is the length of the input array nums. Space complexity: O(log n) to O(n) depending on the sorting algorithm.

Solution Code

import java.util.*;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        int n = nums.length;

        for (int i = 0; i < n - 2; i++) {
            if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
                int target = 0 - nums[i];
                int left = i + 1, right = n - 1;

                while (left < right) {
                    if (nums[left] + nums[right] == target) {
                        result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                        while (left < right && nums[left] == nums[left + 1]) left++;
                        while (left < right && nums[right] == nums[right - 1]) right--;
                        left++;
                        right--;
                    } else if (nums[left] + nums[right] < target) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 15 (3Sum)?

This page provides optimized solutions for LeetCode problem 15 (3Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 15 (3Sum)?

The time complexity for LeetCode 15 (3Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 15 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 15 in Java, C++, or Python.

Back to LeetCode Solutions