
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).
using System.Collections.Generic;
public class PairFinder {
public static void FindPair(int[] arr, int sum) {
HashSet<int> complements = new HashSet<int>();
foreach (var number in arr) {
int complement = sum - number;
if (complements.Contains(complement)) {
Console.WriteLine($"Pair found: ({number}, {complement})");
return;
}
complements.Add(number);
}
Console.WriteLine("No pair found");
}
}C# offers a HashSet class to properly insert elements and check for complements in linear time. This aids in swift detection of pairs without needing to scan through remaining elements unnecessarily.