Leetcode — Two Sum
Java

Leetcode — Two Sum

December 13, 2024

Leetcode — Two Sum

Leetcode categorizes “Two Sum” as an easy question. In this problem, you must return the indexes of two numbers that add up to the given target number. Two Sum - LeetCode

You can solve this in a brute force way using two for loops to check each number against every other number ( 0(n²) ). We can also solve this using two-pointers and using an approach similar to a binary search. I am going to walk through one of the most common solutions for this problem.

Steps:

  1. Create a HashMap to hold each number and its index as the value.

  2. Loop through the nums array.

  3. For each iteration in the for loop, we can subtract the current number from the target number and try to find that number in the map. If the number exists, return the current index and that number's index (from the map). If that number doesn’t exist in the map, add it to the map along with its index.

  4. If there are no numbers that sum up to the target, return an array of -1s.

Java

class Solution {
    public int[] twoSum(int[] nums, int target) {
        
         HashMap<Integer, Integer> map = new HashMap<>();
         for( int i = 0; i < nums.length; i++){
             int current = nums[i];
             int complement = target - current; 
             
             if( map.containsKey(complement) ){
                 return new int[]{map.get(complement), i};
             }
             else{
                 map.put(current,i);
             }
             
         }
        
        return new int[]{-1,-1};
    }
}

Kotlin Solution:

class Solution {
    fun twoSum(nums: IntArray, target: Int): IntArray {
        
        // map to hold the number as the key and it's index in the array as the value
        val map = HashMap<Int, Int>() 
        
        nums.forEachIndexed{ i, currentNum ->
            val complement = target - currentNum
            //if the complement's num is in the map,
            //return it(complement's index in the array) and the current index
            map[complement]?.let{ return intArrayOf(it, i) }
            //else put the currentNum and its index in the map to find in upcoming iterations
            map.put(currentNum, i)
        }
        
        //we didn't find two nums that are equal to the target
        return intArrayOf(-1,-1)
    }
}