Two Sum - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Goal

Given an array of numbers and a target sum, find two indices such that the numbers at those indices add up to the target.

Key Idea (Intuition)

To form the target, for each number we need its complement (target − currentNumber). If we already know where the complement appeared earlier, we have the answer immediately. Thus, while traversing the array once, we maintain a map (valueToIndex) from number → index. This allows constant-time lookup of complements and ensures we can find the pair in O(n) time.

Traversal

🚶 Traverse the array: start from index 0 and move forward one element at a time.

🧮 At each index: compute the complement using target − currentNumber.

📖 Use the valueToIndex map: this map stores numbers that have already been seen as number → index pairs. It allows quick lookup to check whether the current complement was encountered earlier.

🔎 Check the map: if the complement exists in valueToIndex, you have found two numbers that add up to the target.

If found: return the pair [currentIndex, complementingIndex].

If not found: store currentNumber → index in the map and continue traversing.

Return Value

📦 When a complement is found during traversal, return [index, complementingIndex] immediately.

Time Complexity

O(n), since the array is traversed once.

Space Complexity

O(n), for storing numbers in the valueToIndex map.

Visucodize editorial solution titled JS Solution for LeetCode's Two Sum coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/two-sum.