Question d’entretien chez Meta

find 3 elements in an array that sum to 0.

Réponses aux questions d'entretien

Utilisateur anonyme

28 nov. 2012

Richard, The solution using a Hashtable is better, because its time complexity would be O(N^2).

4

Utilisateur anonyme

21 nov. 2012

Thanks for the comment. However, I'm not sure how I am that far off.. If you just replace my hash with an ordered array, then essentially it's the same algorithm. How did I get to n^3 though .. I take it on board that a hash array take longer to construct than an ordered list in which to do a binary search - is that the additional order of magnitude?

2

Utilisateur anonyme

14 nov. 2012

I would construct a hash of all entries in the array and then iterate through a 2d product of all elements in the array and see if that sum was in the hash as first mentioned. Any comments ?

3

Utilisateur anonyme

19 nov. 2012

@Richard no, that's not the way to do it actually. Your naive solution would take a N^3 / 2 complexity. A N^2 lgN complexity can be achieved if you first sort the array. A pair a[i] and a[j] is part of a triple that sums to 0 if and only if the value -(a[i]+ a[j]) is in the array(and not a[i] or a[j]). You need to sort the array, then do N (N - 1)/ 2 binary searches that each take time proportional to log N, for a total running time proportional to N^2 log N. Here's an example in java : http://algs4.cs.princeton.edu/14analysis/ThreeSumFast.java

2

Utilisateur anonyme

3 août 2013

More elegantly, RIchard is correct. Compute the 2sum (N^2/2 +N/2 operations) and store it in a has table (potentially O(1)) or sort the answer (potentiall O(n\lg n)). For each element in the list, look up the negation in this list (O(n) for has tables, O(nlg(n)) for sorted arrays).

Utilisateur anonyme

5 janv. 2013

public void sumIsZero(int[] a){ int n = a.length; for(int i=0; i