|Two Sum
All Challenges

Two Sum

MediumArrays

Given a list of integers nums and a target integer target, return the indices of the two numbers that add up to target.


Return the indices as a list [i, j] where i < j. You may assume exactly one solution exists.


This is the classic entry-level interview problem. It shows up in payment processing (finding matching transactions), logistics (finding pairs that fill a weight limit), and more.

Examples

Input: two_sum([2, 7, 11, 15], 9)
Output: [0, 1]
nums[0] + nums[1] = 2 + 7 = 9
Input: two_sum([3, 2, 4], 6)
Output: [1, 2]
nums[1] + nums[2] = 2 + 4 = 6
Input: two_sum([3, 3], 6)
Output: [0, 1]
Same value, different indices

Constraints

  • 2 <= len(nums) <= 10,000
  • Exactly one valid answer exists
  • Return indices as [i, j] where i < j
pythoneditor
Loading Python runtime…