Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Easy Hash Map / Set High frequency Solution Available Practice Mode

Two Sum LeetCode Solution

Tags: #Array #Hash Map

Approach Summary

Store complement (target - num) in map as you iterate. If current num is already in map, you found the pair.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Hash Map / Set Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Hash Map / Set pattern.

Framework: Hash Map / Set • Interview Prep: Tested at FAANG • Explore all Hash Map / Set problems & invariants →

How to Recognize This Pattern

  • Find pair summing to target
  • Return indices

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Tags

Array Hash Map

Frequently Asked Questions

What is the optimal time and space complexity for Two Sum?
The optimal solution for Two Sum achieves O(n) runtime complexity and requires O(n) auxiliary space. The optimal hash map approach runs in O(n) time because checking and inserting into an unordered map runs in O(1) average time per element. Space complexity is O(n) in the worst case to store at most n - 1 elements in the map.
How do I identify that Two Sum requires the Hash Map / Set pattern?
In technical interviews, look for key problem signals: Find pair summing to target; Return indices. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Hash Map / Set strategy.
What critical edge cases must be handled in Two Sum?
Essential edge cases to verify include: Negative numbers and zeros in nums or target; Pairs located at the very beginning and end of the array; Duplicate values where target is exactly twice the value (handled because check precedes insertion); Large arrays where quadratic nested loops would exceed the time limit. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Two Sum?
Two Sum is a Easy-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Google, Facebook, Apple, Microsoft.
Buy me a coffee
Daily Practice
0/0