In this article we will learn about LeetCode First question Two Sum in detail with optimized solution with Example.
- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
- You may assume that each input would have exactly one solution, and you may not use the same element twice.
- You can return the answer in any order.

Table of Contents
Brute Force Code
Java Example
class Solution {
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[] {};
}
}
// 2023
C++ Example
class Solution {
public:
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 {};
}
};
// 2023
Complexity :
- Time complexity: O(N2)
- Space Complexity: O(1)
Optimized Code
Java Optimized Example
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numToIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (numToIndex.containsKey(target - nums[i])) {
return new int[] {numToIndex.get(target - nums[i]), i};
}
numToIndex.put(nums[i], i);
}
return new int[] {};
}
}
C++ Optimized Example
#include <unordered_map>
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mp;
for(int i = 0; i < nums.size(); i++){
if(mp.find(target - nums[i]) == mp.end())
mp[nums[i]] = i;
else
return {mp[target - nums[i]], i};
}
return {-1, -1};
}
};
Complexity :
Time complexity: O(N);
Space Complexity: O(N);
I hope you like this Amazing Two Sum article.🙂
Also Read :
- Top 10 VS Code extensions
- React Complete Course
- Web Designing Roadmap 2023
- Android Developer Roadmap 2023
- Full-Stack Developer Roadmap 2023