DEV Community

Matsu
Matsu

Posted on • Updated on

Decoding the solution of Two Sum Challenge from LeetCode

Recently, I tackled the "Two Sum" challenge from LeetCode. After studying the solution code, I found myself pondering an interesting question: Why do we use a key-value hash map instead of an array? Let's dig into the solution code and explore the reasoning behind this choice.

Let me start by providing the code:

const twoSum = function(nums, target) {
  // 'result' will store the values encountered in the array along with their indices.
  const result = {};

  for (let i = 0; i < nums.length; i++) {
    // Find the difference between the target and the current array element.
    const complement = target - nums[i];

    // Check if the complement exists in the 'result' object.
    if (result.hasOwnProperty(complement)) {
      // If found, return the indices of the complement and the current element.
      return [result[complement], i];
    }

    // If the complement is not found, store the current array element and its index in 'result'.
    result[nums[i]] = i;
  }

  // If no valid pair is found, return an empty array.
  return [];
};

Enter fullscreen mode Exit fullscreen mode

As I delved into the solution, I questioned the choice of using a key-value hash map instead of an array. It turns out that this approach significantly improves the algorithm's complexity. By utilizing the key as the array element and the value as its index, we achieve an O(n) complexity. This means we no longer need to iterate over the array to find the complement; we can quickly check its existence using the "hasOwnProperty()" method.

In conclusion, opting for a key-value hash map over an array in the "Two Sum" problem significantly enhances algorithm efficiency. By understanding the nuances of data structures and their applications, we can create more streamlined and effective solutions.

Console You Later!

Top comments (0)