Given an array of integers and a value, determine if there are any three integers in the array whose sum equals the given value.
Consider this array and the target sums.
Quadratic, O(n2)
Constant, O(1)
In this solution, we first sort the array. Then we fix one element ‘e’, and try to find a pair (a, b) in the remaining array such that required_sum - e = a + b.We start with the first element e in the array (at index i = 0) and try to find such a pair (a, b) in the remaining array (i.e A[i + 1] to A[n - 1]) that satisfies the condition: a+b = required_sum - e. We can find such a pair in linear time. If we find such a pair, we have found the solution: a, b and e and thus, we can stop the iteration.Otherwise, we repeat the above steps for all elements e at index i = 1 to n - 3, until we find a pair that meets the condition.
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!