DSA AnimatorREVISION VIDEOS
← Back to problems
New

Two Sum — LeetCode 1 video explanation

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.

Loading videos…

DSA Animator › DSA Revision › Arrays › Two Sum

Key moments in the Two Sum video

0:02Problem0:13Example0:21Brute force0:27Key idea0:38Dry run0:52Code1:05Takeaway

What you will learn

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.

Two Sum video transcript

Problem

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.

Example

For 2, 11, 7, 15 with target 9, the answer is indexes 0 and 2. That is 2 plus 7, which is 9.

Brute force

Checking every pair works, but it is O of n squared. For a big array, that is far too slow.

Key idea

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.

Dry run

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.

Code

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.

Takeaway

Remember: Two Sum means storing what you have seen in a hash map. For each number, look up target minus the number.

More Arrays revision videos

← All 185 DSA revision videos