Skip to main content
Easy89% accepted

Two Sum

ArraysHash Map
Problem Statement

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Examplespublic test cases
  • Basic: [2,7,11,15], target=9 → [0,1]

    Input two_sum([2,7,11,15], 9)

    Output [0, 1]

  • Middle pair: [3,2,4], target=6 → [1,2]

    Input two_sum([3,2,4], 6)

    Output [1, 2]

  • Duplicates: [3,3], target=6 → [0,1]

    Input two_sum([3,3], 6)

    Output [0, 1]

  • Both at end: [1,2,5,6], target=11 → [2,3]

    Input two_sum([1,2,5,6], 11)

    Output [2, 3]

Complexity
TimeO(n)
SpaceO(n)
Asked By
GoogleAmazonMetaApple

Ready to solve?

Open the code editor with the official template, run tests, and iterate.