Verified Jobs Live
Data Structures & Algorithms Medium Level ~3 min read

How can you find two indices whose values sum to a target in one pass?

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Model Answer & Deep-Dive Explanation

Keep a map from previously seen values to their indices. For each element, check whether its complement, target minus current value, has already appeared. Check before inserting so the same element cannot be used twice. This naturally handles duplicate values at different positions, such as two 3s for target 6. Expected time is O(n), with O(n) extra space under ordinary hash-map assumptions. State what to retu when no pair exists and whether one pair or all pairs are required.