Skip to content

Instantly share code, notes, and snippets.

@alexwal
Last active September 11, 2018 20:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexwal/5ca7928d0818f3e0dad93c0b3db84c6e to your computer and use it in GitHub Desktop.
Save alexwal/5ca7928d0818f3e0dad93c0b3db84c6e to your computer and use it in GitHub Desktop.
Leet Code 4Sum Solution: https://leetcode.com/problems/4sum/
class Solution:
"""
Solution to Leet Code problem 4Sum: https://leetcode.com/problems/4sum/
Runtime: 100 ms beats 93.4% of python3 submissions
"""
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
# Edge cases:
if len(nums) < 4:
return []
if 4 * max(nums) < target:
return []
nums = sorted(nums)
n = len(nums)
solutions = set()
for _a in range(n - 3):
ta = target - nums[_a]
for _d in range(_a + 3, n):
tad = ta - nums[_d]
# Skip the following cases:
if nums[_d - 2] + nums[_d - 1] < tad:
continue
if nums[_a + 1] + nums[_a + 2] > tad:
continue
_b, _c = _a + 1, _d - 1
while _b < _c:
b, c = nums[_b], nums[_c]
bc = b + c
if bc == tad:
a, d = nums[_a], nums[_d]
solutions.add((a, b, c, d))
_b += 1
elif bc > tad: # decrease c to make bc closer to tad
_c -= 1
else: # increase b to make bc closer to tad
_b += 1
return list(solutions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment