Back to blog

2026-06-23

Two Sum Problem

Given an array of ints and a target value, check if there exists a pair whose sum equals the target

Solution

 Create a unique set to store the elements as you loop through. As you iterate through the loop of the array values, calculate the complement of the target minus the current value. Then refer to the unique set to set if the complement exists within it. If it does, return true, otherwise add the current value to the unqiue set and continue until it is found or isn't.

function twoSum(arr, target) {

    // Create a Set to store the elements
    let set = new Set();

    for (let num of arr) {
    
        // Calculate the complement that added to
        // num, equals the target
        let complement = target - num;

        // Check if the complement exists in the set
        if (set.has(complement)) {
            return true;
        }

        // Add the current element to the set
        set.add(num);
    }
    // If no pair is found
    return false;
}

// Driver Code
let arr = [0, -1, 2, -3, 1];
let target = -2;

if (twoSum(arr, target))
    console.log("true");
else 
    console.log("false");