Given an integer array nums, return all triplets [nums[i], nums[j], nums[k]] such that i≠j≠k and nums[i]+nums[j]+nums[k]==0. The solution set must not contain duplicate triplets.
nums = [-1,0,1,2,-1,-4][[-1,-1,2],[-1,0,1]]Why sort? After sorting, if sum is too small we know moving L right (to bigger values) will increase it. If sum is too large, moving R left decreases it. This eliminates guessing.
Why skip duplicates? After sorting, duplicates are adjacent. Skipping them at both anchor and pointer levels guarantees unique triplets without a HashSet.
Why O(n²)? O(n log n) sort + outer loop O(n) × inner two-pointer O(n) = O(n²) total. Each element is visited at most once per anchor.