0
0
DSA Pythonprogramming~10 mins

Two Sum Problem Classic Hash Solution in DSA Python - Execution Trace

Choose your learning style9 modes available
Concept Flow - Two Sum Problem Classic Hash Solution
Start with empty hash map
Iterate over each number in array
Calculate complement = target - current number
Check if complement in hash map?
YesReturn indices
No
Add current number and index to hash map
Repeat for next number
If no pair found, return None
We scan the list once, storing numbers and their indices in a hash map. For each number, we check if the complement to reach the target exists in the map. If yes, we return the pair of indices.
Execution Sample
DSA Python
def two_sum(nums, target):
    hashmap = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hashmap:
            return [hashmap[complement], i]
        hashmap[num] = i
    return None
This code finds two numbers in 'nums' that add up to 'target' and returns their indices.
Execution Table
StepOperationCurrent Number (num)Index (i)Complement (target - num)Hash Map StateActionResult
1Start iteration---{}Initialize empty hash map-
2Check complement207{}7 not in hash mapAdd 2:0 to hash map
3Add to hash map207{2:0}--
4Check complement712{2:0}2 found in hash mapReturn [0,1]
5End---{2:0}Pair found, stop[0,1]
💡 Complement found in hash map at step 4, so indices [0,1] returned.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
hashmap{}{}{2:0}{2:0}{2:0}
i-0011
num-2277
complement-7722
Key Moments - 3 Insights
Why do we check if the complement is in the hash map before adding the current number?
Because if we add the current number first, we might match it with itself. Checking first ensures we only find pairs with different indices, as shown in execution_table step 4 where complement 2 is found before adding 7.
What happens if no two numbers add up to the target?
The loop finishes without returning, so the function returns None (not shown in this example). The hash map ends up containing all numbers with their indices, but no complement match is found.
Why do we store the number as key and index as value in the hash map?
Because we need to quickly check if a complement number exists and retrieve its index to return the pair. The hash map allows O(1) lookup by number.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the value of 'complement'?
A2
B7
C0
D1
💡 Hint
Check the 'Complement (target - num)' column at step 4 in execution_table.
At which step does the hash map first contain the key 2?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Hash Map State' column to see when {2:0} appears.
If the target was 10 instead of 9, what would happen at step 4?
AComplement 3 found in hash map
BComplement 2 found in hash map
CComplement 3 not found in hash map
DComplement 7 found in hash map
💡 Hint
Think about how complement is calculated and check hash map contents in variable_tracker.
Concept Snapshot
Two Sum Classic Hash Solution:
- Use a hash map to store numbers and their indices.
- For each number, compute complement = target - number.
- Check if complement is in hash map.
- If yes, return indices.
- Else, add current number and index to hash map.
- Runs in O(n) time with one pass.
Full Transcript
The Two Sum problem finds two numbers in a list that add up to a target. This classic hash solution uses a hash map to store numbers and their indices as we scan the list once. For each number, we calculate the complement needed to reach the target. We check if this complement is already in the hash map. If found, we return the pair of indices immediately. Otherwise, we add the current number and its index to the hash map and continue. This approach avoids nested loops and runs efficiently in linear time. The execution table shows step-by-step how the hash map changes and when the pair is found.