← Back to Leo Academy Masterclass

Problem #1: Two Sum

Easy Array & String

Intuition & Strategy Breakdown

Use a hash map to store each number's index while iterating through the array. For each element, calculate its complement (target - num). If the complement is already in the map, return the pair of indices in O(n) time.

Python Solution

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

Java Solution

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map seen = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if (seen.containsKey(diff)) {
                return new int[] { seen.get(diff), i };
            }
            seen.put(nums[i], i);
        }
        return new int[] {};
    }
}
Watch Interactive Video on Leo Academy Main App