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 :

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};

        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:
    return list(result)

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

© 2024 by Chiranjeevi Karthik