v9.1.1
Menu

Two Sum

easyPRODesign & Hash MapsUber DSA

Given an array of integers and a target, return the indices of the two numbers that add up to the target.

Assume exactly one solution exists. Return the two indices as a list [i, j] with i < j; the tests print them space-separated (e.g. 0 1).

Example

Input
2,7,11,15
9
Output
0 1
Reasoning
  • nums is the list of integers [2,7,11,15][2, 7, 11, 15] and target is the single integer 99. Positions count from 00: 22 sits at index 00, 77 at 11, 1111 at 22 and 1515 at 33.
  • We need two different positions i<ji < j with numsi+numsj=9\text{nums}_i + \text{nums}_j = 9. Pairing the first element with each of the others gives 2+7=92 + 7 = 9, 2+11=132 + 11 = 13 and 2+15=172 + 15 = 17, so only the pair at positions 00 and 11 hits the target.
  • The remaining pairs all overshoot: 7+11=187 + 11 = 18, 7+15=227 + 15 = 22, 11+15=2611 + 15 = 26. So (0,1)(0, 1) is the single answer the constraints promise.
  • The output is the two indices, not the values 22 and 77. With the smaller index first they print as 0 1.
  • Notice that one position can't be used twice, but equal values at different positions are fine: for [3,3][3, 3] with target 66 the answer is 0 1, because the two 33s are separate elements.

Constraints

  • 2 <= len(nums) <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • Exactly one valid answer exists

Learn this in

More from Uber DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.