Start learning free

LESSON 258 OF 410 · HASH TABLE

Two Sum IV - O(n) Time Complexity in JavaScript

Practice O(n) Read the full explanation

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input will have at most one solution, and you may not use the same index twice.

In case no solution exists, return [-1, -1]

Example:

Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9

Note:

Your algorithm should run in O(n) time and use O(n) space.


Hints:

This the type of problem where we optimize the brute force approach to get the optimal one. The brute force approach took O(n^2) time because we had two nested for loops, one for i and another one j. In order to get O(n), we have to reduce this to only one for loop, so we should fix only one index, let it be j, the index of the second number. We will try out each possible j, and for each of them we should check if there is an index i < j such that nums[i] + nums[j] == target:
for each j : 0 -> n - 1:
	// We know nums[j]. Find some index i < j such that nums[i] + nums[j] == target.
How can we find that index in O(1)?

nums[i] + nums[j] == target ⇔ nums[i] == target - nums[j]. So for each j, we should look for an element equal to target - nums[j] from the left of j. Is there a data structure that allows us to look for an element in a collection in constant time? How can we use it here?

That data structure is the Hash Map. We can have a Hash Map where we insert all the elements nums[j] we iterate on during the for loop. In this way, for each j, we can look in the Hash Map to see if there is some element of value target - nums[j] and if so, we found a solution:
for each j : 0 -> n - 1:
	- Look for target - nums[j] in the Hash Map. If there exists, we found the solution.
	- Otherwise, insert nums[j] into the Hash Map and continue with the for loop.
I know the code above is not perfect. Hash Maps work with pairs (key => value), we cannot just insert a nums[j] into a Hash Map. What should we actually insert in this hash map? What are the keys and what are the values?

The problem with the code above is that we just check if there is an element equal to target - nums[j]. If so, we have a solution, but that's not enough. The problem asks us to return the indices of those elements and we only know of them: j. Can we adapt the solution such that if for some j there is an element equal to target - nums[j], we can also get its index?

The pairs in the Hash Map should be nums[j] => j so that for each element we insert, we can also get its index:
for each j : 0 -> n - 1:
	if target - nums[j] in indexOfValue:
		return [indexOfValue[target - nums[j]], j]
	indexOfValue[nums[j]] = j
return [-1, -1]

STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · HASH TABLE

    Two Sum in JavaScript, explained

    Understanding the Problem

    The core challenge of this problem is to find two indices in an array such that the sum of the elements at these indices equals a given target. This problem is significant in various applications, such as financial transactions, where you need to find pairs of transactions that sum up to a specific amount.

    Potential pitfalls include assuming multiple solutions or using the same index twice, which the problem explicitly forbids.

    Approach

    To solve this problem, we can start with a naive approach and then optimize it:

    Naive Solution

    The naive solution involves using two nested loops to check all possible pairs of indices. This approach has a time complexity of O(n^2), which is not optimal for large arrays.

    Optimized Solution

    To achieve an O(n) time complexity, we can use a hash map (or dictionary) to store the elements and their indices as we iterate through the array. This allows us to check in constant time whether the complement of the current element (i.e., target - current element) exists in the hash map.

    Algorithm

    Here is a step-by-step breakdown of the optimized algorithm:

    1. Initialize an empty hash map.
    2. Iterate through the array.
    3. For each element, calculate its complement (target - current element).
    4. Check if the complement exists in the hash map.
    5. If it exists, return the indices of the current element and its complement.
    6. If it doesn't exist, add the current element and its index to the hash map.
    7. If no solution is found, return [-1, -1].

    Code Implementation

    /**
     * Function to find two indices such that their elements sum up to the target.
     * @param {number[]} nums - Array of integers.
     * @param {number} target - Target sum.
     * @return {number[]} - Indices of the two numbers.
     */
    function twoSum(nums, target) {
        // Initialize an empty hash map
        const indexMap = new Map();
    
        // Iterate through the array
        for (let j = 0; j < nums.length; j++) {
            // Calculate the complement
            const complement = target - nums[j];
    
            // Check if the complement exists in the hash map
            if (indexMap.has(complement)) {
                // Return the indices of the current element and its complement
                return [indexMap.get(complement), j];
            }
    
            // Add the current element and its index to the hash map
            indexMap.set(nums[j], j);
        }
    
        // If no solution is found, return [-1, -1]
        return [-1, -1];
    }
    
    // Example usage:
    const nums = [2, 7, 11, 15];
    const target = 9;
    console.log(twoSum(nums, target)); // Output: [0, 1]
    

    Complexity Analysis

    The time complexity of this approach is O(n) because we iterate through the array once. The space complexity is also O(n) due to the hash map storing up to n elements.

    Edge Cases

    Potential edge cases include:

    • Empty array: The function should return [-1, -1].
    • Array with one element: The function should return [-1, -1].
    • No solution exists: The function should return [-1, -1].

    To test these edge cases, you can use the following examples:

    console.log(twoSum([], 9)); // Output: [-1, -1]
    console.log(twoSum([1], 9)); // Output: [-1, -1]
    console.log(twoSum([1, 2, 3], 7)); // Output: [-1, -1]
    

    Testing

    To test the solution comprehensively, you can use a variety of test cases, from simple to complex. Here are some examples:

    console.log(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1]
    console.log(twoSum([3, 2, 4], 6)); // Output: [1, 2]
    console.log(twoSum([3, 3], 6)); // Output: [0, 1]
    

    Thinking and Problem-Solving Tips

    When approaching such problems, it's essential to:

    • Understand the problem requirements and constraints.
    • Start with a brute force solution to understand the basic logic.
    • Think about how to optimize the solution using data structures like hash maps.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    In this blog post, we discussed the Two Sum problem, its significance, and how to solve it optimally using a hash map. We also covered edge cases, testing, and provided tips for problem-solving. Understanding and solving such problems is crucial for improving algorithmic thinking and coding skills.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free