1. Two Sum
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target as a pair (i, j) with i < j.
Indices are 0-based. Each input has exactly one solution, and you may not use the same element twice.
Can you do it in a single pass?
Example 1:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9, so the answer is indices 0 and 1.
Example 2:
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
Explanation: nums[1] + nums[2] = 2 + 4 = 6.
Constraints:
- 2 ≤ nums.length ≤ 10⁴
- -10⁹ ≤ nums[i] ≤ 10⁹
- -10⁹ ≤ target ≤ 10⁹
- Exactly one valid answer exists.
Hints:
A brute-force double loop works, but it's O(n²).
While scanning, ask: have I already seen target - nums[i]? A hash map answers that in O(1).
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [2, 7, 11, 15], target = 9
Expected output: [0, 1]