-
Notifications
You must be signed in to change notification settings - Fork 1
/
3_sum.py
56 lines (40 loc) · 1.31 KB
/
3_sum.py
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
#Question: Given an array arr[] of n integers. Check whether it contains a triplet that sums up to zero.
# Return true, if there is at least one triplet following the condition else return false.
#CODE:
#O(N^2) - 2 codes - Best Possible Versions
def findTriplets(self, arr, n):
arr.sort()
for i in range(n):
seen = set()
current_sum = 0 - arr[i]
for j in range(i + 1, n):
if current_sum - arr[j] in seen:
return 1
seen.add(arr[j])
return 0
def findTriplets(self, arr, n):
arr.sort()
for i in range(n - 2):
left, right = i + 1, n - 1
while left < right:
total = arr[i] + arr[left] + arr[right]
if total == 0:
return 1
elif total < 0:
left += 1
else:
right -= 1
return 0
# def findTriplets(self, arr, n):
# arr.sort()
# for i in range(n - 2):
# left, right = i + 1, n - 1
# while left < right:
# total = arr[i] + arr[left] + arr[right]
# if total == 0:
# return 1
# elif total < 0:
# left += 1
# else:
# right -= 1
# return 0