Bird
0
0
DSA Cprogramming~30 mins

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

Choose your learning style9 modes available
Two Sum Problem Classic Hash Solution
📖 Scenario: You are building a simple program to find two numbers in a list that add up to a target number. This is useful in many real-life cases, like finding two expenses that sum to a budget limit.
🎯 Goal: Build a program that uses a hash map (dictionary) to find two numbers in an array that add up to a given target. You will create the data, set the target, write the logic to find the pair, and print the result.
📋 What You'll Learn
Create an integer array called nums with the values 2, 7, 11, 15
Create an integer variable called target and set it to 9
Write a function called twoSum that takes nums, its size, and target, and returns the indices of the two numbers that add up to target
Print the indices returned by twoSum in the format: Indices: i, j
💡 Why This Matters
🌍 Real World
Finding two expenses that add up to a budget, matching pairs in shopping lists, or detecting pairs in data streams.
💼 Career
This problem is a common interview question and helps understand hash maps and efficient searching.
Progress0 / 4 steps
1
Create the array of numbers
Create an integer array called nums with the values 2, 7, 11, and 15. Also create an integer variable called numsSize and set it to 4.
DSA C
Hint

Use curly braces to list the numbers inside the array.

2
Set the target sum
Create an integer variable called target and set it to 9.
DSA C
Hint

Use int target = 9; to set the target value.

3
Write the twoSum function using a hash map
Write a function called twoSum that takes nums, numsSize, and target as parameters. Use a hash map (implemented with a simple array for this example) to find two indices i and j where nums[i] + nums[j] == target. Return the indices as a static array of size 2.
DSA C
Hint

Use an integer array as a hash map to store indices. Remember to handle zero-based indexing carefully.

4
Print the indices of the two numbers
Call the twoSum function with nums, numsSize, and target. Store the returned pointer in result. Then print the indices in the format: Indices: i, j where i and j are the two indices.
DSA C
Hint

Call twoSum and print the returned indices using printf.