optimizationadvanced540 tokens
Algorithm Complexity Optimization
Optimize algorithms for better time/space complexity
algorithmsoptimizationcomplexitydata-structuresperformance
Prompt Template
You are an algorithms expert. Optimize the following code for better time and space complexity.
**Current Code:**
```{language}
{code}
```
**Context:**
- Input size range: {input_size}
- Current complexity: {current_complexity}
- Performance requirement: {requirement}
- Memory constraints: {memory_limit}
Optimize following this process:
**1. Complexity Analysis:**
Analyze current implementation:
- Time complexity: O(?) - explain why
- Space complexity: O(?) - explain why
- Identify bottlenecks:
- Nested loops
- Repeated computations
- Unnecessary data structures
- Redundant operations
**2. Optimization Opportunities:**
List specific improvements by technique:
**Algorithmic Improvements:**
- Can we use a different algorithm? (e.g., sort instead of nested loop)
- Better data structure? (hash map vs array, heap vs linear search)
- Divide and conquer opportunity?
- Dynamic programming applicable?
- Greedy approach possible?
**Code-Level Optimizations:**
- Memoization/caching
- Early termination
- In-place operations
- Batch processing
- Loop invariant optimization
**3. Optimized Solution:**
```{language}
// Optimized code with detailed comments
{optimized_code}
```
**4. Complexity Comparison:**
| Aspect | Before | After | Improvement |
|--------|--------|-------|-------------|
| Time | O({before_time}) | O({after_time}) | ... |
| Space | O({before_space}) | O({after_space}) | ... |
| Real-world runtime | {before_ms}ms | {after_ms}ms | {x}x faster |
**5. Tradeoffs:**
Explain any tradeoffs made:
- Space for time (if applicable)
- Code readability impact
- Maintenance complexity
- Edge case handling changes
**6. Alternative Approaches:**
Briefly describe 1-2 other valid approaches:
- Approach A: [description, complexity, when to use]
- Approach B: [description, complexity, when to use]
**7. Benchmarking Code:**
```{language}
// Code to benchmark both implementations
```
**8. When to Use:**
Recommendations:
- Use optimized version when: [conditions]
- Stick with original when: [conditions]
- Consider alternative when: [conditions]
Provide actual runnable code, not pseudocode.Variables to Replace
{language}{code}{input_size}{current_complexity}{requirement}{memory_limit}Pro Tips
Specify performance requirements (latency, throughput) to get appropriate optimizations.
Related Prompts
Need More Prompts?
Explore our full library of 60+ professional AI prompt templates
Browse All Prompts →