Q4: How do you solve the Two Sum problem in O(n) time?

Given an array of integers and a target sum, return the indices of two numbers that add up to target. Use a HashMap<Integer, Integer> storing (value -> index). Iterate through the array once, computing complement = target - nums[i]. If complement exists in map, return current index and stored complement index.

Optimal Two Sum Solution
import java.util.HashMap;
import java.util.Map;

public class TwoSum {
    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[]{map.get(complement), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
💡 Maps element values to array indices to resolve complement lookups instantly.
Key Takeaways
  • HashMap provides $O(1)$ lookup time for target complements.
  • Achieves $O(n)$ time complexity in a single pass.
Knowledge Check

What is the time complexity of finding a Two Sum pair using a Hash Table?