Let's assume we have a fixed-size array with N
elements. To find a triplet that sums to a given k
value, we must find values at three unique indices that all add up to k
.
For example, given the array [47, 6, 3, 8, 12, 10]
, a triplet that sums to k=28
is (6, 10, 12)
.
A simple solution to the problem is to generate all possible triplets, evaluate the sum of each, and return the triplet that sums to k
. This would require a set of three nested loops, which would generate triplets and evaluate their sum.
This process is visualized below with an example:
However, this naive approach to the problem yields an inefficient solution that takes
A more efficient solution to the problem requires us first to sort the array. Once we sort the array, we need a set of two nested loops.
The outer loop with the i
counter goes to each element from the 0
index to N-3
. The inner loop iterates over each element between i+1
and N-1
, keeping track of the two positions, left_end
and right_end
. These are adjusted as the loop proceeds.
The illustration below demonstrates this process with an example:
This approach takes
The lines highlighted in the code below implement the solution described above in Python and C++.
def findTripletSumToK(arr, N, k):arr.sort() # Sort the array in an ascending orderfor i in range(0, N-2): # Loop through all elements from index 0 to n-3left_end = i + 1 # Set initial left_end for each iteration of this outer loopright_end = N-1 # Set initial right_end for each iteration of this outer loopwhile (1):if(left_end == right_end): # If left_end and right_end become the same, resume with the outer-loopbreakelse:current_triplet = (arr[i] , arr[left_end] , arr[right_end]) # Make an empty tuple to fill with our triplet laterif(sum(current_triplet) == k): # arr[i] + arr[left_end] + arr[right_end] == kreturn current_tripletelif (sum(current_triplet) > k): # arr[i] + arr[left_end] + arr[right_end] > kright_end = right_end - 1elif(sum(current_triplet) < k): # arr[i] + arr[left_end] + arr[right_end] < kleft_end = left_end + 1return ()arr = [47, 6, 3, 8, 12, 10]k = 28N = len(arr)ret = findTripletSumToK(arr, N, k)print("Triplet is:" , ret)
The findTripletSumToK()
function implements the following steps:
We sort arr
in ascending order.
Then, we iterate each element in an array from the 0
index to N-3
.
During each iteration, we set left_end
to i+1
and right_end
to N-1
, where i
is the counter for the loop.
In a nested loop, we adjust left_end
and right_end
until they both become equal, such that:
If the sum of the elements at i
, left_end
, and right_end
is less than k
, then we increment left_end
.
If the sum of the elements at i
, left_end
, and right_end
is greater than k
, then we decrement right_end
.
If the sum of the elements at i
, left_end
, and right_end
is equal to k
, then we return this triplet.
We return the triplet.
Free Resources