Solving Two Sum in Python

0 min read 161 words

The challenge

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[] + nums[1] = 2 + 7 = 9,
return [, 1].

The solution in Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # keep a hashmap of items found
        seen = {}
        
        # loop through the nums, with int and value
        for i, v in enumerate(nums):
            # set remaining to the target minus the value
            remaining = target - v
            # check if the new value is in the hashmap
            if remaining in seen:
                # return it and the index
                return [seen[remaining], i]
            # otherwise, put it on the map instead
            seen[v] = i
        
        # nothing found, return an empty list
        return []
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags