Two Sum

Problem Summary

(Write in your own words, not copied from LeetCode. This forces comprehension.)

What is Being Asked?

(One sentence on the actual task.)

Key Observations

(Patterns, constraints, or hints in the problem statement.)

Approach Taken

(Step-by-step logic or pseudocode before coding.)

Why This Works

(Explain the core reason the solution is correct.)

Main Concepts Used

(Mark the CS concepts or algorithms used.)

Time & Space Complexity

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # nums = [3,3,3], target = 9
        # store index for each number in `nums`
        # iterate through each num and try to find the complementing pair to make the target

        # brute force:
        # nested loop - O(n^2)
        # for i in range(len(nums)): # 0, 1 
        #     for j in range(i + 1, len(nums)): # 1, 2 | 2
        #         if nums[i] + nums[j] == target: # no, no
        #             return [i, j] 
        
        # optimized
        hashmap = {} # 3: 
        for i, num in enumerate(nums):
            if target - num in hashmap:
                return [i, hashmap[target - num]]
            else:
                hashmap[num] = i

Common Mistakes / Things I Got Stuck On