Coding
AI Prompt for Optimizing Algorithms
Optimize slow algorithms with this AI prompt: the key insight explained, O(n²) to O(n) rewrites, correctness proofs, and honest trade-off analysis.
The prompt
Role: You are an optimization expert who improves algorithms asymptotically, not just by constants. Context: Language: [LANGUAGE]. Current code: [CODE] with complexity [CURRENT_COMPLEXITY]. Bottleneck: [BOTTLENECK_DESCRIPTION]. Target: [TARGET_COMPLEXITY or 'as fast as reasonably possible']. Must preserve: [INVARIANTS: output order, stability, etc.]. Task: 1) Explain the key insight that unlocks the better complexity (the "aha" — e.g. "a hash set makes lookups O(1)"). 2) Provide the optimized implementation. 3) Prove it produces the same results: explain the equivalence argument and provide test cases covering edge cases. 4) State the trade-offs (extra memory? less readable? worse constant factors for small n?) and the crossover point where the optimization wins. Format: Insight first, then optimized code, then the equivalence proof + tests, then trade-offs with the crossover analysis. Ask the AI to benchmark the crossover point empirically on your hardware: the input size where the optimized version actually pulls ahead. Asymptotic wins can lose to constants on small inputs. Constraints: Preserve [INVARIANTS] exactly. Do not sacrifice clarity for a 2x constant-factor gain — say when the optimization is NOT worth it.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [CODE] [CURRENT_COMPLEXITY] [BOTTLENECK_DESCRIPTION] [TARGET_COMPLEXITY] [INVARIANTS]
Example input
LANGUAGE=JavaScript, CODE=O(n²) nested loop finding duplicates, BOTTLENECK=inner loop re-scans, TARGET=O(n), MUST_KEEP=output order
How to use this prompt
Point at the bottleneck you suspect — the AI confirms and fixes the algorithmic issue. State what must stay identical (order, stability) to constrain the rewrite.
Tips for the best results
- Ask for the crossover point — optimized algorithms often lose on small inputs.
- Demand the equivalence proof; faster-but-wrong is worthless.
- Have it benchmark both versions on your data size if possible.
Frequently asked questions
Will it preserve exact behavior?
It finds the algorithmic improvement (not micro-optimizations) and proves the new version matches the old on test cases.
Is a faster Big-O always better in practice?
Not for small inputs — constants dominate. The prompt's crossover analysis tells you exactly where the optimization starts paying off.