[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6F4WF3H4PST00FRY3YNJ3BP":3,"skill-same:01M6F4WF3H4PST00FRY3YNJ3BP":89},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":22,"publishedAt":52,"linkOnly":53,"markdownContent":54,"markdownBody":55,"frontMatter":56,"refName":35,"commitSha":69,"skillDirectory":70,"forksCount":71,"repositoryHtmlUrl":72,"repositoryHomepageUrl":6,"ownerHtmlUrl":73,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":74,"install":75,"resources":88},"01M6F4WF3H4PST00FRY3YNJ3BP","complexity-cuts",null,"Lower Big-O on existing code via a one-transformation-at-a-time playbook with verify-revert-stop. For new code use lemmaly; for math-level wins escalate to mathguard.","boisenoise\u002Fskills-collections","boisenoise","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F193180?v=4","01M6CDBDQK6BDN55ZMA6B6PKBM","01M6CDBDVSJ3JPTBYN26FZ7TZK",12,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-complexity-cuts\u002FSKILL.md",[17],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],"complexity cuts","complexity","use","new","2026","at","mathguard","codex-cli","with","transformation","algorithms","time","main","community","stop","cli","math","refactoring","verify","playbook","Optimization","license","code","performance","codex","antigravity","github","gemini","safe","2026-11-10 10:12:30",false,"---\nname: complexity-cuts\ndescription: \"Lower Big-O on existing code via a one-transformation-at-a-time playbook with verify-revert-stop. For new code use lemmaly; for math-level wins escalate to mathguard.\"\nrisk: safe\nsource: community\nsource_repo: morsechimwai\u002Flemmaly\nsource_type: community\ndate_added: \"2026-05-26\"\nauthor: morsechimwai\ntags: [algorithms, big-o, refactoring, optimization, performance, n-plus-one]\ntools: [claude-code, antigravity, cursor, gemini-cli, codex-cli]\nlicense: \"Apache-2.0\"\nlicense_source: \"https:\u002F\u002Fgithub.com\u002Fmorsechimwai\u002Flemmaly\u002Fblob\u002Fmain\u002FLICENSE\"\n---\n\n# complexity-cuts — Lower Big-O on Existing Code\n\n`lemmaly` prevents bad complexity before code is written. **complexity-cuts** fixes it after the fact: code already exists, it works, but its time or space complexity is worse than necessary.\n\n**Violating the letter of these rules is violating the spirit of the skill.** Adapting \"just a little\" is how a faster-but-wrong rewrite ships.\n\n## When to Use This Skill\n\nUse **complexity-cuts** when refactoring existing code that has poor Big-O:\n\n- Nested loops, `O(n²)` or worse scans, repeated work, redundant allocations, blown memory.\n- Stated symptoms: \"this is slow on large inputs\", \"times out\", \"OOM\", \"too much memory\", \"reduce complexity\", \"optimize this algorithm\".\n- N+1 query patterns in ORMs (Prisma, Drizzle, SQLAlchemy, Django, ActiveRecord).\n- `await` inside `for` over independent items causing serial latency.\n\nFor *preventing* bad complexity before code is written, use **`lemmaly`**. For math-level optimizations (Bloom, HLL, FFT, JL projection), escalate to **`mathguard`**.\n\n## The Iron Law\n\n```text\nNO TRANSFORMATION WITHOUT EXISTING TESTS GREEN BEFORE AND AFTER\n```\n\nIf the code has no tests, you write a characterization test first (golden input → current output). Then transform. Then verify the test still passes. If you skip this, the optimization can silently break callers — and faster-but-wrong is worse than slow-and-right.\n\n## Non-negotiable rules\n\n1. **State current and target Big-O before touching code.** In one line:\n   - Current: `time = O(?)`, `space = O(?)`\n   - Target: `time = O(?)`, `space = O(?)`\n   - Dominant input dimension (n = what, how large in practice)\n\n   If you cannot state current Big-O, you do not yet understand the code. Read more.\n\n2. **Identify the bottleneck, do not guess.** Point to the exact line(s) responsible for the dominant term. Nested loop? Repeated linear scan? Recomputation? Allocation inside a hot loop? The fix lives there, not elsewhere.\n\n3. **One transformation at a time, with a verify-revert-stop loop.** The loop is:\n\n   1. Apply exactly one transformation from the playbook.\n   2. Run the existing test suite (or the characterization test you wrote per the Iron Law).\n   3. If any test breaks: **revert immediately.** Do not patch the test. Do not patch around the failure. Revert.\n   4. Count reverts on this piece of code. If **3 reverts in a row**, STOP optimizing. The bottleneck is wrong, the transformation is wrong, or the code has invariants you have not modeled. Escalate to `invariant-guard` and write the missing contract — do not try a fourth transformation.\n   5. Only after a transformation lands green: pick the next one.\n\n   Stacked changes hide regressions. Patched tests hide regressions louder.\n\n4. **Preserve semantics exactly.** Lower complexity must not change outputs, ordering guarantees, stability, or error behavior. If the optimization requires a semantic change (e.g. unordered output), call it out explicitly and confirm it is acceptable.\n\n5. **No invented numbers.** Never write \"10x faster\" or \"saves 200MB\" without measuring. Write `\u003Cmeasured: TBD>` and move on, or actually measure with a representative input.\n\n6. **Always report the measured speedup ratio after a transformation lands.** Once the new code is green, run a representative benchmark (same input, same machine, warm cache) and report `before → after` plus the ratio as `N× faster` (or `N× less memory`). One line, attached to the diff:\n\n   ```text\n   p50:  186 ms → 1.1 ms   (169× faster, n=20,000, 200 samples)\n   ```\n\n   If you cannot measure (e.g. the win is purely asymptotic on inputs you don't have), say so explicitly: `asymptotic only, no measurement — O(n²) → O(n)`. Never silently skip this step.\n\n## The transformation playbook\n\nThe vast majority of real-world Big-O wins come from a small set of moves. Try them in this order:\n\n### Time-complexity reductions\n\n| Smell | Fix | Typical win |\n|---|---|---|\n| `for x in A: if x in B` where B is list\u002Farray | Convert B to `Set`\u002F`Map` once | O(n·m) → O(n+m) |\n| Nested loop computing pairs\u002Fjoins | Hash-join on the key; index by lookup field | O(n·m) → O(n+m) |\n| Repeated `.find` \u002F `.indexOf` \u002F `.includes` inside a loop | Precompute index `Map\u003Ckey, item>` outside loop | O(n^2) → O(n) |\n| Repeated recomputation of same value | Memoize \u002F cache by complete input key | O(n·f(n)) → O(n + f(n)) only when all n calls share one result; account for distinct keys and storage |\n| Sort inside a loop | Sort once outside | O(n^2 log n) → O(n log n) |\n| Linear scan for min\u002Fmax\u002Fmedian repeatedly | Heap \u002F sorted structure | O(n·k) → O(n log k) |\n| Recursive recomputation (naive Fibonacci shape) | Memoize, or convert to iterative DP | exponential → O(n) |\n| String concatenation in a loop (some langs) | Use builder \u002F `join` \u002F `array.push` then join | O(n^2) → O(n) |\n| Repeated regex compile in loop | Compile once outside | constant-factor, large |\n| Counting \u002F grouping via nested loop | Single pass with `Counter` \u002F `Map\u003Ck, count>` | O(n^2) → O(n) |\n| Sliding-window written as nested loop | Two-pointer \u002F windowed sum | O(n^2) → O(n) |\n| Repeated prefix sums | Precompute prefix array, O(1) range queries | O(n·q) → O(n+q) |\n| Pairwise distance \u002F containment checks on intervals | Sort + sweep line | O(n^2) → O(n log n) |\n| Top-K via full sort | Heap of size K | O(n log n) → O(n log k) |\n| Repeated list membership in loop body | `Set` once, reuse | Expected O(n·m) → O(n+m), including construction |\n| `await` inside a `for` over independent items | Bounded batched concurrency, honoring rate limits and cancellation | Ideally O(ceil(n\u002Fc)·latency) at concurrency c; unbounded Promise.all can exhaust resources |\n| ORM query inside a loop (N+1) | `IN (...)` \u002F `select_related` \u002F bulk fetch | O(n) round-trips → O(1) |\n\n### Space-complexity reductions\n\n| Smell | Fix | Typical win |\n|---|---|---|\n| Materializing whole list\u002Farray just to iterate | Generator \u002F iterator \u002F stream | O(n) → O(1) |\n| Building intermediate arrays via chained `.map().filter().map()` on huge data | Single-pass loop or lazy pipeline | k·O(n) → O(n) (often O(1) extra) |\n| Caching every intermediate result of a recursion | Rolling window (keep last k states) | O(n) → O(k) |\n| Storing parents for graph traversal when only count needed | Omit parents, retain visited state when cycles or duplicate visits are possible | Removes parent storage; visited bitset is still O(n) bits |\n| Copying input to mutate | In-place mutation when caller allows | O(n) → O(1) |\n| Reading entire file before processing | Stream line-by-line \u002F chunked | O(file) → O(chunk) |\n| Deep-clone for safety in a loop | Clone once, or use structural sharing \u002F immutables | O(n·m) → O(n+m) |\n| Holding references that prevent GC (closures, listeners, caches) | Bound the cache (LRU), remove listeners, scope closures tightly | unbounded → bounded |\n| Loading full result set from DB | Cursor \u002F pagination \u002F streaming query | O(rows) → O(page) |\n| `JSON.parse(JSON.stringify(x))` for cloning | Targeted copy or structural sharing when semantics permit; structuredClone for supported clone types | A full structuredClone still takes O(n) traversal\u002Fallocation; it is not an asymptotic reduction |\n\n### When you cannot lower asymptotic Big-O\n\nSometimes O(n log n) really is the floor. Then move to constant-factor wins:\n\n- Replace pointer-chasing structures with contiguous arrays (cache locality).\n- Hoist invariants out of loops.\n- Avoid allocation in the hot loop (reuse buffers).\n- Prefer typed arrays \u002F native containers over boxed objects for numeric work.\n- Batch syscalls \u002F I\u002FO.\n\nState explicitly: \"Asymptotic floor is O(n log n); applying constant-factor optimizations only.\"\n\n## Required workflow\n\nFor each piece of code you optimize:\n\n1. **Measure or estimate current Big-O.** Write it down.\n2. **Identify the bottleneck line(s).** Point at them.\n3. **Pick one transformation from the playbook.** Name it.\n4. **Apply it.** One change.\n5. **Verify behavior.** Tests pass, or outputs match on a representative input.\n6. **State new Big-O.** Time and space.\n7. **Repeat if more wins exist and are worth the complexity cost.**\n\n## Canonical example — workflow vs no-workflow\n\nThe same optimization with and without the verify-revert-stop loop.\n\n**Bottleneck.** `getOrdersWithUsers()` runs 10s on 10k orders. Cause: `users.find(u => u.id === o.userId)` inside the map → O(n·m).\n\n### Without the workflow — changes semantics AND patches the test\n\n```ts\n\u002F\u002F No workflow: change semantics + the optimization in one go\nexport function getOrdersWithUsers(orders, users) {\n  const userById = Object.fromEntries(users.map(u => [u.id, u]));\n  return orders\n    .map(o => ({ ...o, user: userById[o.userId] }))\n    .filter(o => o.user); \u002F\u002F silently drops orders whose user was deleted\n}\n```\n\nFaster, *and* changes the result set. Existing tests catch it — but the diff also \"fixes\" a flaky test by removing the assertion that checked the old behavior. Ships green. Breaks the billing report two weeks later.\n\n### With the workflow — one transformation, semantics preserved\n\n```ts\n\u002F\u002F Workflow applied:\n\u002F\u002F   Bottleneck: orders.map → users.find  (line 14)\n\u002F\u002F   Current: time = O(n·m), space = O(1)\n\u002F\u002F   Target:  time = O(n+m), space = O(m)\n\u002F\u002F   Transformation: precompute index Map\u003CuserId, User> outside the loop\n\u002F\u002F   Semantic risk: first duplicate and missing-user behavior preserved; Map equality matches strict equality for the declared finite integer user IDs. Validate that contract first.\n\u002F\u002F   Reverts so far: 0\n\nexport function getOrdersWithUsers(orders, users) {\n  const userById = new Map();\n  \u002F\u002F Array.find returns the first duplicate, so keep the first value.\n  for (const user of users) {\n    if (!userById.has(user.id)) userById.set(user.id, user);\n  }\n  return orders.map(o => ({ ...o, user: userById.get(o.userId) }));\n}\n```\n\nThe example assumes finite integer IDs and side-effect-free ordinary objects; add duplicate-ID and missing-ID characterization cases before transforming. NaN IDs or getters require a different equivalence argument. One transformation. Existing tests stay untouched. Run them. If green, ship. If red, revert (don't patch). After 3 reverts, stop and load `invariant-guard` — the bottleneck is wrong, or the function has a contract no one wrote down.\n\n## Output discipline\n\nWhen proposing or applying an optimization, your message must contain — in this order:\n\n1. **Bottleneck** — file:line and one-sentence reason.\n2. **Current complexity** — `time = O(?)`, `space = O(?)`.\n3. **Transformation** — name from the playbook (or describe it if novel).\n4. **New complexity** — `time = O(?)`, `space = O(?)`.\n5. **Semantic risk** — anything callers might notice (ordering, stability, error timing). \"None\" is a valid answer if true.\n6. **Measured speedup** — `before → after` with the ratio as `N× faster` (or `asymptotic only` if not measured). One line, honest numbers.\n7. **The diff.**\n\nIf any of 1–6 is missing, the optimization is not ready to apply.\n\n## Stop conditions — do not optimize further when\n\n- Asymptotic Big-O already matches a known lower bound for the problem.\n- The input is provably small and bounded (n \u003C ~100 and not on a hot path).\n- The optimization would obscure correctness or harm readability without a measured win.\n- The bottleneck is I\u002FO or external service latency, not CPU\u002Fmemory — go fix that instead.\n\nPremature optimization past these points adds risk without payoff.\n\n## Rationalizations to watch for\n\n| Excuse | Reality |\n| --- | --- |\n| \"I already solved this in my head — just paste the diff and add labels after.\" | Retrofitted labels lie about the reasoning order. Write bottleneck → complexity → transformation → diff in that order, or you are writing fiction. |\n| \"Stating the current Big-O is busywork — everyone can see the nested loop.\" | If everyone can see it, writing one line costs nothing. If only you can see it, you just saved the reviewer's time. |\n| \"Semantic risk is None, skip that step.\" | \"None\" is a valid answer — but write it. The next reader does not know which guarantees you considered. |\n| \"I'll do all three transformations in one diff.\" | Stacked transformations hide regressions. One transformation, verify, repeat. |\n| \"It's just a small refactor, the workflow is overkill.\" | Then it takes 30 seconds. The cases where you skip the workflow are the ones where you miss the optimization next to the obvious one. |\n| \"I'll measure later.\" | Later is `\u003Cmeasured: TBD>` forever. Either measure now or accept the asymptotic argument as the only claim. |\n\n## Red flags — STOP\n\n- Optimizing without stating current Big-O.\n- \"This should be faster\" without identifying a specific bottleneck line.\n- Stacking multiple transformations before verifying any one of them.\n- Claiming a speedup without measuring or without an asymptotic argument.\n- Lowering complexity by silently changing output semantics.\n- Rewriting code that runs once at startup with n = 12.\n\n## Verification checklist\n\nBefore claiming an optimization is complete:\n\n- [ ] Existing tests (or a written characterization test) were green BEFORE the transformation.\n- [ ] Exactly one transformation was applied.\n- [ ] Tests are green AFTER the transformation.\n- [ ] No test was modified, weakened, or skipped to make it pass.\n- [ ] Current Big-O and target Big-O are stated in the diff or PR description.\n- [ ] Semantic risk is written down (\"None\" is valid if true).\n- [ ] Measured speedup ratio is reported as `before → after · N× faster` (or explicitly marked `asymptotic only` if no measurement was possible).\n- [ ] If a measured claim was made (e.g. \"3x faster\"), the measurement command is included.\n- [ ] Revert count on this code is \u003C 3.\n\nCannot check every box? The optimization is not done. Either revert or finish the gap — do not ship a half-verified speedup.\n\n## Limitations\n\n- **Requires existing tests or a written characterization test.** Without one, you cannot detect silent semantic regressions; the Iron Law refuses to skip this.\n- **Asymptotic wins only; constant-factor work is a separate mode** (clearly labeled). The playbook will not improve cache locality or SIMD utilization on its own.\n- **Single-process scope.** Distributed-system bottlenecks (consensus latency, replication lag, queue backpressure) are out of scope.\n- **3-revert rule is firm.** If three transformations failed, the skill explicitly forces escalation to `invariant-guard`; it does not let you try a fourth.\n- **Measurement is on the author.** complexity-cuts requires the ratio to be reported but does not run the benchmark for you — you must produce a representative input.\n- **Won't help I\u002FO-bound code.** If the dominant term is network latency or disk, the playbook will not move the needle — fix the I\u002FO pattern instead.\n\n## The thesis, in one line\n\n> **Existing code earned its slowness one shortcut at a time. complexity-cuts removes them one transformation at a time — and refuses to ship the optimization without a green test.**\n\n## Related Skills\n\n- `lemmaly` — prevention gateway; use when writing new code instead of refactoring existing.\n- `invariant-guard` — escalation target when 3+ transformations have failed tests — the missing piece is a contract, not an optimization.\n- `mathguard` — escalation when the classical floor is reached and an approximate or math-heavy structure could win.\n","# complexity-cuts — Lower Big-O on Existing Code\n\n`lemmaly` prevents bad complexity before code is written. **complexity-cuts** fixes it after the fact: code already exists, it works, but its time or space complexity is worse than necessary.\n\n**Violating the letter of these rules is violating the spirit of the skill.** Adapting \"just a little\" is how a faster-but-wrong rewrite ships.\n\n## When to Use This Skill\n\nUse **complexity-cuts** when refactoring existing code that has poor Big-O:\n\n- Nested loops, `O(n²)` or worse scans, repeated work, redundant allocations, blown memory.\n- Stated symptoms: \"this is slow on large inputs\", \"times out\", \"OOM\", \"too much memory\", \"reduce complexity\", \"optimize this algorithm\".\n- N+1 query patterns in ORMs (Prisma, Drizzle, SQLAlchemy, Django, ActiveRecord).\n- `await` inside `for` over independent items causing serial latency.\n\nFor *preventing* bad complexity before code is written, use **`lemmaly`**. For math-level optimizations (Bloom, HLL, FFT, JL projection), escalate to **`mathguard`**.\n\n## The Iron Law\n\n```text\nNO TRANSFORMATION WITHOUT EXISTING TESTS GREEN BEFORE AND AFTER\n```\n\nIf the code has no tests, you write a characterization test first (golden input → current output). Then transform. Then verify the test still passes. If you skip this, the optimization can silently break callers — and faster-but-wrong is worse than slow-and-right.\n\n## Non-negotiable rules\n\n1. **State current and target Big-O before touching code.** In one line:\n   - Current: `time = O(?)`, `space = O(?)`\n   - Target: `time = O(?)`, `space = O(?)`\n   - Dominant input dimension (n = what, how large in practice)\n\n   If you cannot state current Big-O, you do not yet understand the code. Read more.\n\n2. **Identify the bottleneck, do not guess.** Point to the exact line(s) responsible for the dominant term. Nested loop? Repeated linear scan? Recomputation? Allocation inside a hot loop? The fix lives there, not elsewhere.\n\n3. **One transformation at a time, with a verify-revert-stop loop.** The loop is:\n\n   1. Apply exactly one transformation from the playbook.\n   2. Run the existing test suite (or the characterization test you wrote per the Iron Law).\n   3. If any test breaks: **revert immediately.** Do not patch the test. Do not patch around the failure. Revert.\n   4. Count reverts on this piece of code. If **3 reverts in a row**, STOP optimizing. The bottleneck is wrong, the transformation is wrong, or the code has invariants you have not modeled. Escalate to `invariant-guard` and write the missing contract — do not try a fourth transformation.\n   5. Only after a transformation lands green: pick the next one.\n\n   Stacked changes hide regressions. Patched tests hide regressions louder.\n\n4. **Preserve semantics exactly.** Lower complexity must not change outputs, ordering guarantees, stability, or error behavior. If the optimization requires a semantic change (e.g. unordered output), call it out explicitly and confirm it is acceptable.\n\n5. **No invented numbers.** Never write \"10x faster\" or \"saves 200MB\" without measuring. Write `\u003Cmeasured: TBD>` and move on, or actually measure with a representative input.\n\n6. **Always report the measured speedup ratio after a transformation lands.** Once the new code is green, run a representative benchmark (same input, same machine, warm cache) and report `before → after` plus the ratio as `N× faster` (or `N× less memory`). One line, attached to the diff:\n\n   ```text\n   p50:  186 ms → 1.1 ms   (169× faster, n=20,000, 200 samples)\n   ```\n\n   If you cannot measure (e.g. the win is purely asymptotic on inputs you don't have), say so explicitly: `asymptotic only, no measurement — O(n²) → O(n)`. Never silently skip this step.\n\n## The transformation playbook\n\nThe vast majority of real-world Big-O wins come from a small set of moves. Try them in this order:\n\n### Time-complexity reductions\n\n| Smell | Fix | Typical win |\n|---|---|---|\n| `for x in A: if x in B` where B is list\u002Farray | Convert B to `Set`\u002F`Map` once | O(n·m) → O(n+m) |\n| Nested loop computing pairs\u002Fjoins | Hash-join on the key; index by lookup field | O(n·m) → O(n+m) |\n| Repeated `.find` \u002F `.indexOf` \u002F `.includes` inside a loop | Precompute index `Map\u003Ckey, item>` outside loop | O(n^2) → O(n) |\n| Repeated recomputation of same value | Memoize \u002F cache by complete input key | O(n·f(n)) → O(n + f(n)) only when all n calls share one result; account for distinct keys and storage |\n| Sort inside a loop | Sort once outside | O(n^2 log n) → O(n log n) |\n| Linear scan for min\u002Fmax\u002Fmedian repeatedly | Heap \u002F sorted structure | O(n·k) → O(n log k) |\n| Recursive recomputation (naive Fibonacci shape) | Memoize, or convert to iterative DP | exponential → O(n) |\n| String concatenation in a loop (some langs) | Use builder \u002F `join` \u002F `array.push` then join | O(n^2) → O(n) |\n| Repeated regex compile in loop | Compile once outside | constant-factor, large |\n| Counting \u002F grouping via nested loop | Single pass with `Counter` \u002F `Map\u003Ck, count>` | O(n^2) → O(n) |\n| Sliding-window written as nested loop | Two-pointer \u002F windowed sum | O(n^2) → O(n) |\n| Repeated prefix sums | Precompute prefix array, O(1) range queries | O(n·q) → O(n+q) |\n| Pairwise distance \u002F containment checks on intervals | Sort + sweep line | O(n^2) → O(n log n) |\n| Top-K via full sort | Heap of size K | O(n log n) → O(n log k) |\n| Repeated list membership in loop body | `Set` once, reuse | Expected O(n·m) → O(n+m), including construction |\n| `await` inside a `for` over independent items | Bounded batched concurrency, honoring rate limits and cancellation | Ideally O(ceil(n\u002Fc)·latency) at concurrency c; unbounded Promise.all can exhaust resources |\n| ORM query inside a loop (N+1) | `IN (...)` \u002F `select_related` \u002F bulk fetch | O(n) round-trips → O(1) |\n\n### Space-complexity reductions\n\n| Smell | Fix | Typical win |\n|---|---|---|\n| Materializing whole list\u002Farray just to iterate | Generator \u002F iterator \u002F stream | O(n) → O(1) |\n| Building intermediate arrays via chained `.map().filter().map()` on huge data | Single-pass loop or lazy pipeline | k·O(n) → O(n) (often O(1) extra) |\n| Caching every intermediate result of a recursion | Rolling window (keep last k states) | O(n) → O(k) |\n| Storing parents for graph traversal when only count needed | Omit parents, retain visited state when cycles or duplicate visits are possible | Removes parent storage; visited bitset is still O(n) bits |\n| Copying input to mutate | In-place mutation when caller allows | O(n) → O(1) |\n| Reading entire file before processing | Stream line-by-line \u002F chunked | O(file) → O(chunk) |\n| Deep-clone for safety in a loop | Clone once, or use structural sharing \u002F immutables | O(n·m) → O(n+m) |\n| Holding references that prevent GC (closures, listeners, caches) | Bound the cache (LRU), remove listeners, scope closures tightly | unbounded → bounded |\n| Loading full result set from DB | Cursor \u002F pagination \u002F streaming query | O(rows) → O(page) |\n| `JSON.parse(JSON.stringify(x))` for cloning | Targeted copy or structural sharing when semantics permit; structuredClone for supported clone types | A full structuredClone still takes O(n) traversal\u002Fallocation; it is not an asymptotic reduction |\n\n### When you cannot lower asymptotic Big-O\n\nSometimes O(n log n) really is the floor. Then move to constant-factor wins:\n\n- Replace pointer-chasing structures with contiguous arrays (cache locality).\n- Hoist invariants out of loops.\n- Avoid allocation in the hot loop (reuse buffers).\n- Prefer typed arrays \u002F native containers over boxed objects for numeric work.\n- Batch syscalls \u002F I\u002FO.\n\nState explicitly: \"Asymptotic floor is O(n log n); applying constant-factor optimizations only.\"\n\n## Required workflow\n\nFor each piece of code you optimize:\n\n1. **Measure or estimate current Big-O.** Write it down.\n2. **Identify the bottleneck line(s).** Point at them.\n3. **Pick one transformation from the playbook.** Name it.\n4. **Apply it.** One change.\n5. **Verify behavior.** Tests pass, or outputs match on a representative input.\n6. **State new Big-O.** Time and space.\n7. **Repeat if more wins exist and are worth the complexity cost.**\n\n## Canonical example — workflow vs no-workflow\n\nThe same optimization with and without the verify-revert-stop loop.\n\n**Bottleneck.** `getOrdersWithUsers()` runs 10s on 10k orders. Cause: `users.find(u => u.id === o.userId)` inside the map → O(n·m).\n\n### Without the workflow — changes semantics AND patches the test\n\n```ts\n\u002F\u002F No workflow: change semantics + the optimization in one go\nexport function getOrdersWithUsers(orders, users) {\n  const userById = Object.fromEntries(users.map(u => [u.id, u]));\n  return orders\n    .map(o => ({ ...o, user: userById[o.userId] }))\n    .filter(o => o.user); \u002F\u002F silently drops orders whose user was deleted\n}\n```\n\nFaster, *and* changes the result set. Existing tests catch it — but the diff also \"fixes\" a flaky test by removing the assertion that checked the old behavior. Ships green. Breaks the billing report two weeks later.\n\n### With the workflow — one transformation, semantics preserved\n\n```ts\n\u002F\u002F Workflow applied:\n\u002F\u002F   Bottleneck: orders.map → users.find  (line 14)\n\u002F\u002F   Current: time = O(n·m), space = O(1)\n\u002F\u002F   Target:  time = O(n+m), space = O(m)\n\u002F\u002F   Transformation: precompute index Map\u003CuserId, User> outside the loop\n\u002F\u002F   Semantic risk: first duplicate and missing-user behavior preserved; Map equality matches strict equality for the declared finite integer user IDs. Validate that contract first.\n\u002F\u002F   Reverts so far: 0\n\nexport function getOrdersWithUsers(orders, users) {\n  const userById = new Map();\n  \u002F\u002F Array.find returns the first duplicate, so keep the first value.\n  for (const user of users) {\n    if (!userById.has(user.id)) userById.set(user.id, user);\n  }\n  return orders.map(o => ({ ...o, user: userById.get(o.userId) }));\n}\n```\n\nThe example assumes finite integer IDs and side-effect-free ordinary objects; add duplicate-ID and missing-ID characterization cases before transforming. NaN IDs or getters require a different equivalence argument. One transformation. Existing tests stay untouched. Run them. If green, ship. If red, revert (don't patch). After 3 reverts, stop and load `invariant-guard` — the bottleneck is wrong, or the function has a contract no one wrote down.\n\n## Output discipline\n\nWhen proposing or applying an optimization, your message must contain — in this order:\n\n1. **Bottleneck** — file:line and one-sentence reason.\n2. **Current complexity** — `time = O(?)`, `space = O(?)`.\n3. **Transformation** — name from the playbook (or describe it if novel).\n4. **New complexity** — `time = O(?)`, `space = O(?)`.\n5. **Semantic risk** — anything callers might notice (ordering, stability, error timing). \"None\" is a valid answer if true.\n6. **Measured speedup** — `before → after` with the ratio as `N× faster` (or `asymptotic only` if not measured). One line, honest numbers.\n7. **The diff.**\n\nIf any of 1–6 is missing, the optimization is not ready to apply.\n\n## Stop conditions — do not optimize further when\n\n- Asymptotic Big-O already matches a known lower bound for the problem.\n- The input is provably small and bounded (n \u003C ~100 and not on a hot path).\n- The optimization would obscure correctness or harm readability without a measured win.\n- The bottleneck is I\u002FO or external service latency, not CPU\u002Fmemory — go fix that instead.\n\nPremature optimization past these points adds risk without payoff.\n\n## Rationalizations to watch for\n\n| Excuse | Reality |\n| --- | --- |\n| \"I already solved this in my head — just paste the diff and add labels after.\" | Retrofitted labels lie about the reasoning order. Write bottleneck → complexity → transformation → diff in that order, or you are writing fiction. |\n| \"Stating the current Big-O is busywork — everyone can see the nested loop.\" | If everyone can see it, writing one line costs nothing. If only you can see it, you just saved the reviewer's time. |\n| \"Semantic risk is None, skip that step.\" | \"None\" is a valid answer — but write it. The next reader does not know which guarantees you considered. |\n| \"I'll do all three transformations in one diff.\" | Stacked transformations hide regressions. One transformation, verify, repeat. |\n| \"It's just a small refactor, the workflow is overkill.\" | Then it takes 30 seconds. The cases where you skip the workflow are the ones where you miss the optimization next to the obvious one. |\n| \"I'll measure later.\" | Later is `\u003Cmeasured: TBD>` forever. Either measure now or accept the asymptotic argument as the only claim. |\n\n## Red flags — STOP\n\n- Optimizing without stating current Big-O.\n- \"This should be faster\" without identifying a specific bottleneck line.\n- Stacking multiple transformations before verifying any one of them.\n- Claiming a speedup without measuring or without an asymptotic argument.\n- Lowering complexity by silently changing output semantics.\n- Rewriting code that runs once at startup with n = 12.\n\n## Verification checklist\n\nBefore claiming an optimization is complete:\n\n- [ ] Existing tests (or a written characterization test) were green BEFORE the transformation.\n- [ ] Exactly one transformation was applied.\n- [ ] Tests are green AFTER the transformation.\n- [ ] No test was modified, weakened, or skipped to make it pass.\n- [ ] Current Big-O and target Big-O are stated in the diff or PR description.\n- [ ] Semantic risk is written down (\"None\" is valid if true).\n- [ ] Measured speedup ratio is reported as `before → after · N× faster` (or explicitly marked `asymptotic only` if no measurement was possible).\n- [ ] If a measured claim was made (e.g. \"3x faster\"), the measurement command is included.\n- [ ] Revert count on this code is \u003C 3.\n\nCannot check every box? The optimization is not done. Either revert or finish the gap — do not ship a half-verified speedup.\n\n## Limitations\n\n- **Requires existing tests or a written characterization test.** Without one, you cannot detect silent semantic regressions; the Iron Law refuses to skip this.\n- **Asymptotic wins only; constant-factor work is a separate mode** (clearly labeled). The playbook will not improve cache locality or SIMD utilization on its own.\n- **Single-process scope.** Distributed-system bottlenecks (consensus latency, replication lag, queue backpressure) are out of scope.\n- **3-revert rule is firm.** If three transformations failed, the skill explicitly forces escalation to `invariant-guard`; it does not let you try a fourth.\n- **Measurement is on the author.** complexity-cuts requires the ratio to be reported but does not run the benchmark for you — you must produce a representative input.\n- **Won't help I\u002FO-bound code.** If the dominant term is network latency or disk, the playbook will not move the needle — fix the I\u002FO pattern instead.\n\n## The thesis, in one line\n\n> **Existing code earned its slowness one shortcut at a time. complexity-cuts removes them one transformation at a time — and refuses to ship the optimization without a green test.**\n\n## Related Skills\n\n- `lemmaly` — prevention gateway; use when writing new code instead of refactoring existing.\n- `invariant-guard` — escalation target when 3+ transformations have failed tests — the missing piece is a contract, not an optimization.\n- `mathguard` — escalation when the classical floor is reached and an approximate or math-heavy structure could win.\n",{"name":5,"risk":51,"tags":57,"tools":61,"author":65,"source":36,"license":14,"date_added":66,"description":7,"source_repo":67,"source_type":36,"license_source":68},[33,58,40,59,46,60],"big-o","optimization","n-plus-one",[62,48,63,64,30],"claude-code","cursor","gemini-cli","morsechimwai","2026-05-26","morsechimwai\u002Flemmaly","https:\u002F\u002Fgithub.com\u002Fmorsechimwai\u002Flemmaly\u002Fblob\u002Fmain\u002FLICENSE","7bf2279c8a65758319526a721d5c4b75683aec9c","skills\u002Fantigravity-complexity-cuts",3,"https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections","https:\u002F\u002Fgithub.com\u002Fboisenoise","2026-11-12 14:21:24",{"source":8,"skillName":5,"commands":76,"prompt":86,"zipAvailable":87},[77,80,83],{"tool":78,"command":79},"npx","npx skills add boisenoise\u002Fskills-collections --skill complexity-cuts",{"tool":81,"command":82},"bunx","bunx skills add boisenoise\u002Fskills-collections --skill complexity-cuts",{"tool":84,"command":85},"pnpm","pnpm dlx skills add boisenoise\u002Fskills-collections --skill complexity-cuts","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-complexity-cuts\u002FSKILL.md",true,[],[90,118,141,165,183,206],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":52},"01M6WNH92BHVFXHGPDZCPJ0AG0","web-access","Use Treg for public web or platform data only when existing search, browser and connected tools cannot cover the task, with explicit cost and data boundaries.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-web-access\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-web-access\u002FSKILL.md",[],[98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,27],"web","access","web access","official","development","browser","search","data","Tools","read","fetch","only","youtube","free tools","platform","critical","free","cover","normal","when",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":122,"sourceHtmlUrl":123,"categories":124,"keywords":130,"publishedAt":52},"01M6WNF9XAYAB2CZDDJBAKNM93","treg","Use the Treg CLI or MCP catalog to discover, price and call authorized external tools with team-scoped credentials and a user-approved budget.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-treg\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-treg\u002FSKILL.md",[125],{"categoryNo":126,"categoryName":127,"taxonomyType":128,"taxonomyTypeDesc":129},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[120,131,38,49,101,102,44,106,132,133,134,135,25,136,137,113,138,31,139,140,27],"MCP","Budget","credentials","team","catalog","call","discover","external tools","scoped","blob",{"skillNo":142,"name":143,"nameZh":6,"description":144,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":145,"sourceHtmlUrl":146,"categories":147,"keywords":151,"publishedAt":52},"01M6WN93MEAZ4E41DYAHJRPHQT","recruit","Turn a job description into an evidence-linked candidate shortlist through Treg, with job-related ranking and optional authorized business contact enrichment.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-recruit\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-recruit\u002FSKILL.md",[148],{"categoryNo":149,"categoryName":150,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000038","人力资源",[143,49,101,44,152,153,154,155,156,157,113,158,159,160,31,161,162,163,164,140,120,27],"https","email","enrichment","business","evidence","phone","ranking","post","job description","for","person","candidate","reason",{"skillNo":166,"name":167,"nameZh":6,"description":168,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":169,"sourceHtmlUrl":170,"categories":171,"keywords":172,"publishedAt":52},"01M6WN8R5RXSMHM9B4D9FAFX42","rea-growth","Analyze a company’s public growth and content through Treg, distinguish observations from hypotheses, and produce an evidence-linked playbook within an approved budget.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-rea-growth\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-rea-growth\u002FSKILL.md",[],[173,174,175,49,101,44,176,177,152,42,132,178,179,180,156,113,181,182,140,120,27],"growth","rea","rea growth","produce","content","marketing","analyze","public","observations","company",{"skillNo":184,"name":185,"nameZh":6,"description":186,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":187,"sourceHtmlUrl":188,"categories":189,"keywords":190,"publishedAt":52},"01M6WN2EVE3RQRGWAKBT4S7YT2","make-ugc","Create original AI UGC-style product videos through Treg: research hooks, approve a licensed presenter and voice, generate clips, add captions and report costs.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-make-ugc\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-make-ugc\u002FSKILL.md",[],[191,192,49,193,101,194,44,195,196,197,198,199,113,200,201,202,203,204,205,140],"make","make ugc","research","create","Video","Captions","ads","short","hooks","head","style","niche","trending","talking-head","approve",{"skillNo":207,"name":208,"nameZh":6,"description":209,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":210,"sourceHtmlUrl":211,"categories":212,"keywords":213,"publishedAt":52},"01M6WN10ARAA63Y8K1YNGXJ2RM","lead-signals","Find and qualify public buying signals through Treg, rank fitting business accounts and optionally enrich authorized business contact information.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-lead-signals\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-lead-signals\u002FSKILL.md",[],[214,215,216,49,101,44,217,218,155,219,220,113,221,222,223,224,225,226,227,140],"signals","lead","lead signals","how","find","ready","as","how to","qualify","people","information","enrich","changes","funding"]