Skip to main content

Command Palette

Search for a command to run...

1. Two Sum

Updated
1 min read
1. Two Sum

YouTube Video

[A1] - Brute Force

Time: O(n^2)

Space: O(1)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i]+nums[j]==target:
                    return [i,j]
        return

[A2] - Hash Table

Time: O(n)

Space: O(n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict = {}
        for i,e in enumerate(nums):
            dict[e]=i

        for i in range(len(nums)):
            diff = target-nums[i]
            if diff in dict and i!=dict[diff]:
                return [i,dict[diff]]
        return

Comment: There is another way where you can solve the problem using a single iteration. Try to do it by yourself.

DSA

Part 1 of 1

Master the fundamentals of data structures and algorithms to ace coding interviews and solve real-world problems.