Find Pair With Given Sum in an Array
Explore how to solve the problem of finding two numbers in an array that add up to a specific value. Understand two approaches: one using hashing for both sorted and unsorted arrays, and another leveraging a two-pointer technique for sorted arrays. Gain insights on time and space complexity to prepare effectively for coding interviews.
Statement
We’re given an array of integers and a value. Determine if there are any two integers in the array whose sum is equal to the given value. Return true if the sum exists; otherwise, return false.
Example
Consider this array and the target sums:
Sample input
This challenge covers both sorted and unsorted arrays.
[5, 7, 1, 2, 8, 4, 3]
val = 3
Expected output
True
Try it yourself
The test cases include both sorted and unsorted arrays.
Solution 1
In this solution, we’ll use the following algorithm to find a pair that adds to the target (say val).
- Scan the whole array once and store visited elements in a hash set.
- During the scan, for every element
ein the array, we check ifval-eis present in the hash set. In other words, we check ifval-ewas already visited.