1. Two Sum
Given an integer array nums and a target, return the indices of the two different elements whose sum equals target. Exactly one pair exists. Either index order is accepted.
Return positions, not the two values. The same position cannot be used twice.
Example 1
Input
nums = [4,8,1,6], target = 10
Output
[0,3]
Explanation: The values at positions 0 and 3 are 4 and 6; their sum is 10.
Example 2
Input
nums = [5,5], target = 10
Output
[0,1]
Explanation: The two equal values occupy different positions. Neither position is reused.
Constraints
2 <= nums.length <= 104-109 <= nums[i] <= 109-109 <= target <= 109- Exactly one pair of distinct indices sums to target. Return its indices in either order.
Follow-up: Can you solve this in less than O(n2) time?
Hints
Hint 1
Fix the larger index. What value must appear earlier?
Hint 2
Store a location for each processed value.
Hint 3
Check the complement before insertion; return the earlier index and current index.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Find a complement
[3,2,4]
6
[1,2]