Easy Hashing

Two Sum

Receives an array of integers and a target value, and returns the indices of the two numbers that add up to the target. It scans the array once, keeping a hash map from each value seen so far to its index: at each element it computes the complement (target minus the current value) and checks whether that complement is already a key in the map — if so, the pair is found immediately; otherwise the current value is recorded in the map and the scan continues. This trades a little extra memory for speed, running in O(n) instead of the O(n²) of checking every pair. Returns a new array with the two matching indices in the order [earlier, later]; returns an empty array when no such pair exists.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References