1. Two Sum
My accepted C++ and Python solution to LeetCode problem 1, Two Sum, running in 0ms.
- Difficulty: Easy
- C++
- Python
- Runtime 0ms
- Memory 15MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
C++
Accepted on LeetCode — runtime 0ms, memory 15MB, accepted 2025-12-28.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mp;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (mp.count(complement)) {
return {mp[complement], i};
}
mp[nums[i]] = i;
}
return {};
}
};Python
Accepted on LeetCode — runtime 0ms, memory 13.2MB, accepted 2025-12-23.
class Solution(object):
def twoSum(self, nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i