From Algorithms

Arrays & Hashing

Arrays & Hashing

Q1. Given a list of integers nums, return True if any value appears at least twice, and False if every element is distinct. Fill in the cell, run it, and check it against [1,2,3,1]True and [1,2,3]False.

python
def contains_duplicate(nums):
    return len(set(nums)) != len(nums)

Q2. Given nums and a target, return the indices of the two numbers that add to target (exactly one solution, can’t reuse an element). two_sum([2,7,11,15], 9)[0,1]. Do it in one pass.

python
def two_sum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [i, seen[complement]]
        seen[num] = i
    return None

The move: one pass, store value → index as you go, and check before you store so an element can’t match itself. The hash lookup turns the brute-force O(n²) into O(n).