Given an array nums
of n
integers and an integer target
, find all unique quadruplets in the array which gives the sum of target
.
Note:
You must write a function:
def fourSum(nums: List[int], target: int) -> List[List[int]]:
Input: nums = [1, 0, -1, 0, -2, 2], target = 0
Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Sorting: First, sort the array. This allows us to apply a more systematic approach to finding quadruplets and helps in skipping duplicates effectively.
Iterate with Two Pointers: Use four nested loops, but optimize the innermost two with the two-pointer technique.
Here’s the implementation of the above strategy:
from typing import List
def fourSum(nums: List[int], target: int) -> List[List[int]]:
result = []
nums.sort()
n = len(nums)
for i in range(n-3):
if i > 0 and nums[i] == nums[i-1]:
continue
if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:
break
if nums[i] + nums[n-1] + nums[n-2] + nums[n-3] < target:
continue
for j in range(i+1, n-2):
if j > i+1 and nums[j] == nums[j-1]:
continue
if nums[i] + nums[j] + nums[j+1] + nums[j+2] > target:
break
if nums[i] + nums[j] + nums[n-1] + nums[n-2] < target:
continue
left, right = j+1, n-1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
result.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif total < target:
left += 1
else:
right -= 1
return result
Thus, the overall time complexity is (O(n^3)).
The space complexity is (O(1)) for extra space (results list doesn’t count as extra space).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?