Last active
January 2, 2024 09:13
-
-
Save vamsitallapudi/06f387db72380c8265c742ee98f6317e to your computer and use it in GitHub Desktop.
Solution to Two Sum problem using HashMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int[] twoSum(int[] nums, int target) { | |
// Hashmap to store remainder as key and current index as value | |
Map<Integer, Integer> map = new HashMap<>(); | |
for(int i = 0; i < nums.length; i++) { | |
if(map.containsKey(nums[i])) { | |
// checks if map already contains value | |
return new int[]{i, map.get(nums[i])}; | |
} else { | |
// putting remainder and current index in map | |
map.put(target - nums[i], i); | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment