Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Given an unsorted array of n ≤ 10⁵ integers and a target, report whether two different positions hold values summing to the target. Which approach is optimal in time while passing comfortably?

  1. A. Check every pair with two nested loops – O(n²)
  2. B. Sort, then binary search each element's complement – O(n²)
  3. C. One pass with a hash set of values seen so far – O(n) average time, O(n) space
  4. D. Build a prefix-sum array and look for the target in it – O(n)

Correct answer: C. One pass with a hash set of values seen so far – O(n) average time, O(n) space

Storing each value in a hash set and checking target − x before inserting x finds a pair in a single O(n) pass. Sorting plus binary search is O(n log n), not O(n²), and still slower than hashing; nested loops are 5 × 10⁹ steps at n = 10⁵. Prefix sums find contiguous sums, not arbitrary pairs.

More Coding Interview Problems questions

Exams that ask this topic