Two Sum Python

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
// Single Pass method using HashTable
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        inputMap = {}
        for i in range(0, len(nums)):
            if target - nums[i] in inputMap and i != inputMap[target - nums[i]]:
                return [inputMap[target - nums[i]], i]
            else:
                inputMap[nums[i]] = i





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

No comments:

Post a Comment

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...