migrate 392 questions to pattern format
This commit is contained in:
@@ -8,7 +8,8 @@ categories:
|
||||
- hash-tables
|
||||
- sorting
|
||||
patterns:
|
||||
- prefix-sum
|
||||
- slug: hashing
|
||||
is_optimal: true
|
||||
|
||||
function_signature: "def is_anagram(s: str, t: str) -> bool:"
|
||||
|
||||
@@ -123,6 +124,35 @@ explanation:
|
||||
time_complexity: "O(n). We iterate through both strings once, where `n` is the length of the strings."
|
||||
space_complexity: "O(1). We use a fixed-size array of 26 integers, regardless of input size. This is technically O(26) = O(1) constant space."
|
||||
|
||||
pattern_comparison: |
|
||||
**Counting Array vs Hash Map vs Sorting: Choose Your Weapon**
|
||||
|
||||
Three valid approaches with different trade-offs:
|
||||
|
||||
| Approach | Time | Space | Best For |
|
||||
|----------|------|-------|----------|
|
||||
| **Counting Array** | O(n) | O(1) | Fixed character set (a-z, A-Z) |
|
||||
| **Hash Map (Counter)** | O(n) | O(k) | Unicode, variable character sets |
|
||||
| **Sorting** | O(n log n) | O(n) | Simplest code, small inputs |
|
||||
|
||||
**Why Counting Array wins here:**
|
||||
- The problem guarantees lowercase English letters only (26 characters)
|
||||
- Array indexing (`ord(c) - ord('a')`) is faster than hash function computation
|
||||
- Memory layout is contiguous and cache-friendly
|
||||
- True O(1) space since array size is constant
|
||||
|
||||
**When to use Hash Map instead:**
|
||||
- Unicode strings with unpredictable character sets
|
||||
- When the follow-up asks "What if inputs contain Unicode characters?"
|
||||
- When readability matters more than micro-optimisation
|
||||
|
||||
**When Sorting is acceptable:**
|
||||
- Quick prototyping or one-off scripts
|
||||
- When you need the sorted strings for other purposes
|
||||
- For very short strings where the O(n log n) factor is negligible
|
||||
|
||||
**Interview tip**: Start with the array approach for the O(1) space, then mention the Counter approach as a "cleaner but slightly slower alternative."
|
||||
|
||||
solutions:
|
||||
- approach_name: Character Frequency Count
|
||||
is_optimal: true
|
||||
|
||||
Reference in New Issue
Block a user