Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target,

where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

class Solution(object):

class Solution(object):
    def two_sum_bruteforce(self,arr,num):
        """
        :type arr : List[Int]
        :type num : Int
        :rtype tuple : (Int,Int)
        O(n2) time complexity
        """
        for i in range(len(arr)):
            for j in range(i+1,len(arr)):
                if arr[i]+arr[j]==num:
                    return i+1,j+1
        return None

    def two_sum_hashmap(self,arr,num):
        """
        :type arr : List[Int]
        :type num : Int
        :rtype tuple : (Int,Int)
        O(n) time complexity
        O(n) space complexity worst case
        """
        hash_map = {}
        for i in range(len(arr)):
            if num-arr[i] in hash_map:
                return hash_map[num-arr[i]]+1,i+1
            hash_map[arr[i]] = i
        return None

    def two_sum_sorting_noindex(self,arr,num):
        """
        :type arr : List[Int]
        :type num : Int
        :rtype tuple : (Int,Int)
        O(nLogn) time complexity
        This approach doesn't return index , but returns actual values
        """
        arr = sorted(arr)
        start  = 0
        end = len(arr)-1
        while end>start:
            curr_sum = arr[start]+arr[end]
            if curr_sum == num:
                return arr[start],arr[end]
            if curr_sum>num:
                end-=1
            else:
                start+=1
        return None

results matching ""

    No results matching ""