Algorithm
Array
Pair Sum
Problem Solving
Coding Interview

find pair of numbers in array that add to given sum

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Finding a pair of numbers in an array that sums to a given number is a classic problem in computer science and programming. This problem can be encountered in numerous applications such as financial calculations, game mechanics, and data analytics. The task is to identify two distinct numbers within an array that add up to a specific target value. This article will explore multiple approaches to solving this problem, ranging from brute force to optimized algorithms.

Problem Statement

Given an array of integers and a target sum, find all pairs of numbers that add up to the target sum. Assume each input would have exactly one solution, and the same element cannot be used twice. Note that the pair should be counted only once, not in both orders.

Approaches

1. Brute Force Approach

Description

The simplest approach is to use two nested loops to check every possible pair of numbers in the array to determine if their sum matches the target.

Algorithm

  1. Initialize two loops: an outer loop to pick the first element and an inner loop to pick the second.
  2. For each pair of elements, check if their sum matches the target sum.
  3. Return the pair when a match is found.

Implementation (Python)

  • If it exists, return the pair.
  • Otherwise, add the current element to the hash map.
  • Calculate the sum of the elements at both pointers.
  • If the sum matches the target, return the pair.
  • If the sum is less than the target, increment the left pointer.
  • If the sum is greater than the target, decrement the right pointer.
  • Multiple pairs: Modify the approach to return all unique pairs that add up to the target sum. This is slightly more complicated and involves storing pairs already found and ensuring they're unique.
  • Closest Sum: Instead of finding a precise target sum, find pairs whose sum is closest to a given number. This often requires additional logic during the two-pointer method.

Course illustration
Course illustration

All Rights Reserved.