0
0
DSA Pythonprogramming~30 mins

Two Sum Problem Classic Hash Solution in DSA Python - Build from Scratch

Choose your learning style9 modes available
Two Sum Problem Classic Hash Solution
📖 Scenario: You are helping a friend who runs a small store. They want to find two items that together cost exactly a certain amount of money. You will write a program to find the positions of these two items in the price list.
🎯 Goal: Build a program that finds two numbers in a list that add up to a target value using a hash map (dictionary) for fast lookup.
📋 What You'll Learn
Create a list called prices with the exact values: [2, 7, 11, 15]
Create a variable called target and set it to 9
Use a dictionary called seen to store numbers and their indices while looping through prices
Find two indices i and j such that prices[i] + prices[j] == target
Print the list of the two indices as the final output
💡 Why This Matters
🌍 Real World
Finding two items in a list that add up to a specific value is useful in shopping apps, budgeting tools, and financial software.
💼 Career
This problem is a common coding interview question and helps develop skills in using hash maps for efficient searching.
Progress0 / 4 steps
1
Create the list of prices
Create a list called prices with these exact values: [2, 7, 11, 15]
DSA Python
Hint

Use square brackets to create a list and separate numbers with commas.

2
Set the target sum
Create a variable called target and set it to 9
DSA Python
Hint

Use the equals sign to assign the value 9 to the variable target.

3
Find two indices using a dictionary
Create an empty dictionary called seen. Use a for loop with variables i and num to iterate over enumerate(prices). Inside the loop, check if target - num is in seen. If yes, create a list result with seen[target - num] and i, then break the loop. Otherwise, add num as a key and i as its value to seen.
DSA Python
Hint

Use a dictionary to remember numbers and their positions. Check if the complement exists before adding the current number.

4
Print the result
Print the variable result to show the two indices found.
DSA Python
Hint

Use the print function to display the list of indices.