/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 will have exactly one solution, and you may not use the same element 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] == 13

Example 2

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

Output: [0, 2]

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

Example 3

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

Output: [0, 1]

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

Constraints

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

Case 1

Input: input_array = [9, 3, 6, 2], target_sum = 5

Expected: [1, 3]

Case 2

Input: input_array = [10, -5, 15, 20], target_sum = 5

Expected: [0, 1]

Case 3

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

Expected: [1, 3]