Two Sum Leetcode problem is one of the most asked question in Data Structure and Analysis ( DSA ) interviews. Candidate try to solve it with their prefered programming language but most of the candidate choose Brute Force approach but that will be big mistake.
You’ll learn in this tutorial How we can solve this problem with Hash Map and O(n) Time complexity.
We will solve this problem using C++, Java, Python , and JavaScript programming language.
This problem helps to understand about you knowledge of :
- the array traversal skill.
- your logical thinking.
- your knowledge of time & space complexity.
- Hash map concept.
Problem Statement

You are given:
- An array of integers
nums - An integer
target
Your task is to return the indices of the two numbers such that their sum equals the target.
Important Rules
- Each input has exactly one solution
- You cannot use the same element twice
- You can return the answer in any order
Brute Force Approach ( Not Recommended )
This approach is not recommended because its time complexity is O(n²). In technical interviews, inefficient solutions like this are generally not preferred and may negatively impact your evaluation.
Idea
- Use two for loops
- Try every possible pair
- Check if their sum equals
targetthen return indices.
for i from 0 to n:
for j from i+1 to n:
if nums[i] + nums[j] == target:
return [i, j]
So, Interviewers expect better optimized sollution in Interview.
Optimized Solution – Using Hash Map – Explanation & Animations
Key Idea
Instead of checking every pair using two for loops:
- Store numbers in a hash map
- For each number, calculate the required complement
complement = target - currentNumber
If the complement already exists in the HashMap,
You found the answer immediately.
Algorithm to solve Two Sum Leetcode Problem
- Start
- Initialize an Empty hash map
- Iterate the give array using for loop from i = 0 to i < length_of_nums
- complement = target – nums[i]
- if complement already present within Hash map, then
- return [ map.get(complement), current_index ]
- else, set index to map
- End
Let’s understand this by an Animation

Solution Using C++ , Java, Python , and JavaScript
vector<int> twoSum(vector<int>& nums, int target) {
// Initialize an empty hash map
unordered_map<int, int> map;
// Iterate through the array
for (int i = 0; i < nums.size(); i++) {
// Calculate the complement value
int complement = target - nums[i];
// Check if complement exists in map
if (map.find(complement) != map.end()) {
return {map[complement], i};
}
// Otherwise, store current value with its index
map[nums[i]] = i;
}
return {};
}public int[] twoSum(int[] nums, int target) {
// Initialize an empty HashMap
HashMap<Integer, Integer> map = new HashMap<>();
// Iterate through the array
for (int i = 0; i < nums.length; i++) {
// Calculate the complement value
int complement = target - nums[i];
// Check if complement exists in map
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
// Otherwise, store current value with its index
map.put(nums[i], i);
}
return null;
}def twoSum(nums, target):
# Initialize an empty dictionary
map = {}
# Iterate through the list
for i in range(len(nums)):
# Calculate the complement value
complement = target - nums[i]
# Check if complement exists in dictionary
if complement in map:
return [map[complement], i]
# Otherwise, store current value with its index
map[nums[i]] = i
var twoSum = function(nums, target) {
//Initialize an Empty Array
const maps = new Map();
//Iterate loop
for ( let i=0;i<nums.length;i++ ) {
let complement = target - nums[i];
//if complement present
if ( maps.has( complement ) ) {
return [ maps.get( complement ), i ];
}
// Otherwise map current value to it's index
maps.set( nums[i], i );
}
};Conclusion
Thank you for reading this tutorial. Our motivation is to share DSA concepts and problem-solving techniques in a simple and easy-to-understand way. We hope this explanation helped you clearly understand the Two Sum problem and its optimized solution.
By practicing this problem, you strengthen:
- Time complexity optimization techniques using Hash Maps
- Logical and analytical thinking
- Problem-solving skills that are essential for DSA and coding interviews
We encourage you to explore more DSA problems and interview questions on our platform to build strong fundamentals and gain confidence for technical interviews.


