Start learning free

LESSON 301 OF 677 · BRUTE FORCE

Two Sum

Practice O(n2)

You get an array 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 Array(-1, -1).

Example 1:

Input: nums = Array(5, 12, 3, 8), target = 15
Output: Array(1, 2)
Explanation: nums(1) + nums(2) = 12 + 3 = 15

Example 2:

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

Example 3:

Input: nums = Array(5, 1, 3), target = 10
Output: Array(-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^2) time and use O(1) space.


STEP 1 OF 4
    Ctrl + Enter to check