Menu
CoddyTech

Two Sum

EasyHashingpython iconjava iconcpp iconc iconjs icon+10

You get a list of whole numbers and a goal value. Exactly two numbers in the list add up to the goal, and your job is to report where they sit.

Take nums = [3, 8, 12, 5] and target = 17. The value 12 is at index 2 and 5 is at index 3, and 12 + 5 = 17, so the answer is [2, 3].

The two numbers must come from two different positions. In [4, 2, 6] with target = 8, using the 4 twice is not allowed; the answer is [1, 2] because 2 + 6 = 8. The same value may appear twice, though: in [7, 3, 7] with target = 14 the answer is [0, 2].

Write a function named twoSum that gets an array of integers nums and an integer target, and returns an array of two indices [i, j] such that nums[i] + nums[j] equals target.

The indices must be two different positions, returned in increasing order (i smaller than j). Every input has exactly one such pair.

Constraints: 2 ≤ nums.length ≤ 10^4, -10^9 ≤ nums[i] ≤ 10^9, -10^9 ≤ target ≤ 10^9.

Function

twoSum(arg1: integer-array, arg2: integer) → integer-array
arg1integer-array
arg2integer
Returnsinteger-array

Examples

Input
arg1 = [3, 8, 12, 5]arg2 = 17
Output
[2, 3]

lock icon+13 hidden tests on Submit

Reset code
def twoSum(nums, target):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

arg1 = [3, 8, 12, 5]
arg2 = 17

Expected

[2, 3]