Hey devs! 👋
I'm starting a daily challenge where I solve 2 LeetCode problems every day and share my solutions, explanations, and approach here on Dev.to.
Today’s problems:
🧮 Two Sum
🔹 Problem 1: Two Sum
Problem Number:1
📝 Difficulty: Easy
✅ Problem Statement:
Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.
💡 Approach:
1.Using the basic approach (ie using two for loops)
Caution : This approach has a time complexity of O(n^2)
Python Code:
def twoSum(num,target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if(nums[i]+nums[j]==target):
return [i,j]
💡2.Approach:
We use a hash map to store previously seen numbers and their indices. For each number, we check if target - current number exists in the map.
Here we have use enumerate so first we have to understand what basically is enumerate in python.
enumerate() function adds a counter to each item in a list or other iterable.
Ex:
a = ["Geeks", "for", "Geeks"]
Iterating list using enumerate to get both index and element
for i, name in enumerate(a):
print(f"Index {i}: {name}")
Converting to a list of tuples
print(list(enumerate(a)))
Output:
Index 0: Geeks
Index 1: for
Index 2: Geeks
[(0, 'Geeks'), (1, 'for'), (2, 'Geeks')]
Python Code:
def twoSums(nums, target):
dict1 = {} # Empty dictionary
# Iterating list using enumerate to get both index and element
for i, num in enumerate(nums):
diff = target - num # Calculate the difference
# Check if the required number is already in dictionary
if diff in dict1:
return [dict1[diff], i]
# Store the current number with its index
dict1[num] = i
🧠 Explanation:
We use a dictionary to keep track of numbers we’ve seen so far along with their indices.
For each number num in nums, we compute target - num = diff.
If diff is already in the dictionary, it means we've seen the required number to complete the pair.
We return the stored index of that number and the current index.
Example:
nums = [2, 7, 11, 15]
target = 9
print(twoSums(nums, target)) # Output: [0, 1]
🏁 Conclusion
The Two Sum problem is a great introduction to using hash maps (dictionaries) for efficient lookups. By storing previously seen values, we avoid nested loops and reduce the time complexity to O(n).
This pattern shows up in many other problems, so understanding this well is important for interviews.
Top comments (0)