Practice

Two Sum

Module 6 · Hash Tables

Problem

Given nums and target, return the indices of the two numbers that sum to target. Exactly one solution exists; you may not use the same element twice.

Goal

Return a pair of indices — not the values. Order of the pair does not matter to the judge as long as both indices are correct.

Examples

Example 1

Inputnums = [2,7,11,15], target = 9Output[0,1]

Example 2

Inputnums = [3,2,4], target = 6Output[1,2]

Explanation. not [0,0]!

Example 3

Inputnums = [3,3], target = 6Output[0,1]

Constraints

2 ≤ n ≤ 10⁴ · values in ±10⁹ · exactly one answer

Attempt it first

Tip

You've known the O(n) decision version ("does a pair exist?") since lesson one of Big O. This asks for indices — which changes the structure you carry. Watch [3,2,4] and [3,3]: both trap specific wrong versions.