Three Sum Problem
- Shreyas Naphad
- Jun 4, 2024
- 1 min read
Updated: Jun 6, 2024
In this article, we will be solving another common problem on the array which is the 3 sum problem. Here, we are given an array of N integers and a target integer. We aim to find three elements in the array whose sum equals the target.
Example:
N = 7
Arr = [12, -1, 2, -3, 1, 0, 6]
Target = 2
Output: Yes
-1 + 2 + 1 = 2
Solution:
Explanation:
Our task is to find three numbers in the array whose sum equals to our given target.
We have used an unordered map to store the elements as we traverse through the array.
For each pair of elements, we calculate the difference between the target and the current element needed to reach the target sum.
If the difference is found in the map, it shows that the three numbers sum up to the target is already present, and we return true.
If no such three numbers are found, then we return false.
Time Complexity: O(N)
Space Complexity: O(N)
Comments