Back to articles
Two Sum

Two Sum

via Dev.to TutorialAshiq Omar

In this task, I worked on finding two numbers in an array that add up to a given target. Unlike the previous approach, this method works even if the array is not sorted. What I Did I created a function twoSum that takes an array and a target value, and returns the indices of the two numbers that add up to the target. For example: Input: nums = [2, 7, 11, 15], target = 9 Output: (0, 1) This means the elements at index 0 and 1 add up to 9. How I Solved It To solve this, I used a dictionary (hash map) to store numbers and their indices. I looped through the array, and for each element: I calculated the value needed to reach the target (target - current number) I checked if this value already exists in the dictionary If it exists, I return the indices If not, I store the current number and its index in the dictionary CODE: class Solution : def twoSum ( self , nums : list [ int ], target : int ) -> list [ int ]: numToIndex = {} for i , num in enumerate ( nums ): if target - num in numToInde

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles