Two Sum in TypeScript

/**
 * Finds two numbers in an array that add up to a target and returns their indices.
 * Assumes exactly one solution exists, and each element can be used only once.
 * 
 * @param nums - An array of integers.
 * @param target - The target integer to find the sum for.
 * @returns Indices of the two numbers that add up to the target.
 */
function twoSum(nums: number[], target: number): number[] {
    // Create a map to store the numbers and their indices.
    // The map will hold the value of the number as the key and its index as the value.
    const numMap: Map<number, number> = new Map();

    // Iterate through the array of numbers.
    for (let i = 0; i < nums.length; i++) {
        // Calculate the complement of the current number.
        // This is the number we need to find in the array to pair with the current number to reach the target.
        const complement: number = target - nums[i];

        // Check if the complement exists in the map.
        // If it does, it means we have found the two numbers which add up to the target.
        if (numMap.has(complement)) {
            // If complement is found, return the indices of the complement and the current number.
            return [numMap.get(complement)!, i];
        }

        // If the complement is not found, add the current number and its index to the map.
        numMap.set(nums[i], i);
    }

    // If no solution is found (which should not happen in this problem as per the constraints), return an empty array.
    // This line is more for TypeScript type safety, to ensure the function always returns a value.
    return [];
}

PrevNext