1. Two Sum
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Arrays & Hashing
- Time
- O(n)
- Space
- O(n)
Standard Solution (C++)
SummaryGiven an integer array and a target value, find the indices of the two elements that add up to the target, guaranteeing exactly one valid answer exists.
Approach
- Use a hash map to store each number's index as you iterate through the array once.
- For each element, compute its complement (target minus current value) and check if it already exists in the map.
- If the complement is found, return the current index and the stored complement index immediately.
- This avoids the O(n²) brute-force nested loop by trading linear space for constant-time lookups.
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// Maps value -> index for elements seen so far
unordered_map<int, int> seen;
for (int i = 0; i < (int)nums.size(); ++i) {
int complement = target - nums[i];
// If complement already seen, we found our pair
auto it = seen.find(complement);
if (it != seen.end()) {
return {it->second, i};
}
// Record current value and its index
seen[nums[i]] = i;
}
return {}; // Guaranteed by problem constraints to never reach here
}
}; Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int, int> umap;
int n = nums.size();
for (int i = 0; i < n; ++i) {
int complement = target - nums[i];
if (umap.count(complement)) // O(1)
return {i, umap[complement]};
umap[nums[i]] = i; // O(1)
}
return {}; // No solution found
}
};
// Time Complexity: O(n). Single pass through the array.
// Space Complexity: O(n). In the worst case, the hash map stores all elements. Time O(n) Space O(n)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.