š§ 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
- Find
š 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 = 2 ā complement = 7 ā not found ā store {2:0}
- i = 1 ā num = 7 ā complement = 2 ā found
Output:
[0, 1]
š„ļø Sample Outputs
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]
š§ Explanation
-
num_mapstores values and their indices - For each number:
- Compute
complement = target - num - Check if complement exists
- Compute
- If yes ā return indices
- Else ā store current number
ā” Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
ā Conclusion
This problem helped me understand:
- Efficient searching using hash maps
- Reducing time complexity from O(n²) to O(n)
- Writing optimized and clean code
š This is a very important problem for coding interviews!
Top comments (0)