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.