algorithm
data structures
arrays
k sums
problem solving

Find the top k sums of two sorted arrays

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Finding the top `k` sums of two sorted arrays is a classic problem in computer science and competitive programming. The problem involves two sorted arrays from which we construct a new sorted dataset of sums of elements, one from each array, and then efficiently identify the top `k` sums. This article delves into the technical aspects of this task, outlining different approaches to solving it, while discussing their complexity and providing a concrete example.

Problem Definition

Given two sorted arrays `A` and `B` of sizes `m` and `n` respectively, the task is to find the top `k` sums formed by adding an element from `A` to an element from `B`.

Example:

Consider the arrays:

  • `A = [1, 2, 3]`
  • `B = [4, 5, 6]`

If `k = 3`, the top k sums would be `9, 8, and 8` (i.e., the pairings `(3+6, 3+5, 2+6)`).

Approaches

1. Naïve Approach

Description:

  • Generate all possible sums from both arrays.
  • Sort the resulting sums.
  • Extract the largest `k` sums.

Complexity:

  • Time Complexity: O(m×nlog(m×n))O(m \times n \log(m \times n)), as generating all combinations takes O(m×n)O(m \times n) and sorting them requires an additional logarithmic factor.
  • Space Complexity: O(m×n)O(m \times n) for storing all sums.

2. Min-Heap Approach

Description:

  • Utilize a min-heap to efficiently track the largest sums.
  • Initially, push the largest element possible from each array combination into the heap.
  • Extract the maximum, push the next possible candidate from the arrays, and repeat until `k` sums are extracted.

Technical Explanation:

  • Initialize a min-heap (priority queue) to keep track of the combinations.
  • Start by pushing pairs `(A[i], B[n-1], i, n-1)` for each `i` in `0` to `k-1`, only if `k` does not exceed `m`.
  • Pop the heap's top, which holds the current maximum sum, and insert new pairs by decrementing the second array index.
  • If `(i,j)` is the index used at the top of heap, push `(A[i]+B[j-1], i, j-1)` if `j > 0`.

Complexity:

  • Time Complexity: O(klogk)O(k \log k), where push and pop operations occur `k` times on the heap.
  • Space Complexity: O(k)O(k) to maintain the heap.

Example Walkthrough

Consider `A = [1, 3, 5]` and `B = [2, 4, 6]` with `k = 4`.

Heap Initialization:

  • Start with the combinations: `(5, 6)`, `(3, 6)`, `(1, 6)`.
  • Insert sums: `11, 9, 7` with indices `(2, 2)`, `(1, 2)`, `(0, 2)` into the heap.

Steps:

  1. Extract: `(5, 6)`, Total = 11 (indices `2,2`).
  2. Push Next Candidate: `(5, 4)`, Total = 9 (indices `2, 1`).
  3. Extract: `(3, 6)`, Total = 9 (indices `1,2`).
  4. Push Next Candidate: `(3, 4)`, Total = 7 (indices `1, 1`).
  5. Extract: `(5, 4)`, Total = 9 (indices `2,1`).
  6. Push Next Candidate: `(5, 2)`, Total = 7 (indices `2, 0`).
  7. …and so on until `k` sums are extracted.

Final Top `k` sums:

  • `[11, 9, 9, 8]`

Analysis Table

ApproachTime ComplexitySpace ComplexityProsCons
NaiveO(m×nlog(m×n))O(m \times n \log(m \times n))O(m×n)O(m \times n)Simple and straightforward.Inefficient for large m and n.
Min-HeapO(klogk)O(k \log k)O(k)O(k)Handles large inputs efficientlyMore complex implementation.

Additional Details

Edge Cases

  1. Small `k`: When `k` is smaller than the sizes of both arrays, using a heap offers clear time savings.
  2. Large Arrays: The heap approach scales well with large arrays, where a complete sort of all sums is impractical or infeasible due to time and space constraints.
  3. Equal Elements: Handling situations where elements in either array are equals and their sums appear several times within the top results.

Conclusion

The problem of finding the top `k` sums from two sorted arrays offers significant insight into efficiency and optimization strategies. While the naive approach is intuitive, leveraging a priority queue can dramatically improve performance, especially in scenarios involving large datasets. Understanding and selecting the right approach based on problem constraints is vital for efficient problem-solving.


Course illustration
Course illustration

All Rights Reserved.