The Challenge: Find two numbers in a list that add up to a specific target.
Initially, I thought about checking every single pair (which is slow). Then I realized: if I'm looking at a number like 7 and the target is 10, I am essentially hunting for a 3. Instead of looking forward, I can keep a "memory" of what I've already seen to find that 3 instantly.
- Data Structure: I used a Python Dictionary (
prevMap = {}). - Mechanism: As I iterate, I calculate
diff = target - n. - Logic: If the
diffis in my "memory," I've found the pair! If not, I "remember" the current number and move on.
class Solution(object):
def twoSum(self, nums, target):
prevMap = {} # This is your "memory" (sticky notes)
for i, n in enumerate(nums):
diff = target - n
# CHECK: Have we seen this 'diff' before?
if diff in prevMap:
# If yes, return the index of 'diff' and our current index 'i'
return [prevMap[diff], i]
# If no, SAVE the current number in our memory
# The number is the 'key', the index is the 'value'
prevMap[n] = iπ Performance Reflection
- Time Complexity:
$O(n)$ β We only loop through the list once. - Space Complexity:
$O(n)$ β We store up to$n$ elements in the dictionary.
β Proof of Acceptance