AlgoFrames

Two Sum

Standard · Write code · about 12 min

Given an integer array nums and an integer target, return the indices [i, j] with i < j of the two values that add up to target.

At most one pair works. Return [] if no pair exists. Do not use the same cell twice.

Example 1

Input:

[[2,7,11,15],9]

Output:

[0,1]

2 + 7 = 9.

Example 2

Input:

[[3,2,4],6]

Output:

[1,2]

The first 3 cannot pair with itself.

Constraints

  • 0 ≤ nums.length ≤ 10,000
  • -1,000,000 ≤ nums[i], target ≤ 1,000,000
  • At most one pair adds up to target

Learn the idea first: Hash sets and maps in practice: counting, lookup, deduplication, a visual lesson.

More Hash sets and maps in practice: counting, lookup, deduplication problems