Two Sum

Given an array of integer nums and an integer target, return indices of the two numbers such that they add up to the target.


Problem Link : https://leetcode.com/problems/two-sum

Time complexity : O(n) Space Complexity : O(n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        //Stores value, index
        Map<Integer,Integer> indexMap = new HashMap<>();
        for(int idx=0;idx<nums.length;idx++)
        {
            int compliment = target - nums[idx];
            if(indexMap.containsKey(compliment)) return new int[]{indexMap.get(compliment),idx};

            indexMap.put(nums[idx],idx);
        }
        return new int[] {};
    }
}
  • If we have to return the elements themselves (Python solution):
def twoNumberSum(array, targetSum):
    # Write your code here.
    result = set([])
    for item in array:
        temp = targetSum - item
        if temp in array and temp != item:
            result.add(temp)
            result.add(item)
    return list(result)

Time complexity : O(n) Space Complexity : O(n)



© 2024 by Chiranjeevi Karthik