I enrolled in the Algorithms, Part II course on Coursera, and one of the interview questions (ungraded) is as follows:
2-sum. Given an array
a
ofn
64-bit integers and a target valueT
, determine whether there are two distinct integersi
andj
such thata[i] + a[j] = T
. Your algorithm should run in linear time in the worst case.Hint: sort the array in linear time.
I can think of solving it in several ways:
Insert the elements in a hash table in one pass. Then make a 2nd pass, looking for
T - a[i]
in the hash table. Space complexity is O(n) for the hash table, and O(n) for the 2 passes. This solution meets the time requirement stated in the question.Sort the array, and then run 2 pointers
i
andj
from the beginning and the end, respectively, looking fora[i] + a[j] = T
. Ifa[i] + a[j] < T
, incrementi
, else decrementj
. Space complexity is dependent on the sorting algorithm; assuming, Quick Sort, no additional space necessary. Time complexity, nlogn, so it fails the time requirement stated in the question.Considering that the question is given after the Radix Sort lecture, I'm assuming the intent is to use one of the Radix Sorts. Since the question specifies 64-bit integers, using binary representation of
long
, and using In-place MSD radix sort, the array can be sorted in-place in linear time. This seems like the best approach.
Other ideas?
P.S. I've seen this question, but it assumes a sorted array, and all the answers there use some kind of hashing.
I've also seen this question but it seems overly complicated for the specific case of 2-sum.