Data Structures & Algorithms View on GitHub โ†—

Two Integer Sum

Java

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

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

        for(int i = 0; i < nums.length; i++){
            
            if(map.containsKey(nums[i])) return new int[]{map.get(nums[i]), i};

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


        return new int[] {-1, -1};
    }
}

Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

        sumDict = {}

        for i in range(len(nums)):
            sum = target - nums[i]

            if sum in sumDict:
                return [sumDict[sum], i]

            sumDict[nums[i]] = i

        return [-1, -1]

Enjoyed this solution?

I write about software engineering, algorithms, and lessons learned. Check out more in the newsletter.

Browse the newsletter