File tree Expand file tree Collapse file tree 1 file changed +26
-22
lines changed
Expand file tree Collapse file tree 1 file changed +26
-22
lines changed Original file line number Diff line number Diff line change 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
66class 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+
You can’t perform that action at this time.
0 commit comments