KatInterview

1. Two Sum

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the indices of two numbers in an array nums that add up to a given target. We are guaranteed that there is exactly one solution, and we cannot use the same element twice. The challenge lies in finding a solution more efficient than the naive brute-force approach, which would check every pair of numbers and have a time complexity of O(n²).

Solution

Two Sum in Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Create a hash map (dictionary in Python) to store numbers and their indices.
        # Key: number, Value: index
        num_map = {}

        # Iterate through the array with both index and value.
        for i, num in enumerate(nums):
            # Calculate the complement needed to reach the target.
            complement = target - num

            # Check if the complement exists in the map.
            if complement in num_map:
                # If found, we have our pair.
                # Return the index of the complement and the current index.
                return [num_map[complement], i]

            # If the complement is not found, add the current number and its index to the map.
            # This makes it available for future elements to find as a complement.
            num_map[num] = i

        # The problem statement guarantees that exactly one solution exists,
        # so this part of the code will not be reached. We can return an empty list
        # or raise an error, but it's not necessary given the problem constraints.
        return []

Two Sum in Java

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // Create a hash map to store numbers and their indices.
        // Key: number, Value: index
        Map<Integer, Integer> numMap = new HashMap<>();

        // Iterate through the array.
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            // Calculate the complement needed to reach the target.
            int complement = target - num;

            // Check if the complement exists in the map.
            if (numMap.containsKey(complement)) {
                // If found, we have our pair.
                // Return the index of the complement and the current index.
                return new int[]{numMap.get(complement), i};
            }

            // If the complement is not found, add the current number and its index to the map.
            // This makes it available for future elements to find as a complement.
            numMap.put(num, i);
        }

        // The problem statement guarantees that exactly one solution exists,
        // so this part of the code should not be reached.
        // Throw an exception for good practice if no solution is found.
        throw new IllegalArgumentException("No two sum solution");
    }
}

Two Sum in C++

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // Create a hash map to store numbers and their indices.
        // Key: number, Value: index
        unordered_map<int, int> numMap;

        // Iterate through the array.
        for (int i = 0; i < nums.size(); ++i) {
            int num = nums[i];
            // Calculate the complement needed to reach the target.
            int complement = target - num;

            // Check if the complement exists in the map.
            // .find() returns an iterator to the element if found,
            // otherwise it returns an iterator to map.end().
            if (numMap.find(complement) != numMap.end()) {
                // If found, we have our pair.
                // Return the index of the complement and the current index.
                return {numMap[complement], i};
            }

            // If the complement is not found, add the current number and its index to the map.
            // This makes it available for future elements to find as a complement.
            numMap[num] = i;
        }

        // The problem statement guarantees that exactly one solution exists,
        // so this part of the code will not be reached.
        // We return an empty vector just to satisfy the function's return type.
        return {};
    }
};

Two Sum in TypeScript

function twoSum(nums: number[], target: number): number[] {
    // Create a hash map to store numbers and their indices.
    // Key: number, Value: index
    const numMap = new Map<number, number>();

    // Iterate through the array.
    for (let i = 0; i < nums.length; i++) {
        const num = nums[i];
        // Calculate the complement needed to reach the target.
        const complement = target - num;

        // Check if the complement exists in the map.
        if (numMap.has(complement)) {
            // If found, we have our pair.
            // Return the index of the complement and the current index.
            // The `!` (non-null assertion operator) tells TypeScript that we are sure
            // numMap.get(complement) will not be undefined.
            return [numMap.get(complement)!, i];
        }

        // If the complement is not found, add the current number and its index to the map.
        // This makes it available for future elements to find as a complement.
        numMap.set(num, i);
    }

    // The problem statement guarantees that exactly one solution exists,
    // so this part of the code will not be reached.
    // We return an empty array just to satisfy the function's return type.
    return [];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.