Back to articles
Two sum

Two sum

via Dev.to PythonJAYA SRI J

The Two Sum problem is one of the most important problems in programming interviews. It tests how efficiently you can: Search for values Use data structures Optimize time complexity Instead of checking all pairs (which is slow), we use a dictionary (hash map) to solve it efficiently. Problem Statement You are given: A list of integers → nums A target integer → target Goal: Find two indices such that: nums[i] + nums[j] = target Return those indices. my code: class Solution : def twoSum ( self , nums : List [ int ], target : int ) -> List [ int ]: d = {} for i in range ( 0 , len ( nums )): value = nums [ i ] difference = target - value if value not in d : d [ difference ] = i else : current_index = i prev_index = d [ value ] return [ current_index , prev_index ] Understanding the Code idea This approach works differently from the standard one. Standard Method: Store → number : index Your Method: Store → required number (difference) : index Meaning: Instead of storing what we have seen, w

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles