Data Structures & AlgorithmsVery hardCodeforces Div2 B-D · ICPC regional
An array has 10^5 values and you need the k-th smallest value among all pair sums a[i] + a[j] with i < j. Which approach is the right fit?
- A. Binary search on the answer with a two-pointer count of pairs whose sum is at most the candidate, after sorting
- B. Sort all pair sums explicitly, since n^2 pairs fit in memory
- C. Dijkstra over index pairs, treating each pair as a graph node
- D. Segment tree over the array values, updating one pair per query
Correct answer: A. Binary search on the answer with a two-pointer count of pairs whose sum is at most the candidate, after sorting
Sorting the array lets a two-pointer scan count pairs with sum at most x in O(n), so binary search over x finds the k-th sum in O(n log(range)). Materialising n^2 sums is too large.
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
- From [4, 9, 2, 7, 5, 1] you may pick any elements (each at most once). What is the minimum number of picks so that the picked sum is at…
- How many index triples i < j < k in [-2, -1, 0, 1, 2, 3] have a sum of exactly 0?
- How many contiguous subarrays of [1, 2, 3, 4] have a sum that is a perfect square?
- A string "cdeab" is rotated left by some number of steps k (0 <= k < 5) to become "abcde". What is the smallest such k?
- What is the sum of the maximum over all contiguous subarrays of [3, 1, 2, 4]?
- How many contiguous subarrays of [2, 1, 3, 4, 2] have a sum in the inclusive range [5, 7]?