Two Sum Problem

01 Sep 2025
Beginner
47 Views
2 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

Two Sum Problem

Two Sum Problem is a classic algorithmic problem where you are given an array of integers and a target sum. Your task is to find two numbers in the array that add up to the target and return their indices. Each input has exactly one solution, and you cannot use the same element twice.

Example:

  • Input: nums = [2, 7, 11, 15], target = 9
  • Output: [0, 1]
  • Explanation: nums[0] + nums[1] = 2 + 7 = 9

Logic

Enter an array of numbers (comma-separated) and a target sum to find the indices of two numbers that add up to the target.

Program (Python - Hash Table Approach)

The following Python code uses a hash table to solve the Two Sum Problem efficiently with O(n) time complexity.


twoSum(nums, target):
    hash_table = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hash_table:
            return [hash_table[complement], i]
        hash_table[num] = i
    return []

# Example usage
nums = [2, 7, 11, 15]
target = 9
print(twoSum(nums, target))  # Output: [0, 1]

Output

For the input nums = [2, 7, 11, 15] and target = 9, the output is:

[0, 1]

Explanation:

The numbers at indices 0 and 1 (2 and 7) add up to the target 9.

Take our Datastructures skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Amit Kumar Ghosh (SDE and Mentor at Scholarhat)

As a software developer with a wealth of experience, he brings a unique combination of technical acumen and a passion for mentorship to my role. With 6 years of experience, he has honed the skills in C/C++, Java, Python, SQL, C#, JavaScript, React, Java Spring etc. and has a proven track record of delivering high-quality, scalable software solutions and core Computer fundamental knowledge DSA, OOPs, CN, OS etc.

As a teacher, his approach revolves around interactive techniques, prioritizing hands-on learning and real-world projects. He explains concepts clearly, offer practical examples, and encourage questions to foster a supportive environment.
Live Training - Book Free Demo
ASP.NET Core Certification Training
06 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Advanced Full-Stack .NET Developer with Gen AI Certification Training
06 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Azure AI Foundry Certification Training
06 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
React Certification Training
07 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Azure Developer Certification Training
08 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this