Search code examples
algorithmlanguage-agnostic

How to write an algorithm to check if the sum of any two numbers in an array/list matches a given number?


How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number with a complexity of nlogn?


Solution

  • I'm sure there's a better way, but here's an idea:

    1. Sort array
    2. For every element e in the array, binary search for the complement (sum - e)

    Both these operations are O(n log n).