Given an array and a target, find two indices that sum to the target
Reported in MongoDB USA engineering loops. Classic array + hash map problem testing optimal time–space trade-offs.
Interview scenario
Context for MongoDB candidates:
Return the indices of the two numbers. Exactly one solution exists; you may not use the same element twice. Aim for better than O(n²).
Model answer
Try answering aloud first
Cover trade-offs, structure, and a concrete example before revealing the baseline response.
How to frame this at MongoDB: Connect your answer to measurable impact, clarity of thought, and trade-offs the team cares about. Below is a strong baseline response you can adapt with your own project examples.
Use a hash map storing value → index for elements already seen. For each nums[i], compute complement = target - nums[i]. If complement exists in the map, return [map[complement], i]; otherwise store nums[i] → i.
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(nums[i], i);
}
}Complexity: O(n) time, O(n) space. Sorting + two pointers achieves O(n log n) time and O(1) extra space if indices are not required.
Discuss handling duplicates, integer overflow in other languages, and how hash maps give O(1) average lookup versus linear scan.
Discussion
Comments (0)
Share how this question came up in your loop, or add tips for others preparing.
Log in to comment on this question.