beginner · hashing · arrays · complement

Two readings that add up to a target

Problem

A sensor log is a list of integer readings in the order they arrived (not sorted). Find two different readings whose sum equals a given target.

Return their positions i < j, or report that none exist. Any valid pair is acceptable.

Constraints

  • 2 ≤ n ≤ 32 (visualization limit)
  • readings and target are integers in the ranges −999…999 and −1998…1998

Examples

readings = [7, 2, 13, 9], target = 11 → [1, 3] — 2 + 9 = 11.

readings = [4, 4], target = 8 → [0, 1]

Show the solution

One pass with a hash map of complements

For position j the partner must equal target − a[j]. A hash map from value to position answers "have I seen it?" in expected O(1).

Why it is correct

When the scan reaches the second position of any valid pair, the first is already in the map, so the pair is found no later than then. Looking up before inserting prevents pairing a reading with itself.

Complexity

Time O(n) expected, extra space O(n). n iterations, each with one expected-O(1) lookup and one expected-O(1) insert. The map holds up to n entries.

For contrast: Check all pairs. That costs O(n²) time and O(1) space.

Edge cases

  • Equal readings ([4, 4], target 8): the first 4 is in the map when the second arrives.
  • A reading equal to half the target appearing once must not pair with itself: lookup happens before insertion.

Common mistakes

  • Inserting before looking up, which pairs a reading with itself.
  • Sorting first and losing the original positions.

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 PairSumUnsorted
{
    /// <summary>Two positions i &lt; j with readings[i] + readings[j] == target, or null. Expected O(n) time, O(n) space.</summary>
    public static (int I, int J)? Find(int[] readings, int target)
    {
        var seen = new Dictionary<int, int>(); // value -> position
        for (int j = 0; j < readings.Length; j++)
        {
            int need = target - readings[j];
            if (seen.TryGetValue(need, out int i))
                return (i, j);
            seen[readings[j]] = j; // after the lookup: never pair a reading with itself
        }
        return null;
    }
}

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

from collections.abc import Sequence
 
 
def find(readings: Sequence[int], target: int) -> tuple[int, int] | None:
    """Two positions i < j with readings[i] + readings[j] == target, or None. Expected O(n) time, O(n) space."""
    seen: dict[int, int] = {}  # value -> position
    for j, reading in enumerate(readings):
        need = target - reading
        if need in seen:
            return seen[need], j
        seen[reading] = j  # after the lookup: never pair a reading with itself
    return None

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

package dev.bekadan.dsa.problems;
 
import java.util.HashMap;
import java.util.Map;
 
public final class PairSumUnsorted {
    private PairSumUnsorted() {
    }
 
    /** Two positions i &lt; j with readings[i] + readings[j] == target, or null. Expected O(n) time, O(n) space. */
    public static int[] find(int[] readings, int target) {
        Map<Integer, Integer> seen = new HashMap<>(); // value -> position
        for (int j = 0; j < readings.length; j++) {
            int need = target - readings[j];
            Integer i = seen.get(need);
            if (i != null) {
                return new int[] {i, j};
            }
            seen.put(readings[j], j); // after the lookup: never pair a reading with itself
        }
        return null;
    }
}

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

#pragma once
 
#include <cstddef>
#include <optional>
#include <span>
#include <unordered_map>
#include <utility>
 
namespace bekadan::dsa::problems {
 
// Two positions i < j with readings[i] + readings[j] == target. Expected O(n) time, O(n) space.
inline std::optional<std::pair<std::size_t, std::size_t>> pair_sum_unsorted(std::span<const int> readings, int target) {
    std::unordered_map<int, std::size_t> seen;  // value -> position
    for (std::size_t j = 0; j < readings.size(); ++j) {
        const int need = target - readings[j];
        if (auto it = seen.find(need); it != seen.end())
            return std::pair{it->second, j};
        seen[readings[j]] = j;  // after the lookup: never pair a reading with itself
    }
    return std::nullopt;
}
 
}  // namespace bekadan::dsa::problems

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