Find Two Numbers with a Given Sum
Given an unsorted array of integers and a target value, find any pair that adds up to the target.
Return the two indices or report that no such pair exists.
Need a hint?
- Sort the array first.
- Use one pointer at each end and move inward based on the sum.
After sorting, initialise i = 0
, j = n−1
.
While i < j
:
- if
a[i] + a[j] == target
→ done - else move the lower/higher pointer inward.
Overall O(n log n) due to sort (or O(n) if the array is pre-sorted).