All notes

2026-08-14

Solving Two Sum: a simple DSA approach in C++ and Python

A clear walkthrough of the Two Sum problem, the brute-force baseline, and the hash-map approach that reduces the time complexity to O(n).

Solving Two Sum: a simple DSA approach in C++ and Python

Two Sum is a useful starting point for practising Data Structures and Algorithms because it tests an important habit: before writing code, identify the repeated work in the straightforward solution.

The problem

Given an array of integers and a target value, return the indices of two numbers whose sum equals the target.

For example, for [2, 7, 11, 15] and target 9, the answer is indices [0, 1] because 2 + 7 = 9.

Start with the baseline

The direct approach checks every pair. It is easy to understand, but nested loops make its time complexity O(n²).

Improve it with a hash map

As I scan the array, I calculate the value needed to reach the target. If that value has already appeared, I have found the answer. Otherwise, I store the current number and its index for a later lookup.

This reduces the expected lookup time to O(1), making the overall approach O(n) time with O(n) extra space.

C++

#include <unordered_map>
#include <vector>
using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {
  unordered_map<int, int> seen;

  for (int i = 0; i < nums.size(); i++) {
    int needed = target - nums[i];
    if (seen.count(needed)) return {seen[needed], i};
    seen[nums[i]] = i;
  }

  return {};
}

Python

def two_sum(nums, target):
    seen = {}

    for index, value in enumerate(nums):
        needed = target - value
        if needed in seen:
            return [seen[needed], index]
        seen[value] = index

    return []

What I take from this problem

The important lesson is not memorising one solution. It is learning to ask: what information can I store now so I do not need to search for it again later? That pattern appears in many DSA problems.

I am currently strengthening my DSA practice by focusing on problem understanding, complexity analysis, and writing clean C++ and Python solutions.