Created
June 14, 2025 22:20
-
-
Save Mahedi-61/65ecb80a429a4482b0fd7c0e11fd6d85 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. FourSum: | |
You are given an integer array nums of size n, 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. Note: [1,0,3,2] and [3,0,1,2] are considered as same quadruplets. | |
Example 1: | |
Input: nums = [3,2,3,-3,1,0], target = 3 | |
Output: [[-3,0,3,3],[-3,1,2,3]] | |
# Solution | |
def fourSum(self, nums: List[int], target: int) -> List[List[int]]: | |
nums.sort() | |
result = [] | |
for i in range(len(nums)): | |
if i > 0 and nums[i] == nums[i-1]: | |
continue | |
for j in range(i + 1, len(nums)): | |
if j > i + 1 and nums[j] == nums[j-1]: | |
continue | |
l = j + 1 | |
r = len(nums) - 1 | |
while(l < r): | |
array = [nums[i], nums[j], nums[l], nums[r]] | |
if sum(array) == target: | |
result.append(array) | |
l += 1 | |
r -= 1 | |
while (l < r and nums[l] == nums[l - 1]): | |
l += 1 | |
while (l < r and nums[r] == nums[r + 1]): | |
r -= 1 | |
elif sum(array) < target: | |
l += 1 | |
else: | |
r -= 1 | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment