05
SepTwo Sum Problem
01 Sep 2025
Beginner
47 Views
2 min read
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.