Data Structures & AlgorithmsHard

When counting triangles from sorted stick lengths with a two-pointer scan, why does fixing the largest side k and moving the pointers i < j work?

  1. A. Sorting makes all triangles valid.
  2. B. Each triangle needs the largest side to be the smallest.
  3. C. The pointers must stay on the same element.
  4. D. For a fixed k, the valid pairs with i < j satisfy a_i + a_j > a_k, and moving pointers in a sorted array counts all valid i in linear time.

Correct answer: D. For a fixed k, the valid pairs with i < j satisfy a_i + a_j > a_k, and moving pointers in a sorted array counts all valid i in linear time.

After sorting, the sum a_i + a_j grows monotonically as j increases for fixed i, so one scan counts all valid partners. Overall the method runs in O(n²) time.

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

Exams that ask this topic