# leet code : Two sum Problem solution – Java || CPP || JavaScript || Python

Sure, let’s solve the “Two Sum” problem using different approaches in C++, Python, Java, and JavaScript, and add some humor along the way! We’ll explore the bruteforce, hashmap, two hashmap, and two-pointer methods for each language.

Time Complexity:

• Bruteforce: O(n^2)
• HashMap: O(n)
• Two Pass HashMap: O(n)
• Two Pointer: O(n log n)

## C++:

### 1. Brute Force Approach:

``````vector<int> twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {}; // No solution found!
}``````

Notice: This approach has a time complexity of O(n^2), which isn’t very efficient.

### 2. HashMap Approach:

``````vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> numToIndex;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (numToIndex.find(complement) != numToIndex.end()) {
return {numToIndex[complement], i};
}
numToIndex[nums[i]] = i;
}
return {}; // No solution found!
}``````

Interesting Fact: This approach has a time complexity of O(n), which is much faster than the brute force method.

### 3. Two Pass HashMap Approach:

``````class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> numToIndex;

// First pass: Populate the HashMap
for (int i = 0; i < nums.size(); i++) {
numToIndex[nums[i]] = i;
}

// Second pass: Check for the complement
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (numToIndex.find(complement) != numToIndex.end() && numToIndex[complement] != i) {
return {i, numToIndex[complement]};
}
}

return {};
}
};
``````

Notice: This approach uses two hashmaps, which might be overkill for this problem.

### 4. Two-Pointer Approach:

``````vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int, int>> numsWithIndex;
for (int i = 0; i < nums.size(); i++) {
numsWithIndex.push_back({nums[i], i});
}
sort(numsWithIndex.begin(), numsWithIndex.end());
int left = 0, right = nums.size() - 1;
while (left < right) {
int sum = numsWithIndex[left].first + numsWithIndex[right].first;
if (sum == target) {
return {numsWithIndex[left].second, numsWithIndex[right].second};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return {}; // No solution found!
}``````

Interesting Fact: This approach requires sorting, so it has a time complexity of O(n*log(n)).

## Python:

I’ll provide Python code snippets for the same approaches.

### 1. Brute Force Approach (Python):

``````def twoSum(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []  # No solution found!``````

### 2. HashMap Approach (Python):

``````def twoSum(nums, target):
numToIndex = {}
for i, num in enumerate(nums):
complement = target - num
if complement in numToIndex:
return [numToIndex[complement], i]
numToIndex[num] = i
return []  # No solution found!``````

### 3. Two Pass Hashmap Approach (Python):

``````class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_to_index = {}

# First pass: Populate the dictionary
for i, num in enumerate(nums):
num_to_index[num] = i

# Second pass: Check for the complement
for i, num in enumerate(nums):
complement = target - num
if complement in num_to_index and num_to_index[complement] != i:
return [i, num_to_index[complement]]

return []
``````

### 4. Two-Pointer Approach (Python):

``````def twoSum(nums, target):
numsWithIndex = [(num, i) for i, num in enumerate(nums)]
numsWithIndex.sort()
left, right = 0, len(nums) - 1
while left < right:
num_sum = numsWithIndex[left] + numsWithIndex[right]
if num_sum == target:
return [numsWithIndex[left], numsWithIndex[right]]
elif num_sum < target:
left += 1
else:
right -= 1
return []  # No solution found!``````

## Java:

### 1. Brute Force Approach (Java):

``````public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return new int[]{}; // No solution found!
}``````

### 2. HashMap Approach (Java):

``````public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numToIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (numToIndex.containsKey(complement)) {
return new int[] {numToIndex.get(complement), i};
}
numToIndex.put(nums[i], i);
}
return new int[]{}; // No solution found!
}``````

### 3. Two Pass Hashmap Approach (Java):

``````class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numToIndex = new HashMap<>();

// First pass: Populate the HashMap
for (int i = 0; i < nums.length; i++) {
numToIndex.put(nums[i], i);
}

