Data Structures & AlgorithmsHard
Given a sorted array, why is counting triplets with sum < T O(n²) rather than O(n³)?
- A. For each fixed i, the two-pointer sweep over j and k moves monotonically, so each i costs O(n) work.
- B. Sorting makes each triple's sum equal to the average, so the check is constant time.
- C. The number of triples is at most n, so only linear work is needed.
- 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.
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
- Floyd's cycle detection finds the slow and fast pointers meeting inside the loop. How is the START of the loop then found?
- In the greedy patching algorithm, the reachable range is [1..R] and the next sorted value x exceeds R+1. Why is R+1 the right patch?
- A monotonic deque for sliding-window maximum stores array INDICES instead of values. Why?
- When tracking a '' wildcard that may be '(', ')' or empty while scanning brackets, why is it enough to keep a range [lo, hi] of possible…
- Two different strings produced equal rolling-hash values. What does this tell you?
- In iterative reversal of a singly linked list, which pointer must be saved BEFORE the current node's next pointer is changed?