Skip to content

Commit f4cdf21

Browse files
committed
Sync LeetCode submission Runtime - 565 ms (36.43%), Memory - 17.9 MB (73.40%)
1 parent 22bd48c commit f4cdf21

File tree

1 file changed

+26
-22
lines changed

1 file changed

+26
-22
lines changed

0259-3sum-smaller/solution.py

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,32 @@
1-
# Approach 3 - Two Pointers
1+
# Approach 3: Two Pointers
22

3-
# Time: O(n^2)
3+
# Time: O(n ^ 2)
44
# Space: O(1)
55

66
class Solution:
77
def threeSumSmaller(self, nums: List[int], target: int) -> int:
8+
if len(nums) < 3:
9+
return 0
10+
811
nums.sort()
9-
total = 0
10-
11-
for i in range(len(nums)-1):
12-
total += self.twoSumSmaller(nums, i + 1, target - nums[i])
13-
14-
return total
15-
16-
def twoSumSmaller(self, nums, start_index, target):
17-
total = 0
18-
left, right = start_index, len(nums) - 1
19-
20-
while left < right:
21-
if nums[left] + nums[right] < target:
22-
total += right - left
23-
left += 1
24-
else:
25-
right -= 1
26-
27-
return total
28-
12+
count = 0
13+
n = len(nums)
14+
15+
# Fix the first element and use two pointers for the remaining elements
16+
for i in range(n - 2):
17+
left = i + 1
18+
right = n - 1
19+
20+
while left < right:
21+
curr_sum = nums[i] + nums[left] + nums[right]
22+
23+
if curr_sum < target:
24+
# All numbers between left and right will also work with left
25+
# because array is sorted and we want sum < target
26+
count += right - left
27+
left += 1
28+
else:
29+
right -= 1
30+
31+
return count
32+

0 commit comments

Comments
 (0)