sum-helpers 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sum_helpers/__init__.py +85 -0
- sum_helpers/k_sum.py +416 -0
- sum_helpers/py.typed +0 -0
- sum_helpers/three_sum.py +208 -0
- sum_helpers/triangle.py +163 -0
- sum_helpers/two_sum.py +268 -0
- sum_helpers-0.1.0.dist-info/METADATA +117 -0
- sum_helpers-0.1.0.dist-info/RECORD +9 -0
- sum_helpers-0.1.0.dist-info/WHEEL +4 -0
sum_helpers/__init__.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""sum_helpers: Clean, modular, well-typed Python helpers for sum and combination problems.
|
|
2
|
+
|
|
3
|
+
Core modules:
|
|
4
|
+
- two_sum:
|
|
5
|
+
- two_sum (LC 1)
|
|
6
|
+
- two_sum_sorted (LC 167)
|
|
7
|
+
- two_sum_less_than_k (LC 1099)
|
|
8
|
+
- two_sum_closest
|
|
9
|
+
- two_sum_unique_pairs
|
|
10
|
+
|
|
11
|
+
- three_sum:
|
|
12
|
+
- three_sum (LC 15)
|
|
13
|
+
- three_sum_closest (LC 16)
|
|
14
|
+
- three_sum_smaller (LC 259)
|
|
15
|
+
|
|
16
|
+
- triangle:
|
|
17
|
+
- valid_triangle_number (LC 611)
|
|
18
|
+
- is_valid_triangle
|
|
19
|
+
- find_valid_triangles
|
|
20
|
+
|
|
21
|
+
- k_sum:
|
|
22
|
+
- k_sum (Generalized arbitrary k >= 2)
|
|
23
|
+
- k_sum_closest
|
|
24
|
+
- k_sum_smaller
|
|
25
|
+
- four_sum (LC 18)
|
|
26
|
+
- four_sum_closest
|
|
27
|
+
- four_sum_smaller
|
|
28
|
+
- four_sum_ii (LC 454)
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
from sum_helpers.k_sum import (
|
|
34
|
+
four_sum,
|
|
35
|
+
four_sum_closest,
|
|
36
|
+
four_sum_ii,
|
|
37
|
+
four_sum_smaller,
|
|
38
|
+
k_sum,
|
|
39
|
+
k_sum_closest,
|
|
40
|
+
k_sum_smaller,
|
|
41
|
+
)
|
|
42
|
+
from sum_helpers.three_sum import (
|
|
43
|
+
three_sum,
|
|
44
|
+
three_sum_closest,
|
|
45
|
+
three_sum_smaller,
|
|
46
|
+
)
|
|
47
|
+
from sum_helpers.triangle import (
|
|
48
|
+
find_valid_triangles,
|
|
49
|
+
is_valid_triangle,
|
|
50
|
+
valid_triangle_number,
|
|
51
|
+
)
|
|
52
|
+
from sum_helpers.two_sum import (
|
|
53
|
+
two_sum,
|
|
54
|
+
two_sum_closest,
|
|
55
|
+
two_sum_less_than_k,
|
|
56
|
+
two_sum_sorted,
|
|
57
|
+
two_sum_unique_pairs,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
# Two sum
|
|
62
|
+
"two_sum",
|
|
63
|
+
"two_sum_sorted",
|
|
64
|
+
"two_sum_less_than_k",
|
|
65
|
+
"two_sum_closest",
|
|
66
|
+
"two_sum_unique_pairs",
|
|
67
|
+
# Three sum
|
|
68
|
+
"three_sum",
|
|
69
|
+
"three_sum_closest",
|
|
70
|
+
"three_sum_smaller",
|
|
71
|
+
# Triangle sum
|
|
72
|
+
"valid_triangle_number",
|
|
73
|
+
"is_valid_triangle",
|
|
74
|
+
"find_valid_triangles",
|
|
75
|
+
# K-sum & Four sum
|
|
76
|
+
"k_sum",
|
|
77
|
+
"k_sum_closest",
|
|
78
|
+
"k_sum_smaller",
|
|
79
|
+
"four_sum",
|
|
80
|
+
"four_sum_closest",
|
|
81
|
+
"four_sum_smaller",
|
|
82
|
+
"four_sum_ii",
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
__version__ = "0.1.0"
|
sum_helpers/k_sum.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"""Generalized K-Sum and Four Sum helper functions.
|
|
2
|
+
|
|
3
|
+
This module provides generalized implementations for:
|
|
4
|
+
- 4Sum: All unique quadruplets summing to target
|
|
5
|
+
- 4Sum Closest: Quadruplet sum closest to target
|
|
6
|
+
- 4Sum Smaller: Count of index quadruplets summing to strictly less than target
|
|
7
|
+
- 4Sum II: Count index quadruplets across four separate arrays summing to zero
|
|
8
|
+
- Generalized K-Sum: Arbitrary k >= 2 unique tuple sum algorithm
|
|
9
|
+
- Generalized K-Sum Closest: Sum of k integers closest to target
|
|
10
|
+
- Generalized K-Sum Smaller: Count of index k-tuples summing to strictly less than target
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections import Counter
|
|
16
|
+
from typing import Sequence
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"k_sum",
|
|
20
|
+
"k_sum_closest",
|
|
21
|
+
"k_sum_smaller",
|
|
22
|
+
"four_sum",
|
|
23
|
+
"four_sum_closest",
|
|
24
|
+
"four_sum_smaller",
|
|
25
|
+
"four_sum_ii",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def k_sum(nums: Sequence[int], target: int, k: int) -> list[tuple[int, ...]]:
|
|
30
|
+
"""Find all unique k-tuples in nums that sum to target.
|
|
31
|
+
|
|
32
|
+
Assumptions & Behavior:
|
|
33
|
+
- Input can be unsorted and may contain duplicate values and negative numbers.
|
|
34
|
+
- Result contains unique sorted k-tuples: each tuple has elements in ascending
|
|
35
|
+
order (x_1 <= x_2 <= ... <= x_k).
|
|
36
|
+
- If k < 2 or len(nums) < k, returns an empty list [].
|
|
37
|
+
- Employs pruning optimizations:
|
|
38
|
+
1. If k * minimum remaining element > target, no combination can reach target.
|
|
39
|
+
2. If k * maximum remaining element < target, no combination can reach target.
|
|
40
|
+
- Base case k == 2 uses the optimal two-pointer two-sum approach.
|
|
41
|
+
- Pure function: does not mutate the caller's input sequence.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
nums: A sequence of integers.
|
|
45
|
+
target: The desired target sum.
|
|
46
|
+
k: The number of elements in each tuple (k >= 2).
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
A list of unique k-tuples summing to target.
|
|
50
|
+
|
|
51
|
+
Complexity:
|
|
52
|
+
Time: O(n^(k-1)) where n is len(nums). For k=4, O(n^3); for k=3, O(n^2).
|
|
53
|
+
Space: O(n + k) for sorted copy and recursion call stack.
|
|
54
|
+
|
|
55
|
+
Examples:
|
|
56
|
+
>>> k_sum([1, 0, -1, 0, -2, 2], target=0, k=4)
|
|
57
|
+
[(-2, -1, 1, 2), (-2, 0, 0, 2), (-1, 0, 0, 1)]
|
|
58
|
+
>>> k_sum([-1, 0, 1, 2, -1, -4], target=0, k=3)
|
|
59
|
+
[(-1, -1, 2), (-1, 0, 1)]
|
|
60
|
+
>>> k_sum([1, 2, 3], target=6, k=3)
|
|
61
|
+
[(1, 2, 3)]
|
|
62
|
+
>>> k_sum([1, 2], target=3, k=4)
|
|
63
|
+
[]
|
|
64
|
+
"""
|
|
65
|
+
n = len(nums)
|
|
66
|
+
if k < 2 or n < k:
|
|
67
|
+
return []
|
|
68
|
+
|
|
69
|
+
sorted_nums = sorted(nums)
|
|
70
|
+
|
|
71
|
+
def _helper(start: int, sub_target: int, sub_k: int) -> list[list[int]]:
|
|
72
|
+
res: list[list[int]] = []
|
|
73
|
+
count = n - start
|
|
74
|
+
if count < sub_k:
|
|
75
|
+
return res
|
|
76
|
+
|
|
77
|
+
min_val = sorted_nums[start]
|
|
78
|
+
max_val = sorted_nums[-1]
|
|
79
|
+
|
|
80
|
+
# Pruning: sub_target cannot be achieved by any elements in remaining range
|
|
81
|
+
if sub_k * min_val > sub_target or sub_k * max_val < sub_target:
|
|
82
|
+
return res
|
|
83
|
+
|
|
84
|
+
# Base case: 2-Sum via two pointers
|
|
85
|
+
if sub_k == 2:
|
|
86
|
+
left = start
|
|
87
|
+
right = n - 1
|
|
88
|
+
while left < right:
|
|
89
|
+
curr_sum = sorted_nums[left] + sorted_nums[right]
|
|
90
|
+
if curr_sum == sub_target:
|
|
91
|
+
res.append([sorted_nums[left], sorted_nums[right]])
|
|
92
|
+
left += 1
|
|
93
|
+
right -= 1
|
|
94
|
+
while left < right and sorted_nums[left] == sorted_nums[left - 1]:
|
|
95
|
+
left += 1
|
|
96
|
+
while left < right and sorted_nums[right] == sorted_nums[right + 1]:
|
|
97
|
+
right -= 1
|
|
98
|
+
elif curr_sum < sub_target:
|
|
99
|
+
left += 1
|
|
100
|
+
else:
|
|
101
|
+
right -= 1
|
|
102
|
+
return res
|
|
103
|
+
|
|
104
|
+
# Recursive case: sub_k > 2
|
|
105
|
+
for i in range(start, n - sub_k + 1):
|
|
106
|
+
val = sorted_nums[i]
|
|
107
|
+
# Avoid duplicate elements at the current position
|
|
108
|
+
if i > start and val == sorted_nums[i - 1]:
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
# Additional early stopping bounds for the current loop element
|
|
112
|
+
if val + (sub_k - 1) * sorted_nums[i + 1] > sub_target:
|
|
113
|
+
break
|
|
114
|
+
if val + (sub_k - 1) * max_val < sub_target:
|
|
115
|
+
continue
|
|
116
|
+
|
|
117
|
+
sub_results = _helper(i + 1, sub_target - val, sub_k - 1)
|
|
118
|
+
for sub in sub_results:
|
|
119
|
+
res.append([val] + sub)
|
|
120
|
+
|
|
121
|
+
return res
|
|
122
|
+
|
|
123
|
+
results = _helper(0, target, k)
|
|
124
|
+
return [tuple(r) for r in results]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def k_sum_closest(nums: Sequence[int], target: int, k: int) -> int | None:
|
|
128
|
+
"""Find the sum of k elements in nums closest to target.
|
|
129
|
+
|
|
130
|
+
Assumptions & Behavior:
|
|
131
|
+
- Input can be unsorted and contain negative numbers or duplicates.
|
|
132
|
+
- If k < 1 or len(nums) < k, returns None.
|
|
133
|
+
- Tie-breaking: If two sums are equally distant from target, the smaller sum is returned.
|
|
134
|
+
- Pure function: does not mutate caller's input.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
nums: A sequence of integers.
|
|
138
|
+
target: Target sum to approximate.
|
|
139
|
+
k: Number of elements in each candidate combination (k >= 1).
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
The sum of k elements closest to target, or None if len(nums) < k.
|
|
143
|
+
|
|
144
|
+
Complexity:
|
|
145
|
+
Time: O(n^(k-1)) where n is len(nums).
|
|
146
|
+
Space: O(n + k) for sorted copy and recursion stack.
|
|
147
|
+
|
|
148
|
+
Examples:
|
|
149
|
+
>>> k_sum_closest([-1, 2, 1, -4], target=1, k=3)
|
|
150
|
+
2
|
|
151
|
+
>>> k_sum_closest([1, 1, 1, 0], target=100, k=4)
|
|
152
|
+
3
|
|
153
|
+
"""
|
|
154
|
+
n = len(nums)
|
|
155
|
+
if k < 1 or n < k:
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
sorted_nums = sorted(nums)
|
|
159
|
+
|
|
160
|
+
if k == 1:
|
|
161
|
+
best = sorted_nums[0]
|
|
162
|
+
for val in sorted_nums:
|
|
163
|
+
diff_curr = abs(val - target)
|
|
164
|
+
diff_best = abs(best - target)
|
|
165
|
+
if diff_curr < diff_best or (diff_curr == diff_best and val < best):
|
|
166
|
+
best = val
|
|
167
|
+
return best
|
|
168
|
+
|
|
169
|
+
def _helper(start: int, sub_target: int, sub_k: int) -> int:
|
|
170
|
+
if sub_k == 2:
|
|
171
|
+
left = start
|
|
172
|
+
right = n - 1
|
|
173
|
+
closest = sorted_nums[left] + sorted_nums[right]
|
|
174
|
+
while left < right:
|
|
175
|
+
curr_sum = sorted_nums[left] + sorted_nums[right]
|
|
176
|
+
if curr_sum == sub_target:
|
|
177
|
+
return sub_target
|
|
178
|
+
|
|
179
|
+
diff_curr = abs(curr_sum - sub_target)
|
|
180
|
+
diff_closest = abs(closest - sub_target)
|
|
181
|
+
if diff_curr < diff_closest or (
|
|
182
|
+
diff_curr == diff_closest and curr_sum < closest
|
|
183
|
+
):
|
|
184
|
+
closest = curr_sum
|
|
185
|
+
|
|
186
|
+
if curr_sum < sub_target:
|
|
187
|
+
left += 1
|
|
188
|
+
else:
|
|
189
|
+
right -= 1
|
|
190
|
+
return closest
|
|
191
|
+
|
|
192
|
+
# sub_k > 2
|
|
193
|
+
closest = sum(sorted_nums[start : start + sub_k])
|
|
194
|
+
for i in range(start, n - sub_k + 1):
|
|
195
|
+
if i > start and sorted_nums[i] == sorted_nums[i - 1]:
|
|
196
|
+
continue
|
|
197
|
+
|
|
198
|
+
val = sorted_nums[i]
|
|
199
|
+
# Prune if lowest possible sum from index i exceeds target and is worse than current best
|
|
200
|
+
min_possible = val + sum(sorted_nums[i + 1 : i + sub_k])
|
|
201
|
+
if min_possible > sub_target and abs(min_possible - sub_target) > abs(
|
|
202
|
+
closest - sub_target
|
|
203
|
+
):
|
|
204
|
+
break
|
|
205
|
+
|
|
206
|
+
sub_closest = _helper(i + 1, sub_target - val, sub_k - 1)
|
|
207
|
+
curr = val + sub_closest
|
|
208
|
+
|
|
209
|
+
if curr == sub_target:
|
|
210
|
+
return sub_target
|
|
211
|
+
|
|
212
|
+
diff_curr = abs(curr - sub_target)
|
|
213
|
+
diff_closest = abs(closest - sub_target)
|
|
214
|
+
if diff_curr < diff_closest or (
|
|
215
|
+
diff_curr == diff_closest and curr < closest
|
|
216
|
+
):
|
|
217
|
+
closest = curr
|
|
218
|
+
|
|
219
|
+
return closest
|
|
220
|
+
|
|
221
|
+
return _helper(0, target, k)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def k_sum_smaller(nums: Sequence[int], target: int, k: int) -> int:
|
|
225
|
+
"""Count index k-tuples (i_1 < i_2 < ... < i_k) whose sum is strictly less than target.
|
|
226
|
+
|
|
227
|
+
Assumptions & Behavior:
|
|
228
|
+
- Input can be unsorted and may contain duplicates.
|
|
229
|
+
- Counts combinations of indices: identical values at different positions are distinct.
|
|
230
|
+
- If k < 1 or len(nums) < k, returns 0.
|
|
231
|
+
- Pure function: does not mutate the caller's input.
|
|
232
|
+
|
|
233
|
+
Args:
|
|
234
|
+
nums: A sequence of integers.
|
|
235
|
+
target: Target sum upper bound (strictly less than).
|
|
236
|
+
k: Number of elements in each tuple.
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
Total count of index k-tuples summing to < target.
|
|
240
|
+
|
|
241
|
+
Complexity:
|
|
242
|
+
Time: O(n^(k-1)) where n is len(nums).
|
|
243
|
+
Space: O(n + k).
|
|
244
|
+
|
|
245
|
+
Examples:
|
|
246
|
+
>>> k_sum_smaller([-2, 0, 1, 3], target=2, k=3)
|
|
247
|
+
2
|
|
248
|
+
>>> k_sum_smaller([1, 1, 1, 1], target=5, k=4)
|
|
249
|
+
1
|
|
250
|
+
"""
|
|
251
|
+
n = len(nums)
|
|
252
|
+
if k < 1 or n < k:
|
|
253
|
+
return 0
|
|
254
|
+
|
|
255
|
+
sorted_nums = sorted(nums)
|
|
256
|
+
|
|
257
|
+
if k == 1:
|
|
258
|
+
# Count elements < target
|
|
259
|
+
return sum(1 for x in sorted_nums if x < target)
|
|
260
|
+
|
|
261
|
+
def _helper(start: int, sub_target: int, sub_k: int) -> int:
|
|
262
|
+
if sub_k == 2:
|
|
263
|
+
left = start
|
|
264
|
+
right = n - 1
|
|
265
|
+
count = 0
|
|
266
|
+
while left < right:
|
|
267
|
+
if sorted_nums[left] + sorted_nums[right] < sub_target:
|
|
268
|
+
count += right - left
|
|
269
|
+
left += 1
|
|
270
|
+
else:
|
|
271
|
+
right -= 1
|
|
272
|
+
return count
|
|
273
|
+
|
|
274
|
+
count = 0
|
|
275
|
+
for i in range(start, n - sub_k + 1):
|
|
276
|
+
# Prune if the minimum sum achievable from index i is >= sub_target
|
|
277
|
+
if sum(sorted_nums[i : i + sub_k]) >= sub_target:
|
|
278
|
+
break
|
|
279
|
+
count += _helper(i + 1, sub_target - sorted_nums[i], sub_k - 1)
|
|
280
|
+
|
|
281
|
+
return count
|
|
282
|
+
|
|
283
|
+
return _helper(0, target, k)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def four_sum(nums: Sequence[int], target: int = 0) -> list[tuple[int, int, int, int]]:
|
|
287
|
+
"""Find all unique quadruplets [a, b, c, d] summing to target (LeetCode 18).
|
|
288
|
+
|
|
289
|
+
Assumptions & Behavior:
|
|
290
|
+
- Input can be unsorted and may contain duplicates and negative numbers.
|
|
291
|
+
- Quadruplets are unique (deduplicated).
|
|
292
|
+
- Each quadruplet is ordered: a <= b <= c <= d.
|
|
293
|
+
- Returns [] if len(nums) < 4.
|
|
294
|
+
- Pure function: does not mutate caller's input.
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
nums: A sequence of integers.
|
|
298
|
+
target: The target sum (defaults to 0).
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
A list of unique 4-tuples summing to target.
|
|
302
|
+
|
|
303
|
+
Complexity:
|
|
304
|
+
Time: O(n^3) where n is len(nums).
|
|
305
|
+
Space: O(n) for the sorted copy.
|
|
306
|
+
|
|
307
|
+
Examples:
|
|
308
|
+
>>> four_sum([1, 0, -1, 0, -2, 2], 0)
|
|
309
|
+
[(-2, -1, 1, 2), (-2, 0, 0, 2), (-1, 0, 0, 1)]
|
|
310
|
+
>>> four_sum([2, 2, 2, 2, 2], 8)
|
|
311
|
+
[(2, 2, 2, 2)]
|
|
312
|
+
"""
|
|
313
|
+
results = k_sum(nums, target=target, k=4)
|
|
314
|
+
return [t for t in results if len(t) == 4] # type: ignore[misc]
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def four_sum_closest(nums: Sequence[int], target: int) -> int | None:
|
|
318
|
+
"""Find the sum of four integers closest to target.
|
|
319
|
+
|
|
320
|
+
Assumptions & Behavior:
|
|
321
|
+
- If len(nums) < 4, returns None.
|
|
322
|
+
- Tie-breaking: smaller sum preferred.
|
|
323
|
+
- Pure function: does not mutate caller's input.
|
|
324
|
+
|
|
325
|
+
Args:
|
|
326
|
+
nums: A sequence of integers.
|
|
327
|
+
target: Target sum.
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
The sum of four elements closest to target, or None if len(nums) < 4.
|
|
331
|
+
|
|
332
|
+
Complexity:
|
|
333
|
+
Time: O(n^3) where n is len(nums).
|
|
334
|
+
Space: O(n).
|
|
335
|
+
|
|
336
|
+
Examples:
|
|
337
|
+
>>> four_sum_closest([1, 0, -1, 0, -2, 2], 0)
|
|
338
|
+
0
|
|
339
|
+
>>> four_sum_closest([1, 1, 1], 5) is None
|
|
340
|
+
True
|
|
341
|
+
"""
|
|
342
|
+
return k_sum_closest(nums, target=target, k=4)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def four_sum_smaller(nums: Sequence[int], target: int) -> int:
|
|
346
|
+
"""Count index quadruplets (i, j, k, l) with i < j < k < l whose sum is strictly less than target.
|
|
347
|
+
|
|
348
|
+
Assumptions & Behavior:
|
|
349
|
+
- If len(nums) < 4, returns 0.
|
|
350
|
+
- Counts index combinations.
|
|
351
|
+
- Pure function: does not mutate caller's input.
|
|
352
|
+
|
|
353
|
+
Args:
|
|
354
|
+
nums: A sequence of integers.
|
|
355
|
+
target: Strict upper bound sum.
|
|
356
|
+
|
|
357
|
+
Returns:
|
|
358
|
+
Count of index quadruplets with sum < target.
|
|
359
|
+
|
|
360
|
+
Complexity:
|
|
361
|
+
Time: O(n^3) where n is len(nums).
|
|
362
|
+
Space: O(n).
|
|
363
|
+
|
|
364
|
+
Examples:
|
|
365
|
+
>>> four_sum_smaller([1, 1, 1, 1], 5)
|
|
366
|
+
1
|
|
367
|
+
>>> four_sum_smaller([1, 1, 1, 1], 4)
|
|
368
|
+
0
|
|
369
|
+
"""
|
|
370
|
+
return k_sum_smaller(nums, target=target, k=4)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def four_sum_ii(
|
|
374
|
+
nums1: Sequence[int],
|
|
375
|
+
nums2: Sequence[int],
|
|
376
|
+
nums3: Sequence[int],
|
|
377
|
+
nums4: Sequence[int],
|
|
378
|
+
) -> int:
|
|
379
|
+
"""Count quadruplets (i, j, k, l) such that nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 (LeetCode 454).
|
|
380
|
+
|
|
381
|
+
Assumptions & Behavior:
|
|
382
|
+
- All four arrays can have different or identical lengths.
|
|
383
|
+
- Works with negative numbers, duplicates, and zeros.
|
|
384
|
+
- Uses a hash map to reduce O(n^4) brute force down to O(n^2).
|
|
385
|
+
- Pure function: does not mutate any inputs.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
nums1: First sequence of integers.
|
|
389
|
+
nums2: Second sequence of integers.
|
|
390
|
+
nums3: Third sequence of integers.
|
|
391
|
+
nums4: Fourth sequence of integers.
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
Total count of index tuples (i, j, k, l) whose sum is 0.
|
|
395
|
+
|
|
396
|
+
Complexity:
|
|
397
|
+
Time: O(len(nums1) * len(nums2) + len(nums3) * len(nums4)) -> O(n^2) when lengths are ~n.
|
|
398
|
+
Space: O(len(nums1) * len(nums2)) for the pair sums hash table.
|
|
399
|
+
|
|
400
|
+
Examples:
|
|
401
|
+
>>> four_sum_ii([1, 2], [-2, -1], [-1, 2], [0, 2])
|
|
402
|
+
2
|
|
403
|
+
>>> four_sum_ii([0], [0], [0], [0])
|
|
404
|
+
1
|
|
405
|
+
"""
|
|
406
|
+
sum_counts: Counter[int] = Counter()
|
|
407
|
+
for a in nums1:
|
|
408
|
+
for b in nums2:
|
|
409
|
+
sum_counts[a + b] += 1
|
|
410
|
+
|
|
411
|
+
total_tuples = 0
|
|
412
|
+
for c in nums3:
|
|
413
|
+
for d in nums4:
|
|
414
|
+
total_tuples += sum_counts[-(c + d)]
|
|
415
|
+
|
|
416
|
+
return total_tuples
|
sum_helpers/py.typed
ADDED
|
File without changes
|
sum_helpers/three_sum.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Three Sum helper functions.
|
|
2
|
+
|
|
3
|
+
This module provides solutions for classic Three Sum problem variants:
|
|
4
|
+
- LC 15: 3Sum (unique triplets summing to target, default 0)
|
|
5
|
+
- LC 16: 3Sum Closest (sum of three integers closest to target)
|
|
6
|
+
- LC 259: 3Sum Smaller (count of index triplets summing to strictly less than target)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Sequence
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"three_sum",
|
|
15
|
+
"three_sum_closest",
|
|
16
|
+
"three_sum_smaller",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def three_sum(nums: Sequence[int], target: int = 0) -> list[tuple[int, int, int]]:
|
|
21
|
+
"""Find all unique triplets [a, b, c] summing to target (LeetCode 15).
|
|
22
|
+
|
|
23
|
+
Assumptions & Behavior:
|
|
24
|
+
- Input can be unsorted and may contain duplicates or negative numbers.
|
|
25
|
+
- Triplets are unique (no duplicates in the result set).
|
|
26
|
+
- Each triplet (a, b, c) is sorted such that a <= b <= c.
|
|
27
|
+
- If len(nums) < 3, returns an empty list [].
|
|
28
|
+
- Pure function: does not mutate the caller's input.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
nums: A sequence of integers.
|
|
32
|
+
target: The target sum (defaults to 0 as in LC 15).
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
A list of unique triplets (a, b, c) where a + b + c == target and a <= b <= c.
|
|
36
|
+
|
|
37
|
+
Complexity:
|
|
38
|
+
Time: O(n^2) where n is len(nums).
|
|
39
|
+
Space: O(n) for the sorted copy.
|
|
40
|
+
|
|
41
|
+
Examples:
|
|
42
|
+
>>> three_sum([-1, 0, 1, 2, -1, -4])
|
|
43
|
+
[(-1, -1, 2), (-1, 0, 1)]
|
|
44
|
+
>>> three_sum([0, 1, 1])
|
|
45
|
+
[]
|
|
46
|
+
>>> three_sum([0, 0, 0])
|
|
47
|
+
[(0, 0, 0)]
|
|
48
|
+
"""
|
|
49
|
+
n = len(nums)
|
|
50
|
+
if n < 3:
|
|
51
|
+
return []
|
|
52
|
+
|
|
53
|
+
sorted_nums = sorted(nums)
|
|
54
|
+
triplets: list[tuple[int, int, int]] = []
|
|
55
|
+
|
|
56
|
+
for i in range(n - 2):
|
|
57
|
+
val_i = sorted_nums[i]
|
|
58
|
+
|
|
59
|
+
# Skip duplicate values for the first element
|
|
60
|
+
if i > 0 and val_i == sorted_nums[i - 1]:
|
|
61
|
+
continue
|
|
62
|
+
|
|
63
|
+
# Pruning optimizations based on sorted order:
|
|
64
|
+
# Minimum possible sum with current element exceeds target -> stop
|
|
65
|
+
if val_i + sorted_nums[i + 1] + sorted_nums[i + 2] > target:
|
|
66
|
+
break
|
|
67
|
+
# Maximum possible sum with current element is below target -> skip to next
|
|
68
|
+
if val_i + sorted_nums[-2] + sorted_nums[-1] < target:
|
|
69
|
+
continue
|
|
70
|
+
|
|
71
|
+
left = i + 1
|
|
72
|
+
right = n - 1
|
|
73
|
+
|
|
74
|
+
while left < right:
|
|
75
|
+
curr_sum = val_i + sorted_nums[left] + sorted_nums[right]
|
|
76
|
+
|
|
77
|
+
if curr_sum == target:
|
|
78
|
+
triplets.append((val_i, sorted_nums[left], sorted_nums[right]))
|
|
79
|
+
left += 1
|
|
80
|
+
right -= 1
|
|
81
|
+
|
|
82
|
+
# Skip duplicates for second and third elements
|
|
83
|
+
while left < right and sorted_nums[left] == sorted_nums[left - 1]:
|
|
84
|
+
left += 1
|
|
85
|
+
while left < right and sorted_nums[right] == sorted_nums[right + 1]:
|
|
86
|
+
right -= 1
|
|
87
|
+
elif curr_sum < target:
|
|
88
|
+
left += 1
|
|
89
|
+
else:
|
|
90
|
+
right -= 1
|
|
91
|
+
|
|
92
|
+
return triplets
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def three_sum_closest(nums: Sequence[int], target: int) -> int | None:
|
|
96
|
+
"""Find the sum of three integers closest to target (LeetCode 16).
|
|
97
|
+
|
|
98
|
+
Assumptions & Behavior:
|
|
99
|
+
- Input can be unsorted and contain duplicates or negative numbers.
|
|
100
|
+
- If len(nums) < 3, returns None.
|
|
101
|
+
- Tie-breaking: If two sums have equal distance to target, the smaller sum is returned.
|
|
102
|
+
- Returns exact target immediately if a triplet sum equals target.
|
|
103
|
+
- Pure function: does not mutate the caller's input.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
nums: A sequence of integers.
|
|
107
|
+
target: The target integer to approximate.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
The sum of three integers closest to target, or None if len(nums) < 3.
|
|
111
|
+
|
|
112
|
+
Complexity:
|
|
113
|
+
Time: O(n^2) where n is len(nums).
|
|
114
|
+
Space: O(n) for the sorted copy.
|
|
115
|
+
|
|
116
|
+
Examples:
|
|
117
|
+
>>> three_sum_closest([-1, 2, 1, -4], 1)
|
|
118
|
+
2
|
|
119
|
+
>>> three_sum_closest([0, 0, 0], 1)
|
|
120
|
+
0
|
|
121
|
+
>>> three_sum_closest([1, 1], 2) is None
|
|
122
|
+
True
|
|
123
|
+
"""
|
|
124
|
+
n = len(nums)
|
|
125
|
+
if n < 3:
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
sorted_nums = sorted(nums)
|
|
129
|
+
closest_sum = sorted_nums[0] + sorted_nums[1] + sorted_nums[2]
|
|
130
|
+
|
|
131
|
+
for i in range(n - 2):
|
|
132
|
+
if i > 0 and sorted_nums[i] == sorted_nums[i - 1]:
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
val_i = sorted_nums[i]
|
|
136
|
+
left = i + 1
|
|
137
|
+
right = n - 1
|
|
138
|
+
|
|
139
|
+
while left < right:
|
|
140
|
+
curr_sum = val_i + sorted_nums[left] + sorted_nums[right]
|
|
141
|
+
|
|
142
|
+
if curr_sum == target:
|
|
143
|
+
return target
|
|
144
|
+
|
|
145
|
+
curr_diff = abs(curr_sum - target)
|
|
146
|
+
best_diff = abs(closest_sum - target)
|
|
147
|
+
|
|
148
|
+
if curr_diff < best_diff or (curr_diff == best_diff and curr_sum < closest_sum):
|
|
149
|
+
closest_sum = curr_sum
|
|
150
|
+
|
|
151
|
+
if curr_sum < target:
|
|
152
|
+
left += 1
|
|
153
|
+
else:
|
|
154
|
+
right -= 1
|
|
155
|
+
|
|
156
|
+
return closest_sum
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def three_sum_smaller(nums: Sequence[int], target: int) -> int:
|
|
160
|
+
"""Count index triplets (i, j, k) with i < j < k whose sum is strictly less than target (LeetCode 259).
|
|
161
|
+
|
|
162
|
+
Assumptions & Behavior:
|
|
163
|
+
- Input can be unsorted and may contain duplicates and negative numbers.
|
|
164
|
+
- Counts index triplets: identical values at distinct indices are counted separately.
|
|
165
|
+
- If len(nums) < 3, returns 0.
|
|
166
|
+
- Pure function: does not mutate the caller's input.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
nums: A sequence of integers.
|
|
170
|
+
target: The target sum upper bound (strictly less than).
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
The total number of index triplets (i, j, k) with i < j < k and nums[i] + nums[j] + nums[k] < target.
|
|
174
|
+
|
|
175
|
+
Complexity:
|
|
176
|
+
Time: O(n^2) where n is len(nums).
|
|
177
|
+
Space: O(n) for the sorted copy.
|
|
178
|
+
|
|
179
|
+
Examples:
|
|
180
|
+
>>> three_sum_smaller([-2, 0, 1, 3], 2)
|
|
181
|
+
2
|
|
182
|
+
>>> three_sum_smaller([], 0)
|
|
183
|
+
0
|
|
184
|
+
>>> three_sum_smaller([0], 0)
|
|
185
|
+
0
|
|
186
|
+
"""
|
|
187
|
+
n = len(nums)
|
|
188
|
+
if n < 3:
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
sorted_nums = sorted(nums)
|
|
192
|
+
count = 0
|
|
193
|
+
|
|
194
|
+
for i in range(n - 2):
|
|
195
|
+
left = i + 1
|
|
196
|
+
right = n - 1
|
|
197
|
+
|
|
198
|
+
while left < right:
|
|
199
|
+
curr_sum = sorted_nums[i] + sorted_nums[left] + sorted_nums[right]
|
|
200
|
+
if curr_sum < target:
|
|
201
|
+
# Since sorted_nums is non-decreasing, all elements between left and right
|
|
202
|
+
# paired with sorted_nums[i] and sorted_nums[left] will also sum to < target.
|
|
203
|
+
count += right - left
|
|
204
|
+
left += 1
|
|
205
|
+
else:
|
|
206
|
+
right -= 1
|
|
207
|
+
|
|
208
|
+
return count
|
sum_helpers/triangle.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Triangle Sum and Valid Triangle helper functions.
|
|
2
|
+
|
|
3
|
+
This module provides helpers for triangle inequality and sum problems:
|
|
4
|
+
- LC 611: Valid Triangle Number (count triplets that can form sides of a triangle)
|
|
5
|
+
- is_valid_triangle: Check whether three side lengths can form a valid triangle
|
|
6
|
+
- find_valid_triangles: Return unique sorted value triplets forming valid triangles
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Sequence
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"valid_triangle_number",
|
|
15
|
+
"is_valid_triangle",
|
|
16
|
+
"find_valid_triangles",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_valid_triangle(a: int, b: int, c: int) -> bool:
|
|
21
|
+
"""Check if three side lengths can form a valid, non-degenerate triangle.
|
|
22
|
+
|
|
23
|
+
A valid triangle requires strictly positive side lengths and must satisfy the
|
|
24
|
+
triangle inequality theorem:
|
|
25
|
+
a + b > c and a + c > b and b + c > a.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
a: First side length.
|
|
29
|
+
b: Second side length.
|
|
30
|
+
c: Third side length.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
True if the sides form a valid non-degenerate triangle, False otherwise.
|
|
34
|
+
|
|
35
|
+
Complexity:
|
|
36
|
+
Time: O(1)
|
|
37
|
+
Space: O(1)
|
|
38
|
+
|
|
39
|
+
Examples:
|
|
40
|
+
>>> is_valid_triangle(3, 4, 5)
|
|
41
|
+
True
|
|
42
|
+
>>> is_valid_triangle(1, 2, 3)
|
|
43
|
+
False
|
|
44
|
+
>>> is_valid_triangle(0, 2, 2)
|
|
45
|
+
False
|
|
46
|
+
>>> is_valid_triangle(-2, 3, 4)
|
|
47
|
+
False
|
|
48
|
+
"""
|
|
49
|
+
if a <= 0 or b <= 0 or c <= 0:
|
|
50
|
+
return False
|
|
51
|
+
return (a + b > c) and (a + c > b) and (b + c > a)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def valid_triangle_number(nums: Sequence[int]) -> int:
|
|
55
|
+
"""Count the number of triplets that can form a valid triangle (LeetCode 611).
|
|
56
|
+
|
|
57
|
+
Assumptions & Behavior:
|
|
58
|
+
- Input can be unsorted and may contain zero or negative numbers (which cannot
|
|
59
|
+
form triangle sides).
|
|
60
|
+
- Counts index triplets (i, j, k) with i < j < k whose elements can form a triangle.
|
|
61
|
+
- Two-pointer method: sorts array, fixes the largest side k from right to left,
|
|
62
|
+
and finds pairs (left, right) where nums[left] + nums[right] > nums[k].
|
|
63
|
+
- Pure function: does not mutate caller's input sequence.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
nums: A sequence of side lengths.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
Total number of index triplets (i, j, k) with i < j < k that can form a triangle.
|
|
70
|
+
|
|
71
|
+
Complexity:
|
|
72
|
+
Time: O(n^2) where n is len(nums).
|
|
73
|
+
Space: O(n) for the sorted copy.
|
|
74
|
+
|
|
75
|
+
Examples:
|
|
76
|
+
>>> valid_triangle_number([2, 2, 3, 4])
|
|
77
|
+
3
|
|
78
|
+
>>> valid_triangle_number([4, 2, 3, 4])
|
|
79
|
+
4
|
|
80
|
+
>>> valid_triangle_number([0, 1, 0])
|
|
81
|
+
0
|
|
82
|
+
>>> valid_triangle_number([7, 0, 0, 0])
|
|
83
|
+
0
|
|
84
|
+
"""
|
|
85
|
+
n = len(nums)
|
|
86
|
+
if n < 3:
|
|
87
|
+
return 0
|
|
88
|
+
|
|
89
|
+
sorted_nums = sorted(nums)
|
|
90
|
+
count = 0
|
|
91
|
+
|
|
92
|
+
# Iterate from the largest side backwards down to index 2
|
|
93
|
+
for k in range(n - 1, 1, -1):
|
|
94
|
+
c = sorted_nums[k]
|
|
95
|
+
# In sorted array, if the largest side is <= 0, no valid triangle can be formed
|
|
96
|
+
if c <= 0:
|
|
97
|
+
break
|
|
98
|
+
|
|
99
|
+
left = 0
|
|
100
|
+
right = k - 1
|
|
101
|
+
|
|
102
|
+
while left < right:
|
|
103
|
+
if sorted_nums[left] + sorted_nums[right] > c:
|
|
104
|
+
# Since sorted_nums is non-decreasing, all elements between left and right - 1
|
|
105
|
+
# added to sorted_nums[right] will also be > c.
|
|
106
|
+
count += right - left
|
|
107
|
+
right -= 1
|
|
108
|
+
else:
|
|
109
|
+
left += 1
|
|
110
|
+
|
|
111
|
+
return count
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def find_valid_triangles(nums: Sequence[int]) -> list[tuple[int, int, int]]:
|
|
115
|
+
"""Return all unique value triplets (a, b, c) with a <= b <= c that form a valid triangle.
|
|
116
|
+
|
|
117
|
+
Unlike valid_triangle_number which counts index combinations, this function returns
|
|
118
|
+
the set of distinct side-length combinations that can form valid triangles.
|
|
119
|
+
|
|
120
|
+
Assumptions & Behavior:
|
|
121
|
+
- Side lengths must be positive (<= 0 sides are filtered out).
|
|
122
|
+
- Triplets are unique (deduplicated).
|
|
123
|
+
- Each triplet (a, b, c) is sorted such that a <= b <= c.
|
|
124
|
+
- Pure function: does not mutate caller's input.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
nums: A sequence of integers representing candidate side lengths.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
A list of unique sorted tuples (a, b, c) where a + b > c.
|
|
131
|
+
|
|
132
|
+
Complexity:
|
|
133
|
+
Time: O(n^2) where n is len(nums).
|
|
134
|
+
Space: O(n) for sorting and deduplication.
|
|
135
|
+
|
|
136
|
+
Examples:
|
|
137
|
+
>>> find_valid_triangles([2, 2, 3, 4])
|
|
138
|
+
[(2, 2, 3), (2, 3, 4)]
|
|
139
|
+
>>> find_valid_triangles([1, 2, 3])
|
|
140
|
+
[]
|
|
141
|
+
"""
|
|
142
|
+
# Filter positive sides only and sort
|
|
143
|
+
positive_sides = sorted([x for x in nums if x > 0])
|
|
144
|
+
n = len(positive_sides)
|
|
145
|
+
if n < 3:
|
|
146
|
+
return []
|
|
147
|
+
|
|
148
|
+
unique_triplets: set[tuple[int, int, int]] = set()
|
|
149
|
+
|
|
150
|
+
for k in range(n - 1, 1, -1):
|
|
151
|
+
c = positive_sides[k]
|
|
152
|
+
left = 0
|
|
153
|
+
right = k - 1
|
|
154
|
+
|
|
155
|
+
while left < right:
|
|
156
|
+
if positive_sides[left] + positive_sides[right] > c:
|
|
157
|
+
for i in range(left, right):
|
|
158
|
+
unique_triplets.add((positive_sides[i], positive_sides[right], c))
|
|
159
|
+
right -= 1
|
|
160
|
+
else:
|
|
161
|
+
left += 1
|
|
162
|
+
|
|
163
|
+
return sorted(unique_triplets)
|
sum_helpers/two_sum.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Two Sum helper functions.
|
|
2
|
+
|
|
3
|
+
This module provides solutions for classic Two Sum variants:
|
|
4
|
+
- LC 1: Two Sum (hash table approach on unsorted sequence)
|
|
5
|
+
- LC 167: Two Sum II - Input Array Is Sorted (two-pointer approach on sorted sequence)
|
|
6
|
+
- LC 1099: Two Sum Less Than K (maximum sum strictly less than k)
|
|
7
|
+
- Two Sum Closest (sum of two numbers closest to target)
|
|
8
|
+
- Two Sum Unique Pairs (all unique value pairs summing to target)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import Sequence
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"two_sum",
|
|
17
|
+
"two_sum_sorted",
|
|
18
|
+
"two_sum_less_than_k",
|
|
19
|
+
"two_sum_closest",
|
|
20
|
+
"two_sum_unique_pairs",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def two_sum(nums: Sequence[int], target: int) -> tuple[int, int] | None:
|
|
25
|
+
"""Find 0-indexed indices of two numbers that add up to target (LeetCode 1).
|
|
26
|
+
|
|
27
|
+
Assumptions & Behavior:
|
|
28
|
+
- Input can be unsorted.
|
|
29
|
+
- Returns indices (i, j) with i < j of the first matching pair encountered.
|
|
30
|
+
- If no two numbers add up to target, or if len(nums) < 2, returns None.
|
|
31
|
+
- Does not mutate the input sequence.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
nums: A sequence of integers.
|
|
35
|
+
target: The target sum.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
A tuple (i, j) of 0-based indices such that nums[i] + nums[j] == target,
|
|
39
|
+
or None if no valid pair exists.
|
|
40
|
+
|
|
41
|
+
Complexity:
|
|
42
|
+
Time: O(n) where n is len(nums), single pass with hash table lookup.
|
|
43
|
+
Space: O(n) for the hash table in the worst case.
|
|
44
|
+
|
|
45
|
+
Examples:
|
|
46
|
+
>>> two_sum([2, 7, 11, 15], 9)
|
|
47
|
+
(0, 1)
|
|
48
|
+
>>> two_sum([3, 2, 4], 6)
|
|
49
|
+
(1, 2)
|
|
50
|
+
>>> two_sum([3, 3], 6)
|
|
51
|
+
(0, 1)
|
|
52
|
+
>>> two_sum([1, 2], 5) is None
|
|
53
|
+
True
|
|
54
|
+
"""
|
|
55
|
+
if len(nums) < 2:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
# Map value to its earliest observed index
|
|
59
|
+
seen: dict[int, int] = {}
|
|
60
|
+
for j, num in enumerate(nums):
|
|
61
|
+
complement = target - num
|
|
62
|
+
if complement in seen:
|
|
63
|
+
return seen[complement], j
|
|
64
|
+
if num not in seen:
|
|
65
|
+
seen[num] = j
|
|
66
|
+
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def two_sum_sorted(numbers: Sequence[int], target: int) -> tuple[int, int] | None:
|
|
71
|
+
"""Find 1-indexed indices of two numbers in a sorted array summing to target (LeetCode 167).
|
|
72
|
+
|
|
73
|
+
Assumptions & Behavior:
|
|
74
|
+
- Input numbers MUST be sorted in non-decreasing order.
|
|
75
|
+
- Returns 1-indexed indices (i, j) with 1 <= i < j <= len(numbers).
|
|
76
|
+
- If no pair sums to target, or len(numbers) < 2, returns None.
|
|
77
|
+
- Uses the optimal two-pointer technique without extra memory.
|
|
78
|
+
- Does not mutate the input sequence.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
numbers: A sorted sequence of integers in non-decreasing order.
|
|
82
|
+
target: The target sum.
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
A 1-indexed tuple (i, j) such that numbers[i - 1] + numbers[j - 1] == target,
|
|
86
|
+
or None if no valid pair exists.
|
|
87
|
+
|
|
88
|
+
Complexity:
|
|
89
|
+
Time: O(n) where n is len(numbers).
|
|
90
|
+
Space: O(1) auxiliary space.
|
|
91
|
+
|
|
92
|
+
Examples:
|
|
93
|
+
>>> two_sum_sorted([2, 7, 11, 15], 9)
|
|
94
|
+
(1, 2)
|
|
95
|
+
>>> two_sum_sorted([2, 3, 4], 6)
|
|
96
|
+
(1, 3)
|
|
97
|
+
>>> two_sum_sorted([-1, 0], -1)
|
|
98
|
+
(1, 2)
|
|
99
|
+
>>> two_sum_sorted([1, 2], 10) is None
|
|
100
|
+
True
|
|
101
|
+
"""
|
|
102
|
+
if len(numbers) < 2:
|
|
103
|
+
return None
|
|
104
|
+
|
|
105
|
+
left = 0
|
|
106
|
+
right = len(numbers) - 1
|
|
107
|
+
|
|
108
|
+
while left < right:
|
|
109
|
+
curr_sum = numbers[left] + numbers[right]
|
|
110
|
+
if curr_sum == target:
|
|
111
|
+
return left + 1, right + 1
|
|
112
|
+
if curr_sum < target:
|
|
113
|
+
left += 1
|
|
114
|
+
else:
|
|
115
|
+
right -= 1
|
|
116
|
+
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def two_sum_less_than_k(nums: Sequence[int], k: int) -> int | None:
|
|
121
|
+
"""Find the maximum sum of two distinct elements strictly less than k (LeetCode 1099).
|
|
122
|
+
|
|
123
|
+
Assumptions & Behavior:
|
|
124
|
+
- Input can be unsorted.
|
|
125
|
+
- Finds max(nums[i] + nums[j]) such that i < j and nums[i] + nums[j] < k.
|
|
126
|
+
- If no pair has sum < k, or if len(nums) < 2, returns None.
|
|
127
|
+
- Pure function: does not mutate the caller's list (sorts a copy).
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
nums: A sequence of integers.
|
|
131
|
+
k: The upper threshold (strictly greater than the desired sum).
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
The maximum sum strictly less than k, or None if no such sum exists.
|
|
135
|
+
|
|
136
|
+
Complexity:
|
|
137
|
+
Time: O(n log n) due to sorting, where n is len(nums).
|
|
138
|
+
Space: O(n) for the sorted copy.
|
|
139
|
+
|
|
140
|
+
Examples:
|
|
141
|
+
>>> two_sum_less_than_k([34, 23, 1, 24, 75, 33, 54, 8], 60)
|
|
142
|
+
58
|
|
143
|
+
>>> two_sum_less_than_k([10, 20, 30], 15) is None
|
|
144
|
+
True
|
|
145
|
+
"""
|
|
146
|
+
if len(nums) < 2:
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
sorted_nums = sorted(nums)
|
|
150
|
+
left = 0
|
|
151
|
+
right = len(sorted_nums) - 1
|
|
152
|
+
max_sum: int | None = None
|
|
153
|
+
|
|
154
|
+
while left < right:
|
|
155
|
+
curr_sum = sorted_nums[left] + sorted_nums[right]
|
|
156
|
+
if curr_sum < k:
|
|
157
|
+
if max_sum is None or curr_sum > max_sum:
|
|
158
|
+
max_sum = curr_sum
|
|
159
|
+
left += 1
|
|
160
|
+
else:
|
|
161
|
+
right -= 1
|
|
162
|
+
|
|
163
|
+
return max_sum
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def two_sum_closest(nums: Sequence[int], target: int) -> int | None:
|
|
167
|
+
"""Find the sum of two integers closest to the target.
|
|
168
|
+
|
|
169
|
+
Assumptions & Behavior:
|
|
170
|
+
- Input can be unsorted.
|
|
171
|
+
- If len(nums) < 2, returns None.
|
|
172
|
+
- Tie-breaking: If two candidate sums are equally distant from target
|
|
173
|
+
(e.g., target 10, candidates 8 and 12), the smaller sum is returned.
|
|
174
|
+
- Pure function: sorts a shallow copy without modifying the original input.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
nums: A sequence of integers.
|
|
178
|
+
target: The target sum to approximate.
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
The sum of two elements whose sum is closest to target, or None if len(nums) < 2.
|
|
182
|
+
|
|
183
|
+
Complexity:
|
|
184
|
+
Time: O(n log n) where n is len(nums), dominated by sorting.
|
|
185
|
+
Space: O(n) for the sorted copy.
|
|
186
|
+
|
|
187
|
+
Examples:
|
|
188
|
+
>>> two_sum_closest([-1, 2, 1, -4], 1)
|
|
189
|
+
1
|
|
190
|
+
>>> two_sum_closest([1, 10, 20], 8)
|
|
191
|
+
11
|
|
192
|
+
"""
|
|
193
|
+
if len(nums) < 2:
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
sorted_nums = sorted(nums)
|
|
197
|
+
left = 0
|
|
198
|
+
right = len(sorted_nums) - 1
|
|
199
|
+
closest_sum = sorted_nums[left] + sorted_nums[right]
|
|
200
|
+
|
|
201
|
+
while left < right:
|
|
202
|
+
curr_sum = sorted_nums[left] + sorted_nums[right]
|
|
203
|
+
curr_diff = abs(curr_sum - target)
|
|
204
|
+
best_diff = abs(closest_sum - target)
|
|
205
|
+
|
|
206
|
+
if curr_diff < best_diff or (curr_diff == best_diff and curr_sum < closest_sum):
|
|
207
|
+
closest_sum = curr_sum
|
|
208
|
+
|
|
209
|
+
if curr_sum == target:
|
|
210
|
+
return target
|
|
211
|
+
if curr_sum < target:
|
|
212
|
+
left += 1
|
|
213
|
+
else:
|
|
214
|
+
right -= 1
|
|
215
|
+
|
|
216
|
+
return closest_sum
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def two_sum_unique_pairs(nums: Sequence[int], target: int) -> list[tuple[int, int]]:
|
|
220
|
+
"""Find all unique pairs of values (a, b) with a <= b that sum to target.
|
|
221
|
+
|
|
222
|
+
Assumptions & Behavior:
|
|
223
|
+
- Input can be unsorted and may contain duplicates.
|
|
224
|
+
- Returns unique pairs of values (not indices), ordered such that a <= b.
|
|
225
|
+
- The returned list of pairs is sorted in ascending order of the first element.
|
|
226
|
+
- Pure function: creates a sorted copy.
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
nums: A sequence of integers.
|
|
230
|
+
target: The target sum.
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
A list of unique tuples (a, b) such that a + b == target and a <= b.
|
|
234
|
+
|
|
235
|
+
Complexity:
|
|
236
|
+
Time: O(n log n) due to sorting.
|
|
237
|
+
Space: O(n) for sorted copy and output list.
|
|
238
|
+
|
|
239
|
+
Examples:
|
|
240
|
+
>>> two_sum_unique_pairs([1, 1, 2, 4, 3, 3, 5], 6)
|
|
241
|
+
[(1, 5), (2, 4), (3, 3)]
|
|
242
|
+
>>> two_sum_unique_pairs([1, 2, 3], 10)
|
|
243
|
+
[]
|
|
244
|
+
"""
|
|
245
|
+
if len(nums) < 2:
|
|
246
|
+
return []
|
|
247
|
+
|
|
248
|
+
sorted_nums = sorted(nums)
|
|
249
|
+
left = 0
|
|
250
|
+
right = len(sorted_nums) - 1
|
|
251
|
+
pairs: list[tuple[int, int]] = []
|
|
252
|
+
|
|
253
|
+
while left < right:
|
|
254
|
+
curr_sum = sorted_nums[left] + sorted_nums[right]
|
|
255
|
+
if curr_sum == target:
|
|
256
|
+
pairs.append((sorted_nums[left], sorted_nums[right]))
|
|
257
|
+
left += 1
|
|
258
|
+
right -= 1
|
|
259
|
+
while left < right and sorted_nums[left] == sorted_nums[left - 1]:
|
|
260
|
+
left += 1
|
|
261
|
+
while left < right and sorted_nums[right] == sorted_nums[right + 1]:
|
|
262
|
+
right -= 1
|
|
263
|
+
elif curr_sum < target:
|
|
264
|
+
left += 1
|
|
265
|
+
else:
|
|
266
|
+
right -= 1
|
|
267
|
+
|
|
268
|
+
return pairs
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sum-helpers
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Modular, typed Python utilities for two-sum, three-sum, triangle-sum, and generalized k-sum algorithms.
|
|
5
|
+
Keywords: algorithms,two-sum,three-sum,k-sum,two-pointer,combinatorics
|
|
6
|
+
Author: musleh-khan
|
|
7
|
+
Author-email: musleh-khan <MuslehUddin.khan@exos.systems>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# sum-helpers
|
|
22
|
+
|
|
23
|
+
A modular, strictly-typed Python package providing pure algorithmic solutions for array sum and combination problems.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install sum-helpers
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
- **Pure Functions**: Input collections are never mutated in-place.
|
|
34
|
+
- **Strictly Typed**: Full type annotations (`Sequence[int]`, `tuple[int, ...]`, `int | None`) supporting PEP 561 (`py.typed`).
|
|
35
|
+
- **Comprehensive Algorithms**: Includes two-pointer scans, hash-based lookups, bounding-based pruning, and recursive k-sum decomposition.
|
|
36
|
+
|
|
37
|
+
## Overview of Exported Functions
|
|
38
|
+
|
|
39
|
+
### 1. Two-Element Sums (`sum_helpers.two_sum`)
|
|
40
|
+
- `two_sum(nums, target)`: 0-indexed indices via single-pass hash map ($\mathcal{O}(n)$).
|
|
41
|
+
- `two_sum_sorted(numbers, target)`: 1-indexed two-pointer solution on sorted array ($\mathcal{O}(n)$ time, $\mathcal{O}(1)$ space).
|
|
42
|
+
- `two_sum_less_than_k(nums, k)`: Maximum sum strictly less than $k$ ($\mathcal{O}(n \log n)$).
|
|
43
|
+
- `two_sum_closest(nums, target)`: Pair sum closest to target ($\mathcal{O}(n \log n)$).
|
|
44
|
+
- `two_sum_unique_pairs(nums, target)`: All unique sorted pairs summing to target ($\mathcal{O}(n \log n)$).
|
|
45
|
+
|
|
46
|
+
### 2. Three-Element Sums (`sum_helpers.three_sum`)
|
|
47
|
+
- `three_sum(nums, target=0)`: All unique sorted triplets summing to target ($\mathcal{O}(n^2)$).
|
|
48
|
+
- `three_sum_closest(nums, target)`: Triplet sum closest to target ($\mathcal{O}(n^2)$).
|
|
49
|
+
- `three_sum_smaller(nums, target)`: Count index triplets with sum strictly less than target ($\mathcal{O}(n^2)$).
|
|
50
|
+
|
|
51
|
+
### 3. Triangle Sums (`sum_helpers.triangle`)
|
|
52
|
+
- `valid_triangle_number(nums)`: Count index triplets that can form a valid triangle ($\mathcal{O}(n^2)$).
|
|
53
|
+
- `is_valid_triangle(a, b, c)`: Geometric triangle inequality validator ($\mathcal{O}(1)$).
|
|
54
|
+
- `find_valid_triangles(nums)`: All unique sorted value triplets forming valid triangles ($\mathcal{O}(n^2)$).
|
|
55
|
+
|
|
56
|
+
### 4. Generalized K-Sum & Four Sum (`sum_helpers.k_sum`)
|
|
57
|
+
- `k_sum(nums, target, k)`: Generalized recursive two-pointer k-sum for arbitrary $k \ge 2$ ($\mathcal{O}(n^{k-1})$).
|
|
58
|
+
- `k_sum_closest(nums, target, k)`: Sum of $k$ integers closest to target ($\mathcal{O}(n^{k-1})$).
|
|
59
|
+
- `k_sum_smaller(nums, target, k)`: Count index $k$-tuples with sum strictly less than target ($\mathcal{O}(n^{k-1})$).
|
|
60
|
+
- `four_sum(nums, target=0)`: All unique 4-tuples summing to target ($\mathcal{O}(n^3)$).
|
|
61
|
+
- `four_sum_closest(nums, target)`: Sum of 4 integers closest to target ($\mathcal{O}(n^3)$).
|
|
62
|
+
- `four_sum_smaller(nums, target)`: Count index quadruplets with sum strictly less than target ($\mathcal{O}(n^3)$).
|
|
63
|
+
- `four_sum_ii(nums1, nums2, nums3, nums4)`: Count quadruplets across four separate arrays summing to 0 ($\mathcal{O}(n^2)$).
|
|
64
|
+
|
|
65
|
+
## Quickstart
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from sum_helpers import (
|
|
69
|
+
two_sum,
|
|
70
|
+
two_sum_sorted,
|
|
71
|
+
two_sum_less_than_k,
|
|
72
|
+
two_sum_closest,
|
|
73
|
+
three_sum,
|
|
74
|
+
three_sum_closest,
|
|
75
|
+
three_sum_smaller,
|
|
76
|
+
valid_triangle_number,
|
|
77
|
+
k_sum,
|
|
78
|
+
k_sum_closest,
|
|
79
|
+
k_sum_smaller,
|
|
80
|
+
four_sum,
|
|
81
|
+
four_sum_closest,
|
|
82
|
+
four_sum_smaller,
|
|
83
|
+
four_sum_ii,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# Generalized K-Sum (k=4)
|
|
87
|
+
quadruplets = four_sum([1, 0, -1, 0, -2, 2], target=0)
|
|
88
|
+
assert quadruplets == [
|
|
89
|
+
(-2, -1, 1, 2),
|
|
90
|
+
(-2, 0, 0, 2),
|
|
91
|
+
(-1, 0, 0, 1),
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
# Generalized K-Sum Closest (k=4)
|
|
95
|
+
assert four_sum_closest([1, 0, -1, 0, -2, 2], target=0) == 0
|
|
96
|
+
|
|
97
|
+
# Generalized K-Sum Smaller (k=4)
|
|
98
|
+
assert four_sum_smaller([1, 1, 1, 1], target=5) == 1
|
|
99
|
+
|
|
100
|
+
# Four Sum II across four independent lists
|
|
101
|
+
assert four_sum_ii([1, 2], [-2, -1], [-1, 2], [0, 2]) == 2
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Running Tests
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
uv run pytest -v
|
|
108
|
+
uv run pytest --doctest-modules src/
|
|
109
|
+
uv run --with mypy mypy src/ tests/
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Building for PyPI
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
uv build
|
|
116
|
+
uv publish
|
|
117
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
sum_helpers/__init__.py,sha256=Vu0TGb1NLwwt00VQenPvkkn6uDKKtn3H5YtlSM7jmkA,1711
|
|
2
|
+
sum_helpers/k_sum.py,sha256=NtFGTTOuGN_arMZ3tC9qp1NX2Ng02zt2234VUiHhdWM,13409
|
|
3
|
+
sum_helpers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
sum_helpers/three_sum.py,sha256=2cWpb1XtzJPUnVYCaxzZP_8nc-pT9ANiaSBfzPhkYRc,6355
|
|
5
|
+
sum_helpers/triangle.py,sha256=dX3JZiI0xn3XHHEs2Gv2ozUMYaG3x-fhv4H-CbN1OGg,4971
|
|
6
|
+
sum_helpers/two_sum.py,sha256=TJAycfvhtxBN3pv9ekPBzhja00dnby_sOcNZDwGqDmY,7973
|
|
7
|
+
sum_helpers-0.1.0.dist-info/WHEEL,sha256=3OmCxFA0ffBIsX4x0o8CdfSvZAOvO3mzEG8U_z5TvV4,80
|
|
8
|
+
sum_helpers-0.1.0.dist-info/METADATA,sha256=t85xUNWOc_LqvkQxGW8TkHXLqiNRdh7wupGcuwhI2_w,4498
|
|
9
|
+
sum_helpers-0.1.0.dist-info/RECORD,,
|