easyHashingPattern: Two Sum / Hash Set
Distinct Pair Sum Checker Solution
Problem Statement
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
Example 1:
Input:{"package_weights":[1,2,3,4],"target_weight":5}
Output:YES
Explanation: Packages of weights 1 and 4 or 2 and 3 can be paired to match the target weight of 5
Example 2:
Input:{"package_weights":[1,2,3],"target_weight":10}
Output:NO
Explanation: No distinct package pairs can be found to match the target weight of 10
Constraints
- 2 <= n <= 10^5
- 1 <= arr[i] <= 10^9
Time: O(N) Space: O(N)
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).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
