
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).
1def find_pair(arr, target_sum):
2 arr.sort()
3 left, right = 0, len(arr) - 1
4
5 while left < right:
6 current_sum = arr[left] + arr[right]
7
8 if current_sum == target_sum:
9 return f"Pair found: ({arr[left]}, {arr[right]})"
10 elif current_sum < target_sum:
11 left += 1
12 else:
13 right -= 1
14 return "No pair found"Python's built-in sort() method sorts the array. With two pointers, we can efficiently search towards the middle, combining elements to find the correct sum.
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.