Sponsored
Sponsored
This approach involves sorting the data first and then using a two-pointer technique. By sorting, we can simplify the problem as the elements will be in order. The two-pointer method then efficiently checks possible solutions by limiting the number of checks needed.
Time complexity is O(n log n)
due to sorting, and space complexity is O(1)
.
1function findPair(arr, sum) {
2 arr.sort((a, b) => a - b);
3 let left = 0, right = arr.length - 1;
4
5 while (left < right) {
6 let current_sum = arr[left] + arr[right];
7
8 if (current_sum === sum) {
9 console.log(`Pair found: (${arr[left]}, ${arr[right]})`);
10 return;
11 } else if (current_sum < sum) {
12 left++;
13 } else {
14 right--;
15 }
16 }
17 console.log("No pair found");
18}
This JavaScript code performs sorting utilizing Array.sort()
. By maneuvering two pointers from respective ends towards the center, it quickly isolates potential pairs whose sum matches the target.
This approach uses a hash table (or dictionary) to keep track of the elements and their complements needed to reach the target sum. By utilizing this lookup, we can reduce the problem to a linear time complexity.
Time complexity is O(n)
assuming uniform distribution of hash function (no collisions), and space complexity is O(n)
.
In this Java implementation, a HashSet
stores elements while checking complements efficiently. Each iteration checks if the complement has already been recorded, leading to quick pair identification.