FastPrepTwo Sum

Two Sum

BNSF Railway logoBNSF Railway● EasyFULLTIMEPHONE SCREEN

Problem statement

You are given an integer array nums and an integer target. Find the two numbers in nums whose sum is target and return their indices.

  • The two numbers must come from different indices. The same value may appear at two indices, and those two indices can form the answer.
  • Exactly one pair of indices works.
  • Return the two zero-based indices as [i, j] with i < j.

Function

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

Examples

Example 1

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

Only 1 + 6 equals 7. Those numbers are at indices 2 and 3, so the answer is [2,3].

Example 2

nums = [5,1,5]target = 10return = [0,2]

The two 5s add up to 10. They are at indices 0 and 2. Equal numbers are fine as long as they come from different indices.

Example 3

nums = [-3,8,2,-1]target = -4return = [0,3]

-3 + (-1) = -4. These numbers are at indices 0 and 3, and the smaller index comes first.

Constraints

  • 2 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6
  • -10^6 <= target <= 10^6
  • Exactly one pair of different indices i < j has nums[i] + nums[j] == target.

More BNSF Railway problems

See BNSF Railway hiring insights
Saved
public int[] twoSum(int[] nums, int target) {
    // Write your code here.
}
Checking account…