leetcode solution of problem “Two Sum”

Two Sum

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

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

You can return the answer in any order.

This problem is taken from :- Two Sum Problem

Flow Diagram:-

Approach:-

Here the bad approach would be two use nested loop. So, we should avoid that. One approach we can follow is the use of HashMap. As HashMap stores the desired objects as key and value pairs. So here the key will be the element value of the given array and value will be the index position of that particular element. And we will check if the given (target value) – (current element value of the array nums[i]) present in the map or not.

And depending on that we will return those value after string those in a newly created Array.

Code:-

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
	    	
	    	HashMap map = new HashMap<>();
	    	
	    	for (int i = 0; i

For more problems and solution please visit:- Algorithm Problems and Solutions