|
| 1 | +# Two Sum |
| 2 | + |
| 3 | +## LeetCode Problem |
| 4 | +- Problem Number: 1 |
| 5 | +- Problem Link: https://leetcode.com/problems/two-sum/ |
| 6 | +- Difficulty: Easy |
| 7 | +- Topics: Array, Hash Table |
| 8 | + |
| 9 | +## Problem Description |
| 10 | +Given an array of integers `nums` and an integer `target`, return indices of the two numbers in the array that add up to the `target`. |
| 11 | + |
| 12 | +You may assume that: |
| 13 | +- Each input has exactly one solution |
| 14 | +- You may not use the same element twice |
| 15 | +- You can return the answer in any order |
| 16 | + |
| 17 | +## Examples |
| 18 | + |
| 19 | +### Example 1: |
| 20 | +``` |
| 21 | +Input: nums = [2,7,11,15], target = 9 |
| 22 | +Output: [0,1] |
| 23 | +Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. |
| 24 | +``` |
| 25 | + |
| 26 | +### Example 2: |
| 27 | +``` |
| 28 | +Input: nums = [3,2,4], target = 6 |
| 29 | +Output: [1,2] |
| 30 | +``` |
| 31 | + |
| 32 | +### Example 3: |
| 33 | +``` |
| 34 | +Input: nums = [3,3], target = 6 |
| 35 | +Output: [0,1] |
| 36 | +``` |
| 37 | + |
| 38 | +## Constraints |
| 39 | +- 2 <= nums.length <= 10⁴ |
| 40 | +- -10⁹ <= nums[i] <= 10⁹ |
| 41 | +- -10⁹ <= target <= 10⁹ |
| 42 | +- Only one valid answer exists |
| 43 | + |
| 44 | +## Solution Approach |
| 45 | +There are two main approaches to solve this problem: |
| 46 | + |
| 47 | +### 1. Hash Table Approach (Optimal) |
| 48 | +- Time Complexity: O(n) |
| 49 | +- Space Complexity: O(n) |
| 50 | +- Algorithm: |
| 51 | + 1. Create a HashMap to store complement values |
| 52 | + 2. For each number in the array: |
| 53 | + - Calculate complement (target - current number) |
| 54 | + - If complement exists in HashMap, return [complementIndex, currentIndex] |
| 55 | + - Add current number and its index to HashMap |
| 56 | + |
| 57 | +### 2. Brute Force Approach |
| 58 | +- Time Complexity: O(n²) |
| 59 | +- Space Complexity: O(1) |
| 60 | +- Algorithm: |
| 61 | + 1. Use nested loops to try every possible pair |
| 62 | + 2. Check if any pair sums to target |
| 63 | + 3. Return indices when found |
| 64 | + |
| 65 | +## Common Pitfalls |
| 66 | +1. Using the same element twice |
| 67 | +2. Not considering negative numbers |
| 68 | +3. Forgetting to check if complement exists before adding to HashMap |
| 69 | +4. Returning wrong order of indices |
| 70 | + |
| 71 | +## Related Problems |
| 72 | +- 167: Two Sum II - Input Array Is Sorted |
| 73 | +- 170: Two Sum III - Data structure design |
| 74 | +- 653: Two Sum IV - Input is a BST |
0 commit comments