DEV Community

Cover image for Started With Leetcode- Array- Q1 Two Sum
Pranjal Sailwal
Pranjal Sailwal

Posted on

Started With Leetcode- Array- Q1 Two Sum

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        int n = nums.length;
//Building Hash 
        for (int i = 0; i < n; i++) {
            numMap.put(nums[i], i);
        }
//Finding complement
        for (int i = 0; i < n; i++) {
            int complement = target - nums[i];
            if (numMap.containsKey(complement) && numMap.get(complement) != i) {
                return new int[]{i, numMap.get(complement)};
            }
        }
//for no solution
        return new int[]{};
    }
}
Enter fullscreen mode Exit fullscreen mode

Open to updates and suggestions.

Top comments (0)