1. Two Sum Solution

Approach

The idea to solve this problem is to use a hashmap.

  1. For each element put the number and its index in the hashmap
  2. Difference = Target – current_num;
  3. if we find a difference in the hashmap, We get the solution
public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> prevMap = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            int diff = target - num;

            if (prevMap.containsKey(diff)) {
                return new int[] { prevMap.get(diff), i };
            }

            prevMap.put(num, i);
        }

        return new int[] {};
    }

About the Author

Leave a Reply

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

You may also like these