Back to DSA
Two Sum
easyYou have an integer array and a target sum. Identify two distinct positions whose corresponding values add up to the target. Exactly one valid pair exists, and you must not reuse the same position. Return the pair of indices in any order.
Examples
Example 1:
Input:
arr = [3,5,8,12], target = 13Output:
[0,2]Explanation: The values at positions 0 and 2 are 3 and 8, which sum to the target of 13.
Example 2:
Input:
arr = [4,1,6], target = 7Output:
[1,2]Explanation: Position 1 holds 1 and position 2 holds 6; together they equal 7.
Hints
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[]{};
}
}Time complexity
O(n)Space complexity
O(n)