Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Three Sum (find all triplets summing to zero) is commonly solved by sorting the array and then applying two pointers for each fixed first element. What is the overall time complexity?

  1. A. O(n^2): O(n log n) to sort plus O(n) two-pointer scan for each of the n choices of the first element
  2. B. O(n^3), trying every triplet directly
  3. C. O(n), using a single hash set
  4. D. O(n log n), same as sorting alone

Correct answer: A. O(n^2): O(n log n) to sort plus O(n) two-pointer scan for each of the n choices of the first element

After an O(n log n) sort, fixing each of the n elements as the smallest of the triplet and two-pointering the rest in O(n) gives O(n) * n = O(n^2) dominating the sort, so O(n^2) overall.

More Coding Interview Problems questions

Exams that ask this topic