3Sum - Two Pointers Pattern

3Sum in Java using the Two Pointers pattern: problem statement, approach, template, complexity, and interview tips.

3Sum

Problem Statement

Return all unique triplets in the array that sum to zero.

Pattern: Two Pointers

Move two indices through the data, usually from both ends or in the same direction, to avoid a nested loop.

Use this pattern when the input is sorted (or can be sorted) and you search for pairs, or you must compact or compare from both ends.

Approach

  1. Decide where each pointer starts and which direction it moves.
  2. At each step compare the pointed values and move the pointer that can improve the answer.
  3. Stop when the pointers meet or cross.

Pattern Template (Java)

int left = 0, right = n - 1;
while (left < right) {
    // evaluate nums[left] and nums[right]
    // move the pointer that can still improve the answer
}

Adapt this template to the exact rules of 3Sum: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(n) time and O(1) extra space after sorting; sorting adds O(n log n).

Interview Tips

  • Say out loud why moving a pointer can never skip the best answer.
  • Skip duplicates explicitly when the problem asks for unique results.
  • Start with a brute-force idea, state its complexity, then explain how the Two Pointers pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Two Sum II | Next: Container with Most Water

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.