LeetCode 0018. 4Sum Solution Java | Python | C/C++ | JavaScripts | Go | Rust | Explaination + CODE

CoderIndeed
0
0018. 4Sum

Description

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

Solution 1: Sorting + Double Pointers

We notice that the problem requires us to find non-repeating quadruplets. Therefore, we can first sort the array, which makes it easy to skip duplicate elements.

Next, we enumerate the first two elements of the quadruplet, nums[i] and nums[j], where i \lt j. During the enumeration process, we skip duplicate nums[i] and nums[j]. Then, we use two pointers k and l to point to the two ends behind nums[i] and nums[j]. Let x = nums[i] + nums[j] + nums[k] + nums[l], we compare x with target and perform the following operations:

  • If x \lt target, then update k = k + 1 to get a larger x;
  • If x \gt target, then update l = l - 1 to get a smaller x;
  • Otherwise, it means that a quadruplet (nums[i], nums[j], nums[k], nums[l]) is found. Add it to the answer, then we update the pointers k and l, and skip all duplicate elements to prevent the answer from containing duplicate quadruplets, and continue to find the next quadruplet.

The time complexity is O(n^3), and the space complexity is O(log n). Here, n is the length of the array.

PythonJavaC++GoTypeScriptJavaScriptC#PHP
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 ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !