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.
Saved automatically
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.
Related Questions in Data Structures & Algorithms
How to detect a cycle in a Linked List using Floyd's Cycle-Finding Algorithm?
Intermediate level • 516 views
When would you choose a hash map instead of an array for lookups?
Easy level • 6 views
How do a stack and a queue differ, and where would each be useful?
Easy level • 6 views
When does breadth-first search find a shortest path, and when is it the wrong choice?
Medium level • 5 views
What is the difference between BFS (Breadth-First Search) and DFS (Depth-First Search) and their space-time complexities?
Intermediate level • 4 views