// Second pass: Check for the complement
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (numToIndex.containsKey(complement) && numToIndex.get(complement) != i) {
return new int[]{i, numToIndex.get(complement)};
}
}

return new int;
}
}``````

### 4. Two-Pointer Approach (Java):

``````public int[] twoSum(int[] nums, int target) {
int[][] numsWithIndex = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
numsWithIndex[i] = nums[i];
numsWithIndex[i] = i;
}

Arrays.sort(numsWithIndex, Comparator.comparingInt(arr -> arr));
int left = 0, right = nums.length - 1;
while (left < right) {
int sum = numsWithIndex[left] + numsWithIndex[right];
if (sum == target) {
return new int[] {numsWithIndex[left], numsWithIndex[right]};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[]{}; // No solution found!
}``````

## JavaScript:

### 1. Brute Force Approach (JavaScript):

``````function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return []; // No solution found!
}``````

### 2. HashMap Approach (JavaScript):

``````function twoSum(nums, target) {
const numToIndex = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (numToIndex.has(complement)) {
return [numToIndex.get(complement), i];
}
numToIndex.set(nums[i], i);
}
return []; // No solution found!
}``````

### 3. Two Pass HashMap Approach (JavaScript):

``````var twoSum = function(nums, target) {
const numToIndex = {};

// First pass: Populate the object
for (let i = 0; i < nums.length; i++) {
numToIndex[nums[i]] = i;
}

// Second pass: Check for the complement
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (complement in numToIndex && numToIndex[complement] !== i) {
return [i, numToIndex[complement]];
}
}

return [];
};
``````

### 4. Two-Pointer Approach (JavaScript):

``````function twoSum(nums, target) {
const numsWithIndex = nums.map((num, index) => [num, index]);
numsWithIndex.sort((a, b) => a - b);
let left = 0, right = nums.length - 1;
while (left < right) {
const sum = numsWithIndex[left] + numsWithIndex[right];
if (sum === target) {
return [numsWithIndex[left], numsWithIndex[right]];
} else if (sum < target) {
left++;
} else {
right--;
}
}
return []; // No solution found!
}``````

And there you have it! Four different programming languages, four approaches to solving the “Two Sum” problem, and hopefully a smile on your face as well! Remember, choosing the right approach depends on the specific requirements and constraints of your problem. Happy coding! I am Nilesh,3+ years Exp of SEO, content writing, and keyword research. Also rocks it as a software dev with skills in OS, web dev, Flask, Python, C++, data structures, and algorithms. 3 on Leetcode, 5*on Hackerrank more platform.

### 15 thoughts on “leet code : Two sum Problem solution – Java || CPP || JavaScript || Python”

1. bro you solved it by class method and python code for this problem is simpler but i cant understand why we use class and all so please refer me article so that i can understand is use.
Thankyou.

2. The Class Solution is Only For the Leetcode .Which call the function inside the class

3. the CPP code is not working and you didn’t explain the method using hashmaps(the method used in the code)

4. Bro, python code is correct —

5. Itís nearly impossible to find well-informed people for this subject, however, you seem like you know what youíre talking about! Thanks

6. Please write the dart code for this problem

7. Wһat’s up to every one, it’s truly a good for me to рay a
quick visit this site, it contains preci᧐us Information.

8. what if Input: nums = [0,9,7,2,13,11], target = 9
what will be the output ?

9. the quetion has not include this condition but both [0,1] and [2,3] are correct answer.

10. Your python hash table solution is not n… it’s n^2.
Checking if an element is in a dict is amortized worst case O(n). You perform this check n times. Therefore n^2…
https://wiki.python.org/moin/TimeComplexity

Mine as well just brute force it

11. 0,1

12. I do not even understand how I ended up here, but I assumed this publish used to be great

13. You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!

14. I am truly thankful to the owner of this web site who has shared this fantastic piece of writing at at this place.

15. Very nice article, well written. Thank you, helps a lot!

If someone is looking for a video solution, I recommend you guys to go through this YouTube video on Two Sum. They have explained it in a very simple and easy to understand manner. This for sure has to be the best video on YouTube on Two Sum problem.