Algorithm Design Expert
Designs, analyzes, and optimizes algorithms with multiple approaches, Big-O complexity analysis, production code, and tests.
// prompt
You are a **computer science expert and algorithm researcher**. Help me design, analyze, and optimize an efficient algorithm for the problem below, with rigorous complexity reasoning and production-ready code.
## Problem
- **Algorithm Type:** {{algorithm_type}}
- **Problem Description:** {{problem_description}}
- **Input:** {{input_format}}
- **Expected Output:** {{output_format}}
- **Constraints:** {{size_limits_and_conditions}}
- **Edge Cases:** {{special_scenarios}}
- **Performance Requirements:** {{speed_and_memory_constraints}}
- **Implementation Language:** {{programming_language}}
## What To Deliver
**1. Problem restatement.** Briefly reformulate the task, confirm your assumptions, and list the edge cases any correct solution must handle.
**2. Candidate approaches (at least two).** For each, give:
- the technique and data structures used, plus the core idea
- time and space complexity in Big-O, with a one-line justification
- key trade-offs and when to prefer it
Then compare them and recommend the optimal approach for the stated constraints.
**3. Optimal implementation.** Provide clean, idiomatic {{programming_language}} code with:
- meaningful names and inline comments on non-obvious steps
- a docstring or header stating time and space complexity
- explicit handling of the edge cases above
**4. Test cases.** Include normal, boundary, and adversarial inputs, each with the expected result and the property it verifies.
**5. Optimization notes.** Explain further speedups (caching, pruning, better data structures), the theoretical lower bound if one is known, and what would need to change to handle {{scale_target}} inputs.
## Format
Use clear headings, a complexity comparison table, and fenced code blocks. State assumptions explicitly, and do not invent constraints I did not provide.
Fill in the variables
Example response
🧮 Algorithm Design Analysis
Problem: Find Longest Palindromic Substring
📊 Solution Approaches Comparison
| Approach | Time | Space | Pros | Cons |
|---|---|---|---|---|
| Brute Force | O(n³) | O(1) | Simple | Too slow |
| Expand Centers | O(n²) | O(1) | Optimal space | Still slow for large inputs |
| Manacher's Algorithm | O(n) | O(n) | Linear time | Complex implementation |
🎯 Optimal Implementation: Expand Around Centers
def longest_palindrome(s: str) -> str:
"""
Find the longest palindromic substring using center expansion.
Time Complexity: O(n²)
Space Complexity: O(1)
Args:
s: Input string to search
Returns:
Longest palindromic substring
"""
if not s:
return ""
start = 0
max_len = 1
def expand_around_center(left: int, right: int) -> int:
"""Expand around center and return length."""
while (left >= 0 and right < len(s) and
s[left] == s[right]):
left -= 1
right += 1
return right - left - 1
for i in range(len(s)):
# Check for odd-length palindromes (center at i)
len1 = expand_around_center(i, i)
# Check for even-length palindromes (center between i and i+1)
len2 = expand_around_center(i, i + 1)
# Update maximum if we found a longer palindrome
current_max = max(len1, len2)
if current_max > max_len:
max_len = current_max
start = i - (current_max - 1) // 2
return s[start:start + max_len]
# Comprehensive Test Cases
def test_longest_palindrome():
"""Test cases covering edge cases and normal scenarios."""
test_cases = [
("babad", "bab"), # or "aba"
("cbbd", "bb"),
("a", "a"),
("ac", "a"), # or "c"
("", ""),
("racecar", "racecar"),
("abcdef", "a"), # no palindromes > 1
]
for input_str, expected in test_cases:
result = longest_palindrome(input_str)
print(f"Input: {{input_str}} -> Output: {{result}}")
assert len(result) == len(expected), f"Failed for {{input_str}}"
# Performance Analysis
import time
def benchmark():
"""Benchmark with different input sizes."""
test_strings = [
"a" * 100,
"ab" * 500,
"racecar" * 100
]
for test_str in test_strings:
start_time = time.time()
result = longest_palindrome(test_str)
end_time = time.time()
print(f"Length {{len(test_str)}}: {{end_time - start_time:.4f}}s")
🔍 Complexity Analysis
- Time: O(n²) - for each center, we expand up to n characters
- Space: O(1) - only using constant extra space
- Best Case: O(n) when no palindromes exist
- Worst Case: O(n²) when entire string is palindromic
Related prompts
Programming & Development
Advanced Debugging Assistant
Diagnoses bugs in your code, pinpoints root causes, and delivers fixed code with prevention tips.
Programming & Development
API Development Architect
Designs a production-ready RESTful API with OpenAPI spec, secure auth, validation, and scalable architecture.
Programming & Development
Code Review Expert
Performs a rigorous senior-level code review covering correctness, design, performance, and security with prioritized, actionable fixes.
Programming & Development
JavaScript & React Development Expert
Generates production-grade, typed React and JavaScript code with tests, accessibility, and clear architectural reasoning.