Skip to main content

Pair Index Locator

easy
ArrayHash TableHashmap Lookup
Asked atAmazonGoogleMicrosoftMeta

Problem Description

Given an array of integers `values` and an integer `goalSum`, return the indices of the two distinct elements that add up to `goalSum`.

You may assume that exactly one valid solution exists, and you may not use the same element twice.

Return the answer as an array of two indices in any order.

**Example 1:**
```
Input: values = [3, 7, 2, 11, 5], goalSum = 9
Output: [0, 3] (or [3, 0])
Explanation: values[0] + values[3] = 3 + 11 = 14? No — values[0] + values[4] = 3 + 5 = 8? No — values[1] + values[4] = 7 + 2? No — values[1] + values[2] = 7 + 2 = 9. Output: [1, 2]
```
Wait, let's re-check: values[1]=7, values[2]=2 → 7+2=9 ✓

**Example 1:**
```
Input: values = [3, 7, 2, 11, 5], goalSum = 9
Output: [1, 2]
Explanation: values[1] + values[2] = 7 + 2 = 9.
```

**Example 2:**
```
Input: values = [10, 4, 6, 13, 1], goalSum = 7
Output: [1, 2]
Explanation: values[1] + values[2] = 4 + 6 = 10? No — values[1]+values[4] = 4+1=5? No — values[2]+values[4] = 6+1=7 ✓. Output: [2, 4]
```

**Example 2:**
```
Input: values = [10, 4, 6, 13, 1], goalSum = 7
Output: [2, 4]
Explanation: values[2] + values[4] = 6 + 1 = 7.
```

Constraints

  • 2 <= values.length <= 10^4
  • -10^9 <= values[i] <= 10^9
  • -10^9 <= goalSum <= 10^9
  • Exactly one valid solution exists.

Follow-up

Can you solve this using O(1) extra space if the input array is sorted? (Hint: two-pointer approach.)

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.