Skip to main content

Problems and solution

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.

Input: nums = [2,7,11,15], target = 9 Output: [0,1]

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> numMap =  new HashMap<>();

        for(int i = 0 ; i < nums.length;i++ ){
           int complement = target-nums[i];
           if(numMap.containsKey(complement)){
            return new int[]{numMap.get(complement),i};
           }
           numMap.put(nums[i],i);

        }
        return null;

    }
}