
Two Sum Problem ā Python Solution
š§ Two Sum Problem ā Python Solution Hi All, Today I solved a popular problem from LeetCode called Two Sum . š Problem Statement Given an array of integers nums and an integer target , return the indices of two numbers such that they add up to the target. Conditions: Each input has exactly one solution You cannot use the same element twice You can return the answer in any order š” Approach š¹ Brute Force (Not efficient) Check every pair using two loops Time Complexity: O(n²) š¹ Optimized Approach (Used) Use a dictionary (hash map) Store number and its index For each element: Find target - current number Check if it exists in dictionary š This reduces time complexity to O(n) š» Python Code class Solution : def twoSum ( self , nums , target ): num_map = {} for i in range ( len ( nums )): complement = target - nums [ i ] if complement in num_map : return [ num_map [ complement ], i ] num_map [ nums [ i ]] = i š Example Walkthrough Input: nums = [ 2 , 7 , 11 , 15 ] target = 9 Steps: i = 0 ā num
Continue reading on Dev.to Python
Opens in a new tab


