Ctrl K

Pair With a Target Sum

Easy
You get an integer array values and an integer goal. Find two different elements whose sum is exactly goal and return their indices (0-based). The input is guaranteed to contain exactly one such pair. You cannot use the same element twice, although two different elements may hold the same value. The indices may be returned in either order. The O(n²) approach is obvious; try to do better.
Example 1
values=[8, -3, 5, 12], goal=2 → [1, 2]

-3 + 5 = 2, and those are the elements at indices 1 and 2.

Example 2
values=[4, 1, 6, 4], goal=8 → [0, 3]

Both 4s are needed, at indices 0 and 3: one element cannot be used twice.

Example 3
values=[0, 7], goal=7 → [0, 1]
Constraints
  • 2 ≤ len(values) ≤ 10⁵
  • -10⁹ ≤ values[i] ≤ 10⁹
  • -10⁹ ≤ goal ≤ 10⁹
  • Exactly one valid pair exists
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Candidate With Most Votes EasyDoes Any Value Repeat EasyRepeat Within Reach EasyThe Lost Ticket EasyValues in Both Lists Easy
loading Python…
Input
values=[8, -3, 5, 12], goal=2
Expected
[1, 2]

Run checks the first 3 tests in your browser. Submit checks all 35 tests on the server, hidden ones included.