Two Sum

EasyArrays & HashingFree to try
Asked byAmazonAdobeGoogleAppleMicrosoftFacebook

Problem

Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one valid answer, and you may not use the same element twice.

Examples

Example 1
Input:nums = [2,7,11,15], target = 9
Output:[0,1]
nums[0] + nums[1] = 2 + 7 = 9.
Example 2
Input:nums = [3,2,4], target = 6
Output:[1,2]

Constraints

  • 2 <= nums.length <= 10^4
  • Only one valid answer exists for each input.

Try it now — no sign-up needed. Write your solution in Python or JavaScript, run it against test cases, and submit for a verdict, right in your browser.

Open the editor →

How to approach it: the Arrays & Hashing pattern

Arrays give O(1) index access; hash maps and sets give O(1) average lookup, insert, and delete by trading space for speed. Together they're the toolkit for turning brute-force O(n²) comparisons into a single O(n) pass.

Look for this pattern when

  • You need to check "have I seen this value before?" quickly.
  • You're counting occurrences or grouping items by a derived key (e.g. sorted letters for anagrams).
  • A nested loop is comparing every pair — a hash map can often replace the inner loop.

Read the full Arrays & Hashing guide →

Video walkthroughs

Original problem on LeetCode ↗

More Arrays & Hashing problems