Sum of Three Values
Explore algorithms to check if three numbers in an array sum to a specific target. Understand naive and optimized approaches with their time and space complexities, including sorting with two pointers and hashing methods.
Statement
Given an array of integers and an integer value, determine if there are any three integers in the array whose sum equals the given value. Return true if three such integers from the array are found. Otherwise, return false.
Example
Consider this array and the target sums:
Sample input
([3, 7, 1, 2, 8, 4, 5], 20)
Expected output
true
Try it yourself
Solution 1
The simple and naive solution is to have three nested loops iterate over all unordered triples to see if their sum is equal to the given integer or not. Although this works, it’s not efficient.
There exist other solutions with much better time complexities. We’ll look at them later in this lesson.
Time complexity
The time complexity of this solution is cubic, ...