LeetCode Challenge: Two Sum Explained (Java)

Published on: February 24, 2025

This Java solution finds two indices in an array whose values sum to a specific target.

    
        import java.util.HashMap;
        public int[] twoSum(int[] nums, int target) {
            HashMap map = new HashMap<>();
  
            for (int i = 0; i < nums.length; i++) {
                int complement = target - nums[i];
        
                if (map.containsKey(complement)) {
                    return new int[]{map.get(complement), i}; 
                }
        
                map.put(nums[i], i); 
            }
            
            return new int[]{}; 
        }
    
      

Instead of checking all pairs, we can store numbers we have seen in a HashMap and check if the complement (target - nums[i]) already exists.

Back to Blog