DEV Community

Jeyaprasad R
Jeyaprasad R

Posted on

Two Sum

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 numToIndex:
        return numToIndex[target - num], i
      numToIndex[num] = i
Enter fullscreen mode Exit fullscreen mode

How It Works

The dictionary helps store values we have already seen. As we move through the array, we quickly check if the required pair already exists.

This makes the solution very fast because it avoids checking all possible pairs and finds the answer in a single pass.

Top comments (0)