Skip to content

Instantly share code, notes, and snippets.

@visionbyangelic
Last active December 26, 2025 14:28
Show Gist options
  • Select an option

  • Save visionbyangelic/720b68f20a515a7cbd6886c34fddd274 to your computer and use it in GitHub Desktop.

Select an option

Save visionbyangelic/720b68f20a515a7cbd6886c34fddd274 to your computer and use it in GitHub Desktop.

001 | Two Sum 🎯

The Challenge: Find two numbers in a list that add up to a specific target.


πŸ’‘ The "Aha!" Moment

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.

πŸ› οΈ My Strategy: The "Memory" Map

  • Data Structure: I used a Python Dictionary (prevMap = {}).
  • Mechanism: As I iterate, I calculate diff = target - n.
  • Logic: If the diff is in my "memory," I've found the pair! If not, I "remember" the current number and move on.

🐍 Python Implementation

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

image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment