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?
- A. Sorting makes all triangles valid.
- B. Each triangle needs the largest side to be the smallest.
- C. The pointers must stay on the same element.
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Why is the inequality test for a non-degenerate triangle with sorted sides written as ai + aj > ak for the largest side ak?
- To count subarrays with sum divisible by m, why does the equal-residue method fail for a subarray count that depends on the MAXIMUM element?
- In the 'longest window with equal numbers of high and low values' problem, what turns the condition into a standard prefix-sum problem?
- When two consecutive windows of length 3 are compared, why does equal sums reduce to a single element comparison?
- Why does a pair (i<j) with A[i] AND A[j] = 0 require disjoint sets of set bits?
- Among pairs with A[i] ≠ A[j] and A[i] XOR A[j] = 0, how many exist?