Two Sum
Problem: Given an array of integers nums and an integer target, return the indices of the two numbers that add up to the target.
Source: https://leetcode.com/problems/two-sum/
Difficulty: Easy
Topics: Array, Hash Map
Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Constraints:
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- Only one valid answer exists.
Examples
Example 1:
Example 2:
Example 3:
Core Concept: The Complement
Before diving into approaches, understand this key idea:
For any element nums[i], the value we need to pair it with is called its complement:
If the complement exists at a different index j in the array, then [i, j] is the answer.
Every approach below is just a different strategy for finding the complement efficiently.
