Start learning free

LESSON 376 OF 673 · BINARY SEARCH

Two Sum

Practice O(n log n)

You get a list of integers nums and a number target.

Return the indices of two numbers that add up to target.

The two indices must be different. You can return them in either order.

If no pair adds up to target, return [-1, -1].

Example 1:

Input: nums = [5, 12, 3, 8], target = 15
Output: [1, 2]
Explanation: nums[1] + nums[2] = 12 + 3 = 15

Example 2:

Input: nums = [6, 1, 6], target = 12
Output: [0, 2]
Explanation: nums[0] + nums[2] = 6 + 6 = 12
The two 6s are at different indices.

Example 3:

Input: nums = [5, 1, 3], target = 10
Output: [-1, -1]
Explanation: No pair adds up to 10.
5 + 5 would use index 0 twice.

Constraints:

  • 2 to 1,000,000 numbers.
  • Each number fits in a 32-bit signed integer.
  • The target fits in a 32-bit signed integer too.
  • At most one pair adds up to the target.

Note:

Your algorithm should run in O(n log n) time and use O(n) extra space.


STEP 1 OF 14
    Ctrl + Enter to check