3Sum

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: 3Sum

Approach

Sort the array first. Fix one element with an outer loop, then use two converging pointers on the remaining subarray to find pairs that sum to the negation of the fixed element. Skip duplicate values at each level to ensure unique triplets.

Complexity Analysis

Time
O(n^2)
Space
O(1)

Pattern

Two Pointers (Converging) + Sort

Why It Works

Sorting enables the two-pointer technique: if the current sum is too small, move the left pointer right to increase it; if too large, move right pointer left. Skipping duplicates prevents repeated triplets.

Updated Feb 2026