algorithm
sorted array
pair sums
computational complexity
data structures

Given a sorted array, can we build a sorted array of the sums of all pairs in On2?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

The problem of generating a sorted array of the sums of all pairs from a given sorted array is intriguing both from a theoretical and practical standpoint. In computer science, understanding the complexity and feasibility of such operations can have significant implications on performance and optimization.

Understanding the Problem

Given a sorted array `A` of size `n`, the task is to compute a new sorted array `S` that consists of the sums of all possible pairs `(A[i], A[j])` where `0 ≤ i < j < n`. The challenge is to achieve this in O(n2)O(n^2) time complexity.

Approach to the Solution

Naive Method

A straightforward approach to solve this problem would be to:

  1. Initialize an empty list `S`.
  2. Iterate over all pairs `(i, j)` with `i < j` and add the sum `A[i] + A[j]` to `S`.
  3. Sort the list `S`.

While easy to implement, this method does not perform in O(n2)O(n^2) time since sorting the sums after computing them could increase the time complexity to O(n2logn)O(n^2 \log n), especially when using typical comparison-based sorting algorithms.

Optimized Approach

To ensure we stick to O(n2)O(n^2), leveraging the properties of the sorted array `A` is crucial. Note the following observations:

  1. Pair Sums and Sortedness: Since the array `A` is sorted, the smallest sum is `A[0] + A[1]` and the largest is `A[n-2] + A[n-1]`. Any mid-range sum will be naturally bounded by these extremes.
  2. Two-Pointer Technique: Given that `A` is sorted, using the two-pointer technique can help in efficiently generating sums within possible bounds:
    • Start with one pointer `i` at the beginning of the array and another pointer `j` at the next index (`i + 1`).
    • Calculate sums `A[i] + A[j]`, adjust pointers based on desired conditions, and move through possible combinations.

This technique ensures that each sum is generated in O(1)O(1) time, and iterating over all pairs happens within the O(n2)O(n^2) bounds naturally.

Here is a pseudo-code snippet of the above approach:


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms