Blind 75
1 / 75Free practice

Two Sum

Easy · Arrays & hashing

Jump to code

Find the indices of two different elements of an integer array whose sum equals a target. Assume exactly one pair exists; return the indices in either order.

Examples

Example 1

nums = [2,7,11,15]
target = 9

Output: [0,1]

Example 2

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

Output: [1,2]

Constraints

  • 2 <= nums.length <= 1000
  • -10,000,000 <= nums[i] <= 10,000,000
  • -10,000,000 <= target <= 10,000,000
  • Only one valid answer exists.
Need a hint?

What information would let you find the partner of the current value immediately?

Asked in real interviews

Candidates reported versions of Two Sum from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. No account or XP needed for this problem.
Language
Case 1
Input
[
  [
    2,
    7,
    11,
    15
  ],
  9
]
Expected
[
  0,
  1
]
Case 2
Input
[
  [
    3,
    2,
    4
  ],
  6
]
Expected
[
  1,
  2
]
Case 3
Input
[
  [
    3,
    3
  ],
  6
]
Expected
[
  0,
  1
]
Case 4
Input
[
  [
    0,
    4,
    3,
    0
  ],
  0
]
Expected
[
  0,
  3
]
Case 5
Input
[
  [
    -1,
    -2,
    -3,
    -4,
    -5
  ],
  -8
]
Expected
[
  2,
  4
]

Drafts are saved per language in this browser when storage is available.