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,
we store what we are expecting to see later.
Step-by-Step Line Explanation
Class Definition
class Solution:
Why?
Required for platforms like LeetCode
Organizes the solutionFunction Definition
def twoSum(self, nums: List[int], target: int) -> List[int]:
Why?
nums → input list
target → desired sum
Returns list of indicesCreate Dictionary
d = {}
Why?
This dictionary stores future expectations
Structure:
d = {
required_value : index
}
- Loop Through List
for i in range(0, len(nums)):
Why?
Traverse each element
Access index using i
- Get Current Value
value = nums[i]
Why?
Extract the current number from list
- Calculate Difference
difference = target - valueWhy?
We want:
value + difference = target
So:
difference = target - value
Check Condition
if value not in d:
Why?
Check if current value was expected earlier
Meaning:
“Did we already store this number as a required value?”Store Difference
d[difference] = i
Why?
We store what we need in the future
Example:
target = 9
value = 2
difference = 7
Store → {7: 0}
Meaning:
“If I see 7 later, I can form the answer.”
Else Condition (Match Found)
else:
Why?
If value is already in dictionary
That means we found the required pairStore Indices
current_index = i
prev_index = d[value]
Why?
current_index → current element
prev_index → index where this value was expected
- Return Answer
return [current_index, prev_index]
Why?
Return indices of the two numbers
Top comments (0)