4Sum — LeetCode #18

Norman Aranez
2 min readDec 23, 2022

--

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 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

Constraints:

  • 1 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109

Solutions:

Python

class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
# Sort the list
nums.sort()

# Initialize result list
result = []

# Fix the first two numbers using two pointers
for i in range(len(nums)-3):
# Skip duplicates
if i > 0 and nums[i] == nums[i-1]:
continue

# Fix the second number
for j in range(i+1, len(nums)-2):
# Skip duplicates
if j > i+1 and nums[j] == nums[j-1]:
continue

# Use two pointers to find the last two numbers
left, right = j+1, len(nums)-1
while left < right:
curr_sum = nums[i] + nums[j] + nums[left] + nums[right]
if curr_sum == target:
result.append([nums[i], nums[j], nums[left], nums[right]])
left += 1
right -= 1
# Skip duplicates
while left < right and nums[left] == nums[left-1]:
left += 1
while left < right and nums[right] == nums[right+1]:
right -= 1
elif curr_sum < target:
left += 1
else:
right -= 1

return result

Javascript

/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
// Resultant list
const quadruplets = [];
// Base condition
if (nums == undefined || nums.length < 4) {
return quadruplets;
}
// Sort the array
nums.sort((a, b) => a - b);
// Length of the array
const n = nums.length;
// Loop for each element of the array
for (let i = 0; i < n - 3; i++) {
// Check for skipping duplicates
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// Reducing to three sum problem
for (let j = i + 1; j < n - 2; j++) {
// Check for skipping duplicates
if (j != i + 1 && nums[j] == nums[j - 1]) {
continue;
}
// Left and right pointers
let k = j + 1;
let l = n - 1;
// Reducing to two sum problem
while (k < l) {
const currentSum = nums[i] + nums[j] + nums[k] + nums[l];
if (currentSum < target) {
k++;
} else if (currentSum > target) {
l--;
} else {
quadruplets.push([nums[i], nums[j], nums[k], nums[l]]);
k++;
l--;
// Check for skipping duplicates
while (k < l && nums[k] == nums[k - 1]) {
k++;
}
while (k < l && nums[l] == nums[l + 1]) {
l--;
}
}
}
}
}
return quadruplets;
};

I hope this helps! Let me know if you have any questions. Don’t forget to follow and give some claps and comments

--

--

Norman Aranez

I am a web developer skilled in React, GraphQL, TypeScript, and ASP.NET Core. I enjoy building modern, responsive applications