Find the smallest sum of all indices of unique number pairs summing to a given number in JavaScript

This tutorial shows how to find pairs of numbers in an array that sum to a target value, then return the sum of all indices of these unique pairs.

Problem Description

Given an array of numbers and a target sum, we need to:

  • Find all pairs of numbers that sum to the target
  • Ensure each number is used only once across all pairs
  • Return the sum of indices of all numbers used in valid pairs

Example Walkthrough

For array [1, 4, 2, 3, 0, 5] with target sum 7:

Valid pairs:
4 + 3 = 7 (indices: 1, 3)
5 + 2 = 7 (indices: 5, 2)

Sum of indices: 1 + 3 + 5 + 2 = 11

Solution Implementation

const arr = [1, 4, 2, 3, 0, 5];

const findIndexSum = (arr = [], targetSum = 0) => {
    const used = new Set();
    const validIndices = [];
    
    for (let i = 0; i < arr.length; i++) {
        if (used.has(i)) continue;
        
        for (let j = i + 1; j < arr.length; j++) {
            if (used.has(j)) continue;
            
            if (arr[i] + arr[j] === targetSum) {
                validIndices.push(i, j);
                used.add(i);
                used.add(j);
                break; // Move to next unused element
            }
        }
    }
    
    return validIndices.reduce((sum, index) => sum + index, 0);
};

console.log(findIndexSum(arr, 7));
11

How It Works

The algorithm uses a nested loop approach:

  1. Track used indices: A Set prevents reusing elements in multiple pairs
  2. Find pairs: For each unused element, check all subsequent unused elements
  3. Store valid indices: When a pair sums to target, record both indices
  4. Calculate result: Sum all collected indices

Alternative Optimized Solution

Here's a more efficient approach using a hash map:

const findIndexSumOptimized = (arr = [], targetSum = 0) => {
    const numMap = new Map();
    const used = new Set();
    const validIndices = [];
    
    // Store all numbers with their indices
    arr.forEach((num, index) => {
        if (!numMap.has(num)) {
            numMap.set(num, []);
        }
        numMap.get(num).push(index);
    });
    
    for (let i = 0; i < arr.length; i++) {
        if (used.has(i)) continue;
        
        const complement = targetSum - arr[i];
        const complementIndices = numMap.get(complement) || [];
        
        // Find unused complement index
        const validComplement = complementIndices.find(idx => 
            idx > i && !used.has(idx)
        );
        
        if (validComplement !== undefined) {
            validIndices.push(i, validComplement);
            used.add(i);
            used.add(validComplement);
        }
    }
    
    return validIndices.reduce((sum, index) => sum + index, 0);
};

const testArray = [1, 4, 2, 3, 0, 5];
console.log(findIndexSumOptimized(testArray, 7));
11

Comparison

Approach Time Complexity Space Complexity Readability
Nested Loop O(n²) O(n) Simple
Hash Map O(n) O(n) Moderate

Conclusion

Both solutions correctly find unique pairs summing to the target and return the sum of their indices. The hash map approach offers better time complexity for larger arrays, while the nested loop is more straightforward to understand.

Updated on: 2026-03-15T23:19:00+05:30

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements