← Back to index
EasyPython2 min read

Two Sum

find two indices whose values sum to target using hash map for O(n) lookup.

hash-tablearrays

Problem link

View on LeetCode

Solutions in this repo

  • Python../two sum/solution.pyPython solution

use hash map to store number → index mapping. for each number, check if complement (target - num) exists in map. if found, return both indices.

single pass through array: check complement before adding current number to map. this handles cases where same number appears twice.

complexity

O(n) time for single pass, O(n) space for hash map. classic hash map problem.