Two Sum Problem [Leetcode]

Difficulty – Easy

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9.

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Two Sum Problem Solution

The best way to solve this problem by using Hashmap in Java

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


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment