4Sum | LeetCode 18 | Two Pointers
š§© Problem Description
Given an integer array nums and an integer target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example:
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Constraints:
- 4 <= nums.length <= 200
- -10ā¹ <= nums[i] <= 10ā¹
- -10ā¹ <= target <= 10ā¹
š” Approach
This is a direct extension of the 3Sum problem.
We use sorting + two pointers:
- Sort the array.
- Use two nested loops for the first two numbers.
- Apply the two-pointer method to find the remaining two numbers.
- Skip duplicate values to avoid repeated quadruplets.
š§ Key Insight
After fixing two indices i and j, we need to find two numbers whose sum equals target - nums[i] - nums[j].
This can be efficiently done with a two-pointer scan since the array is sorted.
š§® Complexity
- Time Complexity: O(n³)
- Space Complexity: O(1) (excluding output list)
š» Java Code
1 | class Solution { |
š Summary
- Sort ā Fix two numbers ā Use two pointers for the rest.
- Handle duplicates carefully.
- Similar to 3Sum, but one extra layer of iteration.