-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpair_sums.py
96 lines (80 loc) · 2.39 KB
/
pair_sums.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
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
87
88
89
90
91
92
93
94
95
96
Pair Sums
Given a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it which sum to k.
If an integer appears in the list multiple times, each copy is considered to be different; that is, two pairs are considered different if one pair includes at least one array index which the other doesn't, even if they include the same values.
Signature
int numberOfWays(int[] arr, int k)
Input
n is in the range [1, 100,000].
Each value arr[i] is in the range [1, 1,000,000,000].
k is in the range [1, 1,000,000,000].
Output
Return the number of different pairs of elements which sum to k.
Example 1
n = 5
k = 6
arr = [1, 2, 3, 4, 3]
output = 2
The valid pairs are 2+4 and 3+3.
Example 2
n = 5
k = 6
arr = [1, 5, 3, 3, 3]
output = 4
There's one valid pair 1+5, and three different valid pairs 3+3 (the 3rd and 4th elements, 3rd and 5th elements, and 4th and 5th elements).
import math
# Add any extra import statements you may need here
# Add any helper functions you may need here
def numberOfWays(arr, k):
# Write your code here
sorted_arr = sorted(arr)
n = len(sorted_arr)
i = 0
j = n - 1
count = 0
while j > i:
sum_ = sorted_arr[i] + sorted_arr[j]
if sum_ > k:
j -= 1
elif sum_ < k:
i += 1
else:
v = sorted_arr[i]
u = i
while sorted_arr[u] == v and u < j:
count += 1
u += 1
j -= 1
return count
# These are the tests we use to determine if the solution is correct.
# You can add your own at the bottom.
def printInteger(n):
print('[', n, ']', sep='', end='')
test_case_number = 1
def check(expected, output):
global test_case_number
result = False
if expected == output:
result = True
rightTick = '\u2713'
wrongTick = '\u2717'
if result:
print(rightTick, 'Test #', test_case_number, sep='')
else:
print(wrongTick, 'Test #', test_case_number, ': Expected ', sep='', end='')
printInteger(expected)
print(' Your output: ', end='')
printInteger(output)
print()
test_case_number += 1
if __name__ == "__main__":
k_1 = 6
arr_1 = [1, 2, 3, 4, 3]
expected_1 = 2
output_1 = numberOfWays(arr_1, k_1)
check(expected_1, output_1)
k_2 = 6
arr_2 = [1, 5, 3, 3, 3]
expected_2 = 4
output_2 = numberOfWays(arr_2, k_2)
check(expected_2, output_2)
# Add your own test cases here