-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_pointers04.py
More file actions
59 lines (47 loc) · 1.93 KB
/
Copy pathtwo_pointers04.py
File metadata and controls
59 lines (47 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
'''
Given an array of unsorted numbers, find all unique triplets in it that add up to zero.
Example 1:
Input: [-3, 0, 1, 2, -1, 1, -2]
Output: [-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]
Explanation: There are four unique triplets whose sum is equal to zero.
Example 2:
Input: [-5, 2, -1, -2, 3]
Output: [[-5, 2, 3], [-2, -1, 3]]
Explanation: There are two unique triplets whose sum is equal to zero.
Time complexity #
Sorting the array will take O(N * logN)O(N∗logN). The searchPair() function will take O(N)O(N). As we are calling searchPair() for every number in the input array, this means that overall searchTriplets() will take O(N * logN + N^2)O(N∗logN+N
2
), which is asymptotically equivalent to O(N^2)O(N
2
).
Space complexity #
Ignoring the space required for the output array, the space complexity of the above algorithm will be O(N)O(N) which is required for sorting.
'''
def search_triplets(arr):
arr.sort()
triplets = []
for i in range(len(arr)):
if i > 0 and arr[i] == arr[i-1]: # skip same element to avoid duplicate triplets
continue
search_pair(arr, -arr[i], i+1, triplets)
return triplets
def search_pair(arr, target_sum, left, triplets):
right = len(arr) - 1
while(left < right):
current_sum = arr[left] + arr[right]
if current_sum == target_sum: # found the triplet
triplets.append([-target_sum, arr[left], arr[right]])
left += 1
right -= 1
while left < right and arr[left] == arr[left - 1]:
left += 1 # skip same element to avoid duplicate triplets
while left < right and arr[right] == arr[right + 1]:
right -= 1 # skip same element to avoid duplicate triplets
elif target_sum > current_sum:
left += 1 # we need a pair with a bigger sum
else:
right -= 1 # we need a pair with a smaller sum
def main():
print(search_triplets([-3, 0, 1, 2, -1, 1, -2]))
print(search_triplets([-5, 2, -1, -2, 3]))
main()