MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / triplet_sum2

Function triplet_sum2

maths/triplet_sum.py:42–66  ·  view source on GitHub ↗

Returns a triplet in the array with sum equal to target, else (0, 0, 0). >>> triplet_sum2([13, 29, 7, 23, 5], 35) (5, 7, 23) >>> triplet_sum2([37, 9, 19, 50, 44], 65) (9, 19, 37) >>> arr = [6, 47, 27, 1, 15] >>> target = 11 >>> triplet_sum2(arr, target) (0, 0

(arr: list[int], target: int)

Source from the content-addressed store, hash-verified

40
41
42def triplet_sum2(arr: list[int], target: int) -> tuple[int, int, int]:
43 """
44 Returns a triplet in the array with sum equal to target,
45 else (0, 0, 0).
46 >>> triplet_sum2([13, 29, 7, 23, 5], 35)
47 (5, 7, 23)
48 >>> triplet_sum2([37, 9, 19, 50, 44], 65)
49 (9, 19, 37)
50 >>> arr = [6, 47, 27, 1, 15]
51 >>> target = 11
52 >>> triplet_sum2(arr, target)
53 (0, 0, 0)
54 """
55 arr.sort()
56 n = len(arr)
57 for i in range(n - 1):
58 left, right = i + 1, n - 1
59 while left < right:
60 if arr[i] + arr[left] + arr[right] == target:
61 return (arr[i], arr[left], arr[right])
62 elif arr[i] + arr[left] + arr[right] < target:
63 left += 1
64 elif arr[i] + arr[left] + arr[right] > target:
65 right -= 1
66 return (0, 0, 0)
67
68
69def solution_times() -> tuple[float, float]:

Callers

nothing calls this directly

Calls 1

sortMethod · 0.80

Tested by

no test coverage detected