DSA interview question
A travel site pairs one flight (price list A) with one hotel (price list B) and wants to show the K highest-value combinations A[i] + B[j] across all n² pairs, in non-increasing order. Computing all n² sums is too slow for n = 10⁵. After sorting both arrays in descending order, the best sum is A[0] + B[0], and the next best is always a neighbour of a pair already taken: (i+1, j) or (i, j+1). A max-heap exploring this grid from the top-left corner, with a visited set to avoid duplicates, yields the K best in O(K log K).
Example: A = [1, 4, 2, 3], B = [2, 5, 1, 6], K = 4 → [10, 9, 9, 8].
vector<int> maxCombinations(vector<int> A, vector<int> B, int K); // K <= n * n
Input (A, B, K) | Output | Explanation |
|---|---|---|
([3, 2], [1, 4], 2) | [7, 6] | 3+4, 2+4 |
([1, 4, 2, 3], [2, 5, 1, 6], 4) | [10, 9, 9, 8] | 4+6, 4+5, 3+6, 3+5 |
([1], [1], 1) | [2] | |
([5, 5], [1, 1], 4) | [6, 6, 6, 6] | Equal sums from different pairs all count |
([0, -1], [-2, 3], 3) | [3, 2, -2] |
(Confirm: pairs (i, j) are distinct by index, so equal sums are listed separately; output in non-increasing order.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in