18
OctTwo 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.
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.