Distinct Pair Sum Checker — Problem Statement & Solution Guide
Problem Description
Given an array of integers numbers and a target sum targetSum, determine if any two distinct elements in the array can be paired to match the targetSum. Return 'YES' if such a pair exists, and 'NO' otherwise.
Examples
Input
[1, 2, 3, 4, 5], 7
Output
YES
Explanation: Step-by-step: with input [1, 2, 3, 4, 5] and target sum 7, we can pair 2 and 5 to get 7, so the output is 'YES'
Input
[1, 1, 1, 1], 2
Output
YES
Explanation: Step-by-step: with input [1, 1, 1, 1] and target sum 2, we can pair any two distinct 1's to get 2, so the output is 'YES'
Constraints
- 2 <= n <= 10^5
- 1 <= arr[i] <= 10^9
Optimal Approach & Strategy
Use a HashSet. Iterate through the array, for each element check if (target - element) is in the set. If yes, return YES. Otherwise, add the element to the set. Time: O(N), Space: O(N).
Brute Force Approach
Use two nested loops to check every pair. Time: O(N^2), Space: O(1).
Verified Code Solutions
function solution(numbers, targetSum) {
let numSet = new Set();
for (let num of numbers) {
if (numSet.has(targetSum - num)) {
return 'YES';
}
numSet.add(num);
}
return 'NO';
}class Solution {
public:
string solution(vector<int>& numbers, int targetSum) {
unordered_set<int> numSet;
for (int num : numbers) {
if (numSet.find(targetSum - num) != numSet.end()) {
return "YES";
}
numSet.insert(num);
}
return "NO";
}
};import java.util.HashSet;
import java.util.Set;
class Solution {
public String solution(int[] numbers, int targetSum) {
Set<Integer> numSet = new HashSet<>();
for (int num : numbers) {
if (numSet.contains(targetSum - num)) {
return "YES";
}
numSet.add(num);
}
return "NO";
}
}def solution(numbers, targetSum):
numSet = set()
for num in numbers:
if targetSum - num in numSet:
return 'YES'
numSet.add(num)
return 'NO'function solution(numbers, targetSum) {
let numSet = new Set();
for (let num of numbers) {
if (numSet.has(targetSum - num)) {
return 'YES';
}
numSet.add(num);
}
return 'NO';
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.