Beyond Big O

Pair-sum indices

Pair-sum indices

Easy

Solution guide

Reveal solution guide — spoilers

Approach

  1. Scan right indices from left to right while keeping a map from each previously seen value to its earliest index.
  2. Before inserting the current value, look up target minus that value. If present, return the stored left index and the current right index immediately.
  3. If no match exists, record the current index only when this value has not appeared before. Return an empty list if the scan ends without a pair.

Why it works

When checking right index j, the map contains only positions before j, preventing reuse of one position. Returning at the first matching j minimizes the right index. Retaining the earliest occurrence of each complement also minimizes the left index among pairs with that same right endpoint.

Complexity

Expected O(n) time and O(n) auxiliary space for n values. Do not sort or modify the input; sorting would also lose the required original-position ordering unless additional work restored it.

Edge cases to check

  • Two equal values may form a pair only when they occupy different positions; check before inserting the current position.
  • When duplicates provide several valid left endpoints, keep the earliest rather than overwriting its map entry.
  • Empty/single-value input and no-solution input return an empty list. Negative values and zero use the same complement rule.
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…