DEV Community

Debesh P.
Debesh P.

Posted on

1. Two Sum | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/two-sum/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/two-sum/solutions/7498090/most-optimal-solution-beats-200-hashmap-bya71


leetcode 1


Solution

class Solution {
    public int[] twoSum(int[] nums, int target) {

        Map<Integer, Integer> map = new HashMap<>();

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

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

            map.put(nums[i], i);
        }

        return new int[] {};
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)