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

šŸ› ļø 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

šŸ“š Reference Solution

ā–¼
⌘K Search āŒ˜ā†© Run ⌘S Submit