algorithm
data structures
problem solving
coding challenge
pair sum

Given a list of numbers and a number k, return whether any two numbers from the list add up to k

Master System Design with Codemia

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

Given a list of numbers and a number `k`, the challenge is to determine whether any two numbers from the list sum up to `k`. This problem is a common interview question and a fundamental problem in computer science that has applications in various algorithms and systems. In this article, we will delve into multiple approaches to solve this problem, discussing their time complexity, space complexity, and potential trade-offs.

Problem Statement

We are provided with:

  • A list `nums` of integers.
  • An integer `k`.

The task is to find out if there are two distinct numbers in `nums` such that their sum equals `k`.

Approaches

Brute Force Method

The most straightforward approach is to check all possible pairs within the list to see if any pair sums up to `k`. This can be implemented using nested loops.

Algorithm:

  1. Loop through each index `i` in the list.
  2. For each `i`, loop through each index `j` greater than `i`.
  3. Check if `nums[i] + nums[j] == k`.
  4. If such a pair is found, return `True`.
  5. If the loops complete without finding a pair, return `False`.
  • Time Complexity: O(n2)O(n^2), where `n` is the length of `nums`, since we are checking all pairs.
  • Space Complexity: O(1)O(1), no additional space used besides the input.
  • Time Complexity: O(n)O(n), as each element is processed once.
  • Space Complexity: O(n)O(n), for storing elements in the hash map.
    • Calculate `current_sum = nums[left] + nums[right]`.
    • If `current_sum` equals `k`, return `True`.
    • If `current_sum` is less than `k`, increment `left`.
    • If `current_sum` is greater than `k`, decrement `right`.
  • Time Complexity: O(nlogn)O(n \log n), due to the sorting step.
  • Space Complexity: O(1)O(1), if the sort is done in place.
  • Edge Cases: Consider when the list is empty, contains fewer than two numbers, or when all elements are the same and potentially equal to `k/2`.
  • Input Constraints: The choice of approach may depend on constraints such as the range of integer values, list size, and execution environment limitations.

Course illustration
Course illustration

All Rights Reserved.