Two Sum Problem Java Solution - The Coding Shala

Home >> Interview Questions >> Two Sum Problem

Two Sum Problem Java Solution

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 Java Program

Method 1:
We can use HashMap to store value and index.

Java Code: 

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0; i<nums.length; i++){
            int val = nums[i];
            if(map.containsKey(target-val)){
                ans[0] = map.get(target-val);
                ans[1] = i;
                return ans;
            }
            map.put(val, i);
        }
        return ans;
    }
}




Other Posts You May Like
Prev<< Introduction to Array                                                                           NEXT >>Rotate Array
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala