Problem 391925 · easy · Level 03 Linear Management & Searching

Two Entries That Explain the Gap

two pointers · arrays

A hash map can find two numbers with a given sum in one pass. When the input is sorted, there is an even leaner approach that uses two indices and no extra memory.

A bookkeeper's ledger is out by exactly target, and she knows two entries together cause it. The adjustments are in numbers, sorted in non-decreasing order (some may be negative). Return the 0-based indices [i, j], with i < j, of the two entries whose sum is target. Every input has exactly one such pair.

Examples

Input:  numbers = [4, 6, 9, 13, 18], target = 15
Output: [1, 2]
Explanation: 6 + 9 == 15
Input:  numbers = [2, 5, 8], target = 10
Output: [0, 2]

Constraints

  • 2 <= len(numbers) <= 10**4
  • Exactly one valid pair exists.
  • Aim for O(n) time and O(1) extra space (no hash map needed).

Goals

  • Start pointers at opposite ends and move them towards each other
  • Use the sorted order to decide which pointer to move
  • Solve a pair-finding problem in O(n) time and O(1) extra space
Starting Python…