Start learning free

LESSON 295 OF 671 · BRUTE FORCE

Two Sum

Practice O(n2)

You get a slice 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^2) time and use O(1) space.


Go starter code:

func twoSum(nums []int, target int) []int {
}
STEP 1 OF 5
    Ctrl + Enter to check