Given a list of n integers?(negative and positive), not sorted and duplicates allowed, you have to output the triplets which sum upto 0.
Some rules to base the algorithm on:
* Zeroes dont directly contribute to the sum. So, only matter as the third number when needed in an output triplet.
* For a number n, if there exists a 0 in the list, we need to find a -n and include the 0 to form a triplet. (Question: Not sure if I can count the same 0 multiple times - probably not.). We can use a hash table for this part. O(n) to form the table and O(1) lookups.
* When there's no -n for a specific n, we need to find out -a and -b such that (a+b) = n. In other words, in context of a n, for every a, search for a -(n-b) number. We can use a different hash table for this part. Again, O(n) to form the table and O(1) lookups.
* Overall algorithm is therefore, no worse than O(n) (strictly, O(2n)...), which is nearly the best possible case.
Your third point.. How will you decide a and b..
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks