Given an array and a target, return the indexes of the two numbers that add up to the target. Exactly one answer exists, and you cannot use the same element twice.
DSA Animator › DSA Revision › Arrays › Two Sum
Remember: Two Sum means storing what you have seen in a hash map. For each number, look up target minus the number. The video solves Two Sum (LeetCode 1, Easy) with the Hash Map pattern from the Arrays topic, and you can replay every step in the interactive Two Sum animation.
Given an array and a target, return the indexes of the two numbers that add up to the target. Exactly one answer exists, and you cannot use the same element twice.
For 2, 11, 7, 15 with target 9, the answer is indexes 0 and 2. That is 2 plus 7, which is 9.
Checking every pair works, but it is O of n squared. For a big array, that is far too slow.
For each number, ask: have I already seen the number I need? The number you need is the target minus the current number. A hash map from value to index answers that in constant time.
2 needs 7, which we have not seen, so store 2 at index 0. 11 needs minus 2, not seen, so store 11 at index 1. 7 needs 2. 2 is in the map, at index 0. So the answer is indexes 0 and 2.
In code, loop once over the array. Compute the number you need. If the map has it, return both indexes. Otherwise store the current number with its index, so it's O of n time and O of n space.
Remember: Two Sum means storing what you have seen in a hash map. For each number, look up target minus the number.