Two Sum

Algorithms
Easy
Google
104.5K views

Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`.

Why Interviewers Ask This

Google asks the Two Sum problem to evaluate a candidate's ability to optimize time complexity beyond brute force. Interviewers specifically look for proficiency in using hash maps to trade space for speed, demonstrating logical thinking and the capacity to identify edge cases like duplicate elements or negative numbers efficiently.

How to Answer This Question

1. Clarify Requirements: Immediately confirm if input arrays are sorted, if duplicates exist, or if multiple solutions are possible. Google values precise communication before coding. 2. Discuss Brute Force: Briefly mention the O(n^2) nested loop approach to establish a baseline, then explain why it fails on large datasets typical at scale. 3. Propose Hash Map Strategy: Articulate the plan to use a hash map (dictionary) to store visited numbers and their indices. Explain that this allows constant-time lookups for the complement value. 4. Walk Through Logic: Describe iterating once through the array, calculating the target minus current number, checking the map, and updating the map if not found. 5. Analyze Complexity: Conclude by explicitly stating the Time Complexity is O(n) and Space Complexity is O(n), justifying why this is optimal for this specific constraint.

Key Points to Cover

  • Demonstrating immediate recognition of the O(n) hash map optimization over O(n^2) brute force
  • Clearly explaining the logic of storing complements versus current values during iteration
  • Handling edge cases such as finding the solution on the very first or last element
  • Explicitly articulating both Time and Space complexity analysis at the conclusion
  • Communicating thought process clearly while writing code, reflecting Google's collaborative culture

Sample Answer

To solve the Two Sum problem efficiently, I first clarify constraints. Assuming an unsorted array with potential duplicates, the brute-force method of comparing every pair would take O(n^2) time, which is inefficient for…

Common Mistakes to Avoid

  • Failing to handle the case where the same element cannot be used twice, leading to incorrect index returns
  • Ignoring the requirement to return indices instead of the actual values, causing logic errors
  • Implementing a two-pass solution that unnecessarily iterates the array twice instead of combining steps
  • Not discussing the space-time tradeoff, missing an opportunity to demonstrate system design awareness

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 145 Google questions