The 2-SUM Problem

From NovaOrdis Knowledge Base
Revision as of 20:29, 16 October 2021 by Ovidiu (talk | contribs) (→‎Overview)
Jump to navigation Jump to search

Internal

Overview

Given as input an input of n numbers, in no particular order, and a target sum t, find all pairs of integers that sum to t.

The naive solution would be to double loop over the array in O(n2) running time.

The better solution (that comes with an extra space requirement, though) is to insert all numbers in a hash table and then do a second pass where for each number we look to see if (t - xi) exists in the table. This is a O(n) solution.