forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount_triplets_with_sum_k.py
More file actions
86 lines (67 loc) · 2.02 KB
/
count_triplets_with_sum_k.py
File metadata and controls
86 lines (67 loc) · 2.02 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'''
Count Triplets with Sum K
Given an array (sorted in ascending order) and a value, count how many triplets
exist in array whose sum is equal to the given value.
Input: [1, 2, 3, 4, 5], 9
Output: 2
Output explanation: (1, 3, 5) and (2, 3, 4)
=========================================
Fix the first element (i), move the second element (j) and search into the hashset.
(similar approach to find_pairs_with_sum_k.py)
Time Complexity: O(N^2)
Space Complexity: O(N)
Fix the first element (i), and play with 2 pointers from the left (i+1) and right (n-1) side.
If the current sum is smaller than K then increase the left pointer, otherwise decrease the right pointer.
* This solution works only for elements in sorted ascending order. If the elements aren't sorted, first sort
them and after that use this algorithm, the time complexity will be same O(NLogN + N^2) = O(N^2).
Time Complexity: O(N^2)
Space Complexity: O(1)
'''
##############
# Solution 1 #
##############
def count_triplets_1(arr, k):
count = 0
n = len(arr)
for i in range(n - 2):
elements = set()
curr_sum = k - arr[i]
for j in range(i + 1, n):
if (curr_sum - arr[j]) in elements:
count += 1
elements.add(arr[j])
return count
##############
# Solution 2 #
##############
def count_triplets_2(arr, k):
count = 0
n = len(arr)
for i in range(n - 2):
left = i + 1
right = n - 1
while left < right:
curr_sum = arr[i] + arr[left] + arr[right]
if curr_sum == k:
count += 1
right -= 1
elif curr_sum < k:
left += 1
else:
right -= 1
return count
###########
# Testing #
###########
# Test 1
# Correct result => 1
arr = [10, 11, 16, 18, 19]
k = 40
print(count_triplets_1(arr, k))
print(count_triplets_2(arr, k))
# Test 2
# Correct result => 2
arr = [1, 2, 3, 4, 5]
k = 9
print(count_triplets_1(arr, k))
print(count_triplets_2(arr, k))