📖
Coding interview questions
  • 👋Coding Interview
  • Easy
    • Two number sum
    • Validate Subsequence
    • Sorted Squared Array
    • Tournament Winner
    • Non-Constructible Change
    • Find Closest Value in BTS
    • Branch sum
    • Node Depths
    • Depth-first Search
    • Minimum Waiting Time
    • Class Photos
  • Medium
    • Three Number Sum
    • Smallest Difference
    • Move Element To End
    • Monotonic Array
    • Spiral Traverse
    • Longest Peak
    • Array Of Products
    • First Duplicate Value
    • Merge Overlapping Intervals
    • Zero Sum Subarray
    • BST Traversal
    • Validate BST
    • Min Height BST
    • Find Kth Largest Value In BST
    • Reconstruct BST
    • Invert Binary Tree
  • Hard
    • Three Number Sum
  • Really-Hard
    • Three Number Sum
Powered by GitBook
On this page
  1. Easy

Two number sum

Two Number Sum

Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If no two numbers sum up to the target sum, the function should return an empty array.

Note that the target sum has to be obtained by summing two different integers in the array; you can't add a single integer to itself in order to obtain the target sum.

You can assume that there will be at most one pair of numbers summing up to the target sum.

Sample Input

array = [3, 5, -4, 8, 11, 1, -1, 6]
targetSum = 10

Sample Output

[-1, 11] // the numbers could be in reverse order
// O(n^2) time | O(1) space
function twoNumberSum(array, targetSum) {
  for (let i = 0; i < array.length - 1; i++) {
    const firstNum = array[i];
    for (let j = i + 1; j < array.length; j++) {
      const secondNum = array[j];
      if (firstNum + secondNum === targetSum) {
        return [firstNum, secondNum];
      }
    }
  }
  return []
}
// O(n) time | O(n) space
function twoNumberSum(array, targetSum) {
  const nums = {};
  for (const num of array) {
    const match = targetSum - num;
    if (match in nums) {
      return [match, num];
    } else {
      nums[num] = true;
    }
  }
  return [];
}
// O(nlog(n)) time | O(1) space
function twoNumberSum(array, targetSum) {
  array.sort((a, b) => a - b);
  let left = 0;
  let right = array.length - 1;
  while (left < right) {
    const currentSum = array[left] + array[right];
    if (currentSum === targetSum) {
      return [array[left], array[right]]
    } else if (currentSum < targetSum) {
      left++;
    } else if (currentSum > targetSum) {
      right--;
    }
  }
  return [];
}

PreviousCoding InterviewNextValidate Subsequence

Last updated 2 years ago

Page cover image