October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How the Two Sum Hash Map Scan Works in C++, Java, and Elixir

Solve LeetCode 1 Two Sum with one shared hash-map invariant, shown in imperative C++ and Java and a functional Elixir reducer.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

LeetCode 1 Two Sum can be solved in expected O(n) time with a hash map. As you scan the array, keep each previously seen number and its index; for the current number, look up the complement needed to reach the target. C++ and Java express this with a loop and a mutable local map, while Elixir can carry the same state through a reducer.

What Two Sum asks you to return

Given an array of integers and a target, return the indices of two distinct elements whose values add to the target. The prompt guarantees exactly one solution and allows the two indices in either order. The example with [3,3] and target 6 demonstrates why equal values at different positions are valid. The array length is 2 through 104; values and target range from −109 through 109. LeetCode’s Two Sum statement

As an Amazon Associate I earn from qualifying purchases.

This is not Two Sum II: that separate problem gives a sorted array, asks for one-based indices, and requires constant extra space. Two Sum I does not promise sorted input.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How the hash map finds the complement

For each value x at index i, calculate target - x. If that complement is already in the map, its stored index and i are the answer. If it is absent, store x with index i and continue.

  1. Start with an empty map from number to index.
  2. Scan the input from left to right, one index at a time.
  3. Look for the complement before inserting the current value. The map then contains only earlier positions, so the current element cannot be paired with itself.
  4. If the complement is found, return its index and the current index. Otherwise, record the current value and index.

Checking first still handles duplicates: with [3,3], the first 3 is stored; when the second 3 is reached, its complement is found at the first index.

C++: use a mutable local map

#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 < static_cast<int>(nums.size()); ++i) {
int complement = target - nums[i];
auto it = seen.find(complement);
if (it != seen.end()) {
return {it->second, i};
}
seen[nums[i]] = i;
}
return {};
}

The map stores the number as the key and its earlier index as the value, matching the required output directly. std::unordered_map is a hash table and does not keep entries sorted; its search and insertion are average constant time. cppreference’s unordered_map reference

The input values are signed, so keep the arithmetic signed too. The documented bounds make int sufficient on the stated LeetCode C++ platform; avoid converting values to an unsigned type, which can change the meaning of subtraction.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Java: the same invariant with HashMap

import java.util.HashMap;
import java.util.Map;

class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (seen.containsKey(complement)) {
return new int[] { seen.get(complement), i };
}
seen.put(nums[i], i);
}
return new int[0];
}
}

containsKey checks whether an earlier index exists; get retrieves it, and put records the current value after the check. Java’s HashMap documents constant-time basic get and put when the hash function disperses elements properly, and it makes no ordering guarantee. Oracle’s Java SE 25 HashMap API

Elixir: carry state through a reducer

Elixir can express the scan as a reduction over values paired with their indices. The accumulator holds both the map of earlier values and either no answer or the answer. Each pass returns the next accumulator; when it finds the complement, it retains the answer and later passes leave it unchanged.

def two_sum(nums, target) do
nums
|> Enum.with_index()
|> Enum.reduce({%{}, nil}, fn {x, i}, {seen, answer} ->
if answer do
{seen, answer}
else
complement = target - x

case Map.fetch(seen, complement) do
{:ok, j} -> {seen, [j, i]}
:error -> {Map.put(seen, x, i), nil}
end
end
end)
|> elem(1)
end

The reducer makes state changes explicit: a branch either returns the found indices or carries forward the map produced by Map.put/3. This version scans the remaining indexed values after finding a pair, but does not change the saved answer. Elixir maps are unordered key-value structures with unique keys, and Map.put/3 adds or replaces the value for a key. Elixir’s Map reference

This is a functional way to express the same traversal, not a different algorithm. Since the prompt guarantees a solution, the function returns a pair of indices for valid inputs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why these implementations are expected O(n)

Each array position is processed once, and each pass performs a bounded number of map operations. Under the hash-table assumptions documented for these structures, the scan is expected or average O(n), with O(n) additional space in the number of distinct values stored. This is not an unconditional worst-case O(n) guarantee. By contrast, testing every pair takes O(n²) time and O(1) additional space. The official prompt’s follow-up asks for an algorithm below O(n²), and its hints point toward looking up the complement with additional storage. LeetCode Two Sum

Best Value

Platform versions and portability

LeetCode’s Help Center article, updated March 2, 2026, lists C++ as clang 19 with C++23 and libstdc++ from GCC 14, Java as OpenJDK 25, and Elixir 1.17 with Erlang/OTP 26. These are platform environment details and can change. LeetCode language environments

The Elixir Map reference linked above is labeled v1.20.4, not the 1.17 version listed for LeetCode. The code illustrates the reducer approach; the documentation versions should not be treated as identical or as proof that this exact snippet has been tested in LeetCode’s runtime.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.