Two Sum: Find Indices That Add Up to Target
Find two array indices whose values sum to a target in one pass using a hash map, with validation for non-numeric input.
Code
export function twoSum(numbers, target) {
if (!Array.isArray(numbers)) throw new TypeError("numbers must be an array");
if (!Number.isFinite(target)) throw new TypeError("target must be a finite number");
const seen = new Map();
for (let index = 0; index < numbers.length; index += 1) {
const value = numbers[index];
if (!Number.isFinite(value)) throw new TypeError("numbers must be finite at index " + index);
const complement = target - value;
if (seen.has(complement)) return [seen.get(complement), index];
seen.set(value, index);
}
return null;
}How the snippet works
Count the function twoSum as the entire surface area of Two Sum: Find Indices That Add Up to Target.
The one repetition in this snippet is the loop for (let index = 0; index < numbers.length; index += 1). The code refuses to proceed on bad state and throws TypeError at its guard.
The result is a fresh construction, so callers can keep their originals.
Applying it
The primary signature is export function twoSum(numbers, target)
twoSum is the public entry point; everything else in the file exists to support it.
Statements that matter
if (!Number.isFinite(value)) throw new TypeError("numbers must be finite at index " + index);
if (!Number.isFinite(target)) throw new TypeError("target must be a finite number");
if (!Array.isArray(numbers)) throw new TypeError("numbers must be an array");
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does `twoSum` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- How are precondition violations signaled?
- Validation comes first — `TypeError` marks the failure, before any partial work happens.
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `twoSum` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.