Skip to content

Instantly share code, notes, and snippets.

@humpydonkey
Created April 7, 2021 00:14
Show Gist options
  • Save humpydonkey/2a54593520c8c526b892fd345f6f42d3 to your computer and use it in GitHub Desktop.
Save humpydonkey/2a54593520c8c526b892fd345f6f42d3 to your computer and use it in GitHub Desktop.
class Solution:
def threeSumSmaller(self, nums: List[int], target: int) -> int:
"""
If we fix one dimension, the question essentially becomes a "two sum smaller" problem
The ideas are:
1) when sum < target, count += r - l, then we need to move left to the next bigger value
2) otherwise move r to the next smaller value
"""
nums.sort()
n = len(nums)
count = 0
for start in range(n-2):
l, r = start + 1, n - 1
while l < r:
curr_sum = nums[start] + nums[l] + nums[r]
if curr_sum < target:
count += r - l
l += 1
else:
r -= 1
return count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment