two-sum.sh — zsh

Two Sum

easy
Next
arrayshashmap

Given an integer array nums and an integer target, return the indices of two distinct elements whose values add up to target. Exactly one valid pair exists. Return the lower index first.

Input / output

  • Input: nums: integer[], target: integer
  • Output: [leftIndex, rightIndex]

Examples

  1. nums = [2, 7, 11, 15], target = 9 returns [0, 1] because 2 + 7 = 9.
  2. nums = [3, 2, 4], target = 6 returns [1, 2].

Constraints

  • 2 <= nums.length <= 10,000
  • -1,000,000 <= nums[i], target <= 1,000,000
  • Do not reuse the same array element.

Follow-up Can you solve it in linear time with a single pass and explain the memory tradeoff?

Examples
Example 1
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Example 2
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3
Input: nums = [3,3], target = 6
Output: [0,1]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.