Applied AI Engineer (LLM) coding learning path Level 1 This level · 1 of 9

Two Sum

Easy Hash map Array

Problem

Given an integer array nums and an integer target, return the indices of the two different positions whose values add up to the target. The problem guarantees exactly one answer.

Original: LeetCode 1: Two Sum.

Examples

Example 1

Input`nums = [2, 7, 11, 15], target = 9`
Output`[0, 1]`

Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2

Input`nums = [3, 3], target = 6`
Output`[0, 1]`

Two equal values at different indices are allowed. You just cannot use the same index twice.

Example 3

Input`nums = [-1, -2, -3, -4], target = -7`
Output`[2, 3]`

Negative numbers work the same way: -3 + -4 == -7.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 1: Two Sumleetcode.com
  2. Java SE 17 API: HashMapdocs.oracle.com
Previous
Next