Two Sums | LeetCode problem #1 | Solution using Python

Hi,

The following solution has a time complexity of O(n) and not O(n2), because it does use for loop but not in nested form. If uses python hash map i.e. python dictionary to compare the values.

Problem Statement:

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.

constraints: please check here on the Leetcode website Two sums problem

Solution code:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
#Constraints
        if 2 > len(nums) > 10**4:
            print('list length is beyond acceptable')
            return

        if -10**9 > target > 10**9:
            return print("target is beyond acceptable")
      # Create has map out of list storing the list values and indexes.    
        hash_dict = {}
        for i in range (len(nums)):
#Another constraint
            if nums[i] < -10**9 or nums[i] > 10**9:
                return print("list carries bigger numbers")
            if nums[i] in hash_dict:
                hash_dict[nums[i]].append(int(i))
            else:
                hash_dict[nums[i]] = [int(i)]
        print(hash_dict)
        for j in range (len(nums)):
            target_value = target-nums[j]

            if target_value in hash_dict:
                target_list = hash_dict[target_value]
                if len(target_list)==1:
                    if j == target_list[0]:
                        continue 
                    else:
                        return [j, target_list[0]]
                else:
                    return [j, target_list[1]]

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP Code Snippets Powered By : XYZScripts.com