Skip to main content

Two Sum

KANISHKA GUPTA
EditReport

Two Sum

Problem Statement​

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

Video Explanation​

Approach​

To solve this problem, we can use a hash map to store the numbers and their indices. As we iterate through the list, we check if the complement (target - current number) exists in the hash map.

Steps:​

  1. Initialize:

    • Create an empty hash map.
  2. Iterate:

    • For each number in nums, calculate its complement.
    • Check if the complement exists in the hash map.
    • If it exists, return the indices.
    • Otherwise, add the current number and its index to the hash map.
  3. Return:

    • If no solution is found, return an empty list.

Solutions​

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> numMap;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (numMap.count(complement)) {
return {numMap[complement], i};
}
numMap[nums[i]] = i;
}
return {};
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

Was this page helpful?

💬

Discuss this page

Have a question or spot something confusing in "Two Sum"? Ask below. Backed by GitHub Discussions—maintainers receive system notifications directly.