FastPrepTwo Sum

Two Sum

Amazon logoAmazon● EasyFULLTIMENEW GRADPHONE SCREEN
Learn

Problem statement

Given an integer array nums and an integer target, find two distinct indices whose values add to target.

Return a two-element array [i, j], where 0 <= i < j < nums.length and nums[i] + nums[j] = target. At least one valid pair exists. If several pairs are valid, return the lexicographically smallest pair: minimize i first, then j.

Function

twoSum(nums: int[], target: int) → int[]

Examples

Example 1

nums = [2,7,11,15]target = 9return = [0,1]

nums[0] + nums[1] = 2 + 7 = 9.

Example 2

nums = [3,2,4]target = 6return = [1,2]

nums[1] + nums[2] = 2 + 4 = 6.

Example 3

nums = [3,3]target = 6return = [0,1]

The two equal values occupy distinct indices and form the required pair.

Constraints

  • 2 <= nums.length <= 100000.
  • -10^9 <= nums[i] <= 10^9.
  • -10^9 <= target <= 10^9.
  • At least one valid pair exists.

More Amazon problems

See Amazon hiring insights
public int[] twoSum(int[] nums, int target) {
    // write your code here
}
nums[2,7,11,15]
target9
expected[0,1]
Checking account…