Two Sum

Given an int array and an int target, return indices of the two numbers such that they add up to target.

import java.util.Map;
import java.util.HashMap;

public class TwoSum {

    public static 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);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        int[] result = twoSum(nums, target);
        System.out.println(result[0] + " " + result[1]);
    }
}
0 1

This program uses a HashMap to store the indices of the array elements as values and the element values as keys. Then, it iterates through the array and for each element, it checks if the complement of the element with respect to the target sum is present in the HashMap. If it is, then it returns the indices of the two elements. If it isn’t, then it adds the current element and its index to the HashMap. If no solution is found, it throws an IllegalArgumentException.

Leave a Reply

Your email address will not be published. Required fields are marked *