Two Sum
The problem
Given an array of integers **nums and an integer target. Return the indices(0 - indexed) of two elements in nums **such that they add up to target.
Each input will have exactly one** **solution, and the same element **cannot be used twice. Return **the answer in any order.
Input: nums = [1, 6, 2, 10, 3], target = 7 Output: [0, 1] Explanation: nums[0] + nums[1] = 1 + 6 = 7
Input: nums = [1, 3, 5, -7, 6, -3], target = 0 Output: [1, 5] Explanation: nums[1] + nums[5] = 3 + (-3) = 0
Input: nums = [-6, 7, 1, -7, 6, 2], target = 3
- 2 <= nums.length <= 105
- -104 <= nums[i] <= 104
- -105 <= target <= 105
- Only one valid answer exists.
cpp
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
}
};java
class Solution {
public int[] twoSum(int[] nums, int target) {
}
}python
class Solution:
def twoSum(self, nums, target):javascript
class Solution {
twoSum(nums, target) {
}
}csharp
public class Solution {
public List<int> TwoSum(List<int> nums, int target) {
}
}go
func twoSum(nums []int, target int) []int {
//your code goes here
}Stuck? Show a way to structure it+
- 01For each value x, compute the needed complement target - x.
- 02Check whether that complement was seen at an earlier index.
- 03Store the current value and index only after the lookup.
- 04Return original indices and ensure one element is never used twice.
Reference answer
Then expect these follow-ups
How would you return every unique pair instead of one guaranteed pair?
Tests: duplicate handling
What changes if the input is already sorted?
Tests: algorithm choice
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question