Two Sum in Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Initialize an empty dictionary to store the potential complements and their indices.
        complements = {}

        # Iterate through the list of numbers with their indices.
        for index, num in enumerate(nums):
            # Calculate the complement by subtracting the current number from the target.
            complement = target - num

            # Check if the complement is in the dictionary.
            if complement in complements:
                # If found, return the current index and the index of the complement.
                return [complements[complement], index]

            # If the complement is not found, store the current number and its index in the dictionary.
            complements[num] = index

        # If no solution is found (problem constraints guarantee one exists), return an empty list.
        return []

PrevNext