14 · Hashing & Prefix Sums

#1 Two Sum

Easysolve on LeetCode ↗

frequently reported atGoogleAmazonMicrosoftAdobeBloombergInfosys

the problem

In plain words

Given an array of integers and a target, return the indices of the two numbers that add up to the target. Exactly one answer exists, and you may not use the same element twice.

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

out [0,1]

2 + 7 = 9.

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

out [1,2]

in nums = [3,3], target = 6

out [0,1]

  • 2 ≤ n ≤ 10⁴
  • -10⁹ ≤ nums[i], target ≤ 10⁹
  • Exactly one valid answer

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #167
    2. #15
      3Sum
      Mediumin Two Pointers
    3. #560
      Subarray Sum Equals K
      Mediumin Hashing