/1. Two Sum
Previous|Next

1. Two Sum

Easy
Arrays57.2% acceptance

Given an integer array input_array and an integer target_sum, return a list containing the indices of two distinct elements in input_array whose sum equals target_sum. Each input is guaranteed to have exactly one solution. The same element cannot be used twice. The order of indices in the output does not matter.

Example 1

Input: input_array = [5, 8, 12, 20], target_sum = 13

Output: [0, 1]

Explanation: input_array[0] + input_array[1] = 5 + 8 = 13

Example 2

Input: input_array = [-2, 4, 7, 10], target_sum = 8

Output: [0, 2]

Explanation: input_array[0] + input_array[2] = -2 + 10 = 8

Example 3

Input: input_array = [1, 1], target_sum = 2

Output: [0, 1]

Explanation: input_array[0] + input_array[1] = 1 + 1 = 2

Constraints

  • 2 <= len(input_array) <= 104
  • -109 <= input_array[i] <= 109
  • -109 <= target_sum <= 109
  • Exactly one valid answer exists
  • Indices must be distinct
Python (current runtime)

Case 1

Input: input_array = [6, 3, 9, 15], target_sum = 12

Expected: [1, 2]

Case 2

Input: input_array = [0, -1, 2, 5], target_sum = 4

Expected: [1, 3]

Case 3

Input: input_array = [100, 200, 300, 400], target_sum = 500

Expected: [0, 3]