SDE & MLE Prep

1. Two Sum

Problem

Given an integer array nums and an integer target, return the indices of the two elements that add up to target. Exactly one such pair exists, an element can't be paired with itself, and the indices may be returned in any order.

Example: nums = [2,7,11,15], target = 9 → [0,1]

Constraints: 2 ≤ n ≤ 10⁴. Follow-up: do better than O(n²).

Scan once. For each x, the partner we need is target - x. If we've already seen it, we're done; otherwise remember x → index.

nums = [2, 7, 11, 15], target = 9
i=0  x=2   need 7   seen {}       -> store {2:0}
i=1  x=7   need 2   seen {2:0}    -> hit!  answer [0, 1]

Complexity: O(n) time, O(n) space.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}  # value -> index
        for i, x in enumerate(nums):
            if target - x in seen:
                return [seen[target - x], i]
            seen[x] = i
        return []