migrate 392 questions to pattern format
This commit is contained in:
@@ -7,7 +7,8 @@ categories:
|
||||
- arrays
|
||||
- hash-tables
|
||||
patterns:
|
||||
- two-pointers
|
||||
- slug: hashing
|
||||
is_optimal: true
|
||||
|
||||
function_signature: "def two_sum(nums: list[int], target: int) -> list[int]:"
|
||||
|
||||
@@ -135,6 +136,34 @@ explanation:
|
||||
time_complexity: "O(n). We traverse the array once, and each hash map lookup/insert is O(1) on average."
|
||||
space_complexity: "O(n). In the worst case, we store all n elements in the hash map before finding a match (e.g., when the solution is the last two elements)."
|
||||
|
||||
pattern_comparison: |
|
||||
**Hash Map vs Two Pointers: Different Problems, Different Patterns**
|
||||
|
||||
Two Sum is often confused with sorted-array two-pointer problems, but they require different approaches:
|
||||
|
||||
| Approach | Time | Space | Requires Sorted Input? | Returns |
|
||||
|----------|------|-------|------------------------|---------|
|
||||
| **Hash Map** | O(n) | O(n) | No | Original indices |
|
||||
| **Two Pointers** | O(n) | O(1) | Yes | Values or sorted indices |
|
||||
| **Brute Force** | O(n²) | O(1) | No | Indices |
|
||||
|
||||
**Why Hash Map is optimal for this problem:**
|
||||
- We need **original indices**, not just values
|
||||
- Sorting would lose index information (or require O(n) extra space to track)
|
||||
- Hash map gives O(1) lookup while preserving indices naturally
|
||||
|
||||
**When Two Pointers would apply:**
|
||||
- If the array is already sorted
|
||||
- If we only need to find the values (not indices)
|
||||
- In space-constrained environments where O(n) extra space is prohibitive
|
||||
|
||||
**The Two Sum pattern family:**
|
||||
- **Two Sum** (unsorted): Hash map for complement lookup
|
||||
- **Two Sum II** (sorted): Two pointers from both ends
|
||||
- **3Sum/4Sum**: Sort + Two pointers (indices don't matter)
|
||||
|
||||
Remember: The right pattern depends on what the problem asks for and what guarantees you have about the input.
|
||||
|
||||
solutions:
|
||||
- approach_name: One-Pass Hash Map
|
||||
is_optimal: true
|
||||
|
||||
Reference in New Issue
Block a user