Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up
Two Sum Problem

Two Sum Problem

Beginner 3 min read 23 Sep 2025 2.16K views
Two Sum Problem

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.

85% of top tech companies prioritize DSA expertise in hiring. Start your journey with our Free Data Structures and Algorithms Course now!

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.

Top developers are already moving into Solution Architect roles. If you stay just a “coder,” you’ll be stuck while they lead. Enroll now in our Java Solution Architect Certification and step up.

Test yourself in 5 minutes

Take the free Datastructures skill challenge to see your strengths and the gaps to fix next.

Start the challenge
Share LinkedIn X Facebook WhatsApp

About the author

Amit Kumar Ghosh

Amit Kumar Ghosh

SDE and Mentor

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.

Keep learning

Courses that go with this tutorial