Back to DSA sheet
Two Sum
EasyArraysYou are given an array of integers and a target value. Find the two positions whose values add up exactly to the target and return those positions. Exactly one valid pair exists, and you may not use the same element twice.
Input format (stdin): the first line has two integers n and target. The second line has n integers. Output the two zero-based indices i and j (with i < j) separated by a space.
Examples
Input: 4 9
2 7 11 15
Output: 0 1
nums[0] + nums[1] = 2 + 7 = 9, so the indices are 0 and 1.
Input: 3 6
3 2 4
Output: 1 2
nums[1] + nums[2] = 2 + 4 = 6.
Constraints
- 2 <= n <= 10^4
- -10^9 <= nums[i] <= 10^9
- Exactly one valid pair exists
Sheets
Blind 75Grind 75NeetCode 150NeetCode 250Striver A2Z
two-sum.cpp3 sample tests
Loading editor
Test results
Run the sample tests to check your solution against expected output.
Custom input (stdin)
Output
Run your code to see its output.