MEDIUM NC#12 Blind #9 Two Pointers
15. 3Sum
š Problem
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
š§ Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- ā¢Array methods (`push`, `pop`, `shift`, `slice`)
- ā¢Object/Map/Set usage patterns
- ā¢Function parameter and return typing
- ā¢In-place array updates
- ā¢Sorted array traversal
- ā¢Boundary condition checks
Logical Thinking Concepts
- ā¢Define invariants before coding
- ā¢Check edge cases first (`[]`, single element, duplicates)
- ā¢Estimate time/space before implementation
- ā¢Apply Two Pointers reasoning pattern
š” Approach
- ā Sort array first to use two pointers
- ā Fix one element, use two pointers for remaining two
- ā Skip duplicates to avoid duplicate triplets
- ā Time: O(n²), Space: O(k) for results
š§ Prerequisites
š ļø Hints & Pitfalls
Hints
- ā¢Sort array first to use two pointers
- ā¢Fix one element, use two pointers for remaining two
- ā¢Skip duplicates to avoid duplicate triplets
Common Pitfalls
- ā¢Time: O(n²), Space: O(k) for results
š§Ŗ Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
threeSum([-1,0,1,2,-1,-4]); Expected:
[[-1,-1,2], [-1,0,1]] Test Case 2
Not run Input:
threeSum([0,1,1]); Expected:
[] Test Case 3
Not run Input:
threeSum([0,0,0]); Expected:
[[0,0,0]] š Code Editor
š¤ Output