1. Two Sum

1. Two Sum

Leetcode Blind 75

19th June 2022 ~ Dion Pinto

Description

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. (Problem)

Code (Python) -> Brute Force


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

Time Complexity => o(n2)

Space Complexity => o(1)

Code (Python) -> Hash


				
    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            d={}
            for i in range(len(nums)):
                if((target-nums[i]) in d):
                    return [i,d[target-nums[i]]]
                else:
                    d[nums[i]]=i
							
			

Time Complexity => o(n)

Space Complexity => o(n)

Back