4Sum — LeetCode 18 Python Solution
- Problem
- #18
- Pattern
- Two Pointers
- Reading time
- 5 min
- Source
- leetcode.com
The problem
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 0 <= a, b, c, d < n a, b, c, and d are distinct. 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]]
Python solution
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
n = len(nums)
ans = []
if n < 4:
return ans
nums.sort()
for i in range(n - 3):
if i and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
k, l = j + 1, n - 1
while k < l:
x = nums[i] + nums[j] + nums[k] + nums[l]
if x < target:
k += 1
elif x > target:
l -= 1
else:
ans.append([nums[i], nums[j], nums[k], nums[l]])
k, l = k + 1, l - 1
while k < l and nums[k] == nums[k - 1]:
k += 1
while k < l and nums[l] == nums[l + 1]:
l -= 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^3) |
| Space | O(\log n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 18. 4Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 18. 4Sum?
- LeetCode 18. 4Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 18. 4Sum?
- The Python solution on this page runs in O(n^3).
- What is the space complexity of LeetCode 18. 4Sum?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 18. 4Sum cover?
- LeetCode 18. 4Sum is tagged Array, Two Pointers and Sorting on LeetCode.