beginner · two pointers · sorted array · arrays

Two prices that fit the budget exactly

Problem

A shop lists item prices in ascending order. A customer wants to buy exactly two different items whose prices add up to their budget, to the cent.

Return the positions (0-based) of two such items, smaller position first, or report that no pair exists. If several pairs work, any one is acceptable.

Constraints

  • 2 ≤ n ≤ 32 (visualization limit; the method works for any n)
  • prices are integers from −999 to 999, sorted ascending (duplicates allowed)
  • the budget is an integer from −1998 to 1998

Examples

prices = [3, 8, 11, 15, 22], budget = 26 → [2, 3] — 11 + 15 = 26.

prices = [1, 2, 4], budget = 10 → no pair — The largest possible sum is 2 + 4 = 6.

Show the solution

Two pointers from both ends

With left at the cheapest and right at the most expensive remaining item, a sum that is too small means a[left] is too small to pair with anything left (a[right] is already the largest partner), so left can be discarded. Symmetrically for a sum that is too large.

Why it is correct

Invariant: if a valid pair exists, one exists with both indices in [left, right]. Each move discards one index that cannot be part of any pair inside the range, so the invariant holds; the loop stops when the pair is found or the range is too small to hold two items.

Complexity

Time O(n), extra space O(1). Each iteration moves left or right one step toward each other, and they start n − 1 apart: at most n − 1 iterations, each O(1).

For contrast: Try every pair i < j. That costs O(n²) time and O(1) space.

Edge cases

  • No pair: the pointers meet and the result is "no pair".
  • Duplicates such as [5, 5] with budget 10: the two pointers are different positions, so the pair is valid.
  • Negative prices work unchanged: only the order matters.

Common mistakes

  • Using left <= right, which can pair an item with itself.
  • Moving both pointers at once and skipping a valid pair.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class PairSumSorted
{
    /// <summary>Two positions i &lt; j with prices[i] + prices[j] == budget in an ascending array, or null. O(n), O(1) space.</summary>
    public static (int I, int J)? Find(int[] prices, int budget)
    {
        int left = 0, right = prices.Length - 1;
        while (left < right)
        {
            int sum = prices[left] + prices[right];
            if (sum == budget)
                return (left, right);
            if (sum < budget)
                left++;  // prices[left] is too small for any remaining partner
            else
                right--; // prices[right] is too large for any remaining partner
        }
        return null;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/PairSumSorted.cs

from collections.abc import Sequence
 
 
def find(prices: Sequence[int], budget: int) -> tuple[int, int] | None:
    """Two positions i < j with prices[i] + prices[j] == budget in an ascending list, or None. O(n), O(1) space."""
    left, right = 0, len(prices) - 1
    while left < right:
        total = prices[left] + prices[right]
        if total == budget:
            return left, right
        if total < budget:
            left += 1  # prices[left] is too small for any remaining partner
        else:
            right -= 1  # prices[right] is too large for any remaining partner
    return None

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/pair_sum_sorted.py

package dev.bekadan.dsa.problems;
 
public final class PairSumSorted {
    private PairSumSorted() {
    }
 
    /** Two positions i &lt; j with prices[i] + prices[j] == budget in an ascending array, or null. O(n), O(1) space. */
    public static int[] find(int[] prices, int budget) {
        int left = 0, right = prices.length - 1;
        while (left < right) {
            int sum = prices[left] + prices[right];
            if (sum == budget) {
                return new int[] {left, right};
            }
            if (sum < budget) {
                left++; // prices[left] is too small for any remaining partner
            } else {
                right--; // prices[right] is too large for any remaining partner
            }
        }
        return null;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/PairSumSorted.java

#pragma once
 
#include <cstddef>
#include <optional>
#include <span>
#include <utility>
 
namespace bekadan::dsa::problems {
 
// Two positions i < j with prices[i] + prices[j] == budget in an ascending span. O(n), O(1) space.
inline std::optional<std::pair<std::size_t, std::size_t>> pair_sum_sorted(std::span<const int> prices, int budget) {
    if (prices.size() < 2) return std::nullopt;
    std::size_t left = 0, right = prices.size() - 1;
    while (left < right) {
        const int sum = prices[left] + prices[right];
        if (sum == budget)
            return std::pair{left, right};
        if (sum < budget)
            ++left;  // prices[left] is too small for any remaining partner
        else
            --right;  // prices[right] is too large for any remaining partner
    }
    return std::nullopt;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/pair_sum_sorted.hpp