Problems › Arrays & strings

Two Sum

Difficulty: Easy · Topic: Arrays & strings

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

You may assume that each input has exactly one solution, and you may not use the same element twice. Return the indices in increasing order.

Examples

two_sum([2,7,11,15], 9)
→ [0,1]

nums[0] + nums[1] = 2 + 7 = 9.

two_sum([3,2,4], 6)
→ [1,2]

nums[1] + nums[2] = 2 + 4 = 6.

two_sum([3,3], 6)
→ [0,1]

Target complexity: time O(n), space O(n)

Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.

Learn the idea first: the lesson for this problem.

More Arrays & strings problems