migrate 392 questions to pattern format

This commit is contained in:
2025-09-10 18:05:55 +01:00
parent 91e48f5239
commit 0ee388c420
402 changed files with 1383 additions and 545 deletions

View File

@@ -7,7 +7,8 @@ categories:
- arrays
- hash-tables
patterns:
- heap
- slug: hashing
is_optimal: true
function_signature: "def contains_duplicate(nums: list[int]) -> bool:"
@@ -138,6 +139,38 @@ explanation:
time_complexity: "O(n). We traverse the array once, with O(1) set operations at each step."
space_complexity: "O(n). In the worst case (all unique elements), we store all n elements in the set."
pattern_comparison: |
**Hash Set vs Sorting: The Classic Space-Time Trade-off**
Two fundamentally different approaches, each optimal in different contexts:
| Approach | Time | Space | Modifies Input? | Early Exit? |
|----------|------|-------|-----------------|-------------|
| **Hash Set** | O(n) | O(n) | No | Yes |
| **Sorting** | O(n log n) | O(1)* | Yes | Yes |
*In-place sorting like quicksort uses O(1) extra space (ignoring recursion stack).
**When Hash Set is better:**
- Memory is plentiful (most modern systems)
- Input must not be modified
- You need the fastest possible runtime
- Data is already streaming in one element at a time
**When Sorting is better:**
- Memory is extremely constrained (embedded systems, very large arrays)
- Modifying the input is acceptable
- You also need the sorted array for subsequent operations
- The data is nearly sorted (adaptive sorts like Timsort are very fast)
**The one-liner alternative:**
```python
return len(nums) != len(set(nums))
```
This is clean and Pythonic, but always processes all elements (no early exit). The iterative set approach can exit immediately upon finding a duplicate, which is faster when duplicates appear early.
**Foundation pattern**: This simple problem teaches the fundamental "have I seen this before?" pattern that appears in Two Sum, cycle detection, and many other problems.
solutions:
- approach_name: Hash Set
is_optimal: true