Skip to content

visual walkthrough

3Sum

MediumSort + Two PointersReported at: AmazonMetaMicrosoft+14

Reduces k-sum to 2-sum and tests duplicate handling; asked constantly.

Solve on LeetCode

The idea

Sort the array and fix the first number. Now the other two must add up to its opposite, which is the Two Sum II problem: one pointer at each end, moving toward whichever side fixes the total.

Skipping repeated values for the fixed number and for the pointers keeps every triplet unique.

Complexity

approachtimespace
Three loopsO(n³)O(1)
Sort + two pointersO(n²)O(1)

More walkthroughs