This page looks best with JavaScript enabled

Two Sum

 ·  ☕ 1 min read  ·  ✍️ Syed Dawood

Problem

LeetCode 1: Two Sum

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from typing import Optional

class Solution:
    def twoSum(self, nums: list[int], target: int) -> list[Optional[int], Optional[int]]:
        storage = {}
        for i in range(len(nums)):
            other = target - nums[i]
            if other in storage:
                return [storage[other], i]
            storage[nums[i]] = i
        return []

Explaination

The core idea here is x + y = z(sum) , y = z(sum) - x . We iterate over the list, each element becomes x, we do z(sum) - x and check it’s presense in the list. we are using sets for efficient membership checks.

References

Also see

Share on

ALLSYED
WRITTEN BY
Syed Dawood
< frontend | backend | fullstack > Developer