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.

JavascriptData Integrity

Code

javascriptsnippet
13 lines
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

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.