JJobsMoi
Amazon
AM

Two Sum

Codingeasy

Problem

You are given an array of integers nums and an integer target. Find the two distinct elements in the array whose values add up exactly to target, and return their indices as a two-element array.

  • Each input is guaranteed to have exactly one valid pair of indices that solves it.
  • You may not use the same element twice — the two indices must be different, even if the array contains a duplicate value that could pair with itself.
  • The indices may be returned in either order.

Examples

Example 1:

Input: nums = [3, 10, 2, 7], target = 9

Output: [2, 3]

Explanation:

nums[2] + nums[3] = 2 + 7 = 9, and no other pair of elements in the array sums to 9.

Example 2:

Input: nums = [5, 5, 11], target = 10

Output: [0, 1]

Explanation:

The two 5s at indices 0 and 1 sum to 10. Even though the values are equal, they occupy different positions, so this pair is valid.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Exactly one valid answer exists for each input.

Solution

Loading editor…

Sign in to get AI feedback on your answer. Your work is saved while you do.

Sign in to evaluate