algorithm
number sum
list processing
programming
computer science

Algorithm to find which number in a list sum up to a certain number

Master System Design with Codemia

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


Finding numbers in a list that sum up to a certain target value is a common programming problem that can be approached using various algorithms. This problem is prevalent in both software engineering interviews and competitive programming. The challenge lies not only in finding a solution but in finding it efficiently. This article delves into several techniques for solving this problem, ranging from brute force methods to more optimized algorithms.

Problem Statement

Given a list of numbers and a target number, find all unique pairs in the list that sum up to the target number. For example, consider the list `[2, 7, 11, 15]` and a target sum of `9`. The pairs that sum to `9` are `(2, 7)`.

Approaches

1. Brute Force Approach

This is the most straightforward approach, where each element in the list is paired with every other element to check if they sum up to the target. Though easy to implement, it is not the most efficient as its time complexity is O(n2)O(n^2).

Algorithm:

  1. Iterate through each element `i` in the list.
  2. For each element `i`, iterate through each element `j` following `i`.
  3. Check if the sum of `i` and `j` equals the target.
  4. If yes, store this pair.
    • If yes, a pair is found.
    • If no, store the number in the hash map.
    • If the sum of the values at the pointers is equal to the target, store the pair.
    • If the sum is less than the target, move the starting pointer to the right.
    • If the sum is more than the target, move the ending pointer to the left.
  • Handling Duplicates: If the list contains duplicates and only unique pairs are required, consider additional logic to skip over duplicates.
  • Negative Numbers: These approaches work well with negative numbers, as they treat any number as a valid candidate for pairing.
  • Generalization: This problem can be generalized to find three numbers that sum up to a target (3-Sum Problem) or even more.
  • Real-world Applications: This algorithm is beneficial for financial services, such as finding expenses that sum up to a daily budget or multiple transactions that meet a certain total.

Course illustration
Course illustration

All Rights Reserved.