Skip to content

Instantly share code, notes, and snippets.

@vamsitallapudi
Last active January 2, 2024 09:13
Show Gist options
  • Save vamsitallapudi/06f387db72380c8265c742ee98f6317e to your computer and use it in GitHub Desktop.
Save vamsitallapudi/06f387db72380c8265c742ee98f6317e to your computer and use it in GitHub Desktop.
Solution to Two Sum problem using HashMap
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