|
| 1 | +# [Two Sum](https://leetcode.com/problems/two-sum/) |
| 2 | + |
| 3 | +## Question Description |
| 4 | +Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. You may assume that each input would have exactly one solution, and you may not use the same element twice. |
| 5 | + |
| 6 | +--- |
| 7 | + |
| 8 | +## Constraints |
| 9 | +- `2 <= nums.length <= 10^4` |
| 10 | +- `-10^9 <= nums[i] <= 10^9` |
| 11 | +- `-10^9 <= target <= 10^9` |
| 12 | +- Only one valid answer exists. |
| 13 | + |
| 14 | +--- |
| 15 | + |
| 16 | +## Approach |
| 17 | +Use a HashMap to store visited numbers and their indices. For each number, check if `target - current` exists in the map. If it does, return the stored index and current index. Otherwise, store the current number with its index. |
| 18 | + |
| 19 | +This approach works because we need to find two numbers that sum to target, and using a hashmap allows O(1) lookups for the complement. Alternative approaches like brute force (O(n²)) would be too slow for large inputs, and sorting would require additional complexity to track original indices. |
| 20 | + |
| 21 | +--- |
| 22 | + |
| 23 | +## Dry Run |
| 24 | +Example Input: `nums = [2,7,11,15], target = 9` |
| 25 | + |
| 26 | +Step-by-step execution: |
| 27 | +- i=0, nums[0]=2, complement=7, map is empty, put (2,0) in map |
| 28 | +- i=1, nums[1]=7, complement=2, map contains 2, return [0,1] |
| 29 | + |
| 30 | +Final Answer = `[0,1]` |
| 31 | + |
| 32 | +--- |
| 33 | + |
| 34 | +## Solution |
| 35 | +```java |
| 36 | +class Solution { |
| 37 | + public int[] twoSum(int[] nums, int target) { |
| 38 | + Map<Integer, Integer> map = new HashMap<>(); |
| 39 | + for (int i = 0; i < nums.length; i++) { |
| 40 | + int complement = target - nums[i]; |
| 41 | + if (map.containsKey(complement)) { |
| 42 | + return new int[] { map.get(complement), i }; |
| 43 | + } |
| 44 | + map.put(nums[i], i); |
| 45 | + } |
| 46 | + return new int[] {}; |
| 47 | + } |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +--- |
| 52 | + |
| 53 | +## Time and Space Complexity |
| 54 | +- **Time Complexity:** O(n) - single pass through the array |
| 55 | +- **Space Complexity:** O(n) - hashmap stores up to n elements in worst case |
0 commit comments