Skip to content
CodeKruPro

Two sum

Coding problemEasy

Given a list of integers nums and a target, find the two different positions whose values add up to target. Return the two positions (counting from 0), smaller position first.

Every test has exactly one such pair. The same position cannot be used twice, but two positions may hold equal values. The largest hidden tests have 300,000 values, so checking every pair is too slow.

Examples

Example 1
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Example 2
Input: nums = [3,2,4], target = 6
Output: [1,2]
Position 0 holds 3, but it cannot be used twice.
Example 3
Input: nums = [3,3], target = 6
Output: [0,1]

Constraints

  • The list holds between 2 and 300,000 integers
  • Each value and the target are between -1,000,000,000 and 1,000,000,000
  • Exactly one pair adds up to the target

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

to answer and keep your progress. Reading is free for everyone.