Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Examples
Input:
nums = [2,7,11,15], target = 9Output:
[0,1]Constraints
š” Hints
Hint 1
Use a hash map to store the elements and their indices.
Algorithm Complexity
Official asymptotic Big-O runtime and auxiliary memory analysis
Linear
Algorithmic Approach
Use a hash map to look up the complement (target - num) in O(1) time while iterating through the array.
Time ComplexityO(N)
Why:
Iterates through the array of N elements once, performing O(1) hash map lookups and insertions for complements.
Space ComplexityO(N)
Why:
In the worst case where no matching pair is found until the end, the hash map stores up to N elements.
Big-O Growth CurveLinear (O(N))
š Dry Run
Solutionā± O(N) | š¾ O(N)
Hash Map
Key
Value
Map is empty
Step 1 / 5