Data Structures & AlgorithmsHard

Given a sorted array, why is counting triplets with sum < T O(n²) rather than O(n³)?

  1. A. For each fixed i, the two-pointer sweep over j and k moves monotonically, so each i costs O(n) work.
  2. B. Sorting makes each triple's sum equal to the average, so the check is constant time.
  3. C. The number of triples is at most n, so only linear work is needed.
  4. D. Each element is compared only with its immediate neighbour, so the work is linear.

Correct answer: A. For each fixed i, the two-pointer sweep over j and k moves monotonically, so each i costs O(n) work.

After fixing the smallest index, a sorted array lets one pointer move up and the other down, so the inner search is linear in n. That gives n · n = n² operations in total.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic