BackeasyHashingInfosys

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.

Example 1
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'

Example 2
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
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Distinct Pair Sum Checker — Problem Statement & Solution Guide

HashingEasyTwo Sum / Hash Set
TimeO(n)
|
SpaceO(n)

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

Example 1

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'

Example 2

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

JavaScript Solution
Time: O(n)
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

Infosys

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.