[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7A43JVTCBX96F2GP29C8VCW":3,"skill-same:01M7A43JVTCBX96F2GP29C8VCW":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":49,"ownerDescription":50,"updatedAt":51,"install":52,"resources":65},"01M7A43JVTCBX96F2GP29C8VCW","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.","MHassan0000\u002FSkills","MHassan0000","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F224296448?v=4","01M7A14DTC1EZCRN04582533RD","Muhammad Hassan Yousaf","01M7A14DV10KTW8NHQTJPD08X0",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fantigravity skills\u002Fagentic-awesome-skills\u002Fskills\u002Fcomplexity-cuts\u002FSKILL.md",[],[],"2026-11-15 14:19:17",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 input key | O(n·f(n)) → O(n + f(n)) |\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 set membership in loop body | `Set` once, reuse | O(n·m) → O(n) |\n| `await` inside a `for` over independent items | `Promise.all` \u002F batched concurrency | wall-clock O(n·latency) → O(latency) |\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\u002Fvisited for graph traversal when only count needed | Bitset \u002F counter only | O(n) → O(1) |\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 | `structuredClone` or targeted copy | O(n) work and allocation removed |\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: None — orders with missing users still emit `user: undefined` exactly as before\n\u002F\u002F   Reverts so far: 0\n\nexport function getOrdersWithUsers(orders, users) {\n  const userById = new Map(users.map(u => [u.id, u]));\n  return orders.map(o => ({ ...o, user: userById.get(o.userId) }));\n}\n```\n\nOne 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 input key | O(n·f(n)) → O(n + f(n)) |\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 set membership in loop body | `Set` once, reuse | O(n·m) → O(n) |\n| `await` inside a `for` over independent items | `Promise.all` \u002F batched concurrency | wall-clock O(n·latency) → O(latency) |\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\u002Fvisited for graph traversal when only count needed | Bitset \u002F counter only | O(n) → O(1) |\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 | `structuredClone` or targeted copy | O(n) work and allocation removed |\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: None — orders with missing users still emit `user: undefined` exactly as before\n\u002F\u002F   Reverts so far: 0\n\nexport function getOrdersWithUsers(orders, users) {\n  const userById = new Map(users.map(u => [u.id, u]));\n  return orders.map(o => ({ ...o, user: userById.get(o.userId) }));\n}\n```\n\nOne 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":24,"tags":25,"tools":32,"author":38,"source":39,"license":15,"date_added":40,"description":7,"source_repo":41,"source_type":39,"license_source":42},"safe",[26,27,28,29,30,31],"algorithms","big-o","refactoring","optimization","performance","n-plus-one",[33,34,35,36,37],"claude-code","antigravity","cursor","gemini-cli","codex-cli","morsechimwai","community","2026-05-26","morsechimwai\u002Flemmaly","https:\u002F\u002Fgithub.com\u002Fmorsechimwai\u002Flemmaly\u002Fblob\u002Fmain\u002FLICENSE","main","a4404a75dc81d6b7e58c5906b6aaffbcb5e84747","Claude\u002Fantigravity skills\u002Fagentic-awesome-skills\u002Fskills\u002Fcomplexity-cuts",0,"https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills","https:\u002F\u002Fgithub.com\u002FMHassan0000","https:\u002F\u002Fhassanyousaf.vercel.app","Full Stack Developer building web apps, SaaS, AI systems, and automations. Passionate about clean code, UI\u002FUX, backend systems, and turning ideas into products.","2026-08-07 20:42:05",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add MHassan0000\u002FSkills --skill complexity-cuts",{"tool":58,"command":59},"bunx","bunx skills add MHassan0000\u002FSkills --skill complexity-cuts",{"tool":61,"command":62},"pnpm","pnpm dlx skills add MHassan0000\u002FSkills --skill complexity-cuts","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fantigravity skills\u002Fagentic-awesome-skills\u002Fskills\u002Fcomplexity-cuts\u002FSKILL.md",true,[],[67,75,82,89,97,105],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":71,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7AGBX58S04DX8DKKME8N311","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","MIT","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Fvercel-react-best-practices\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":71,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7AGBREE890608Z7YDMAKH27","stop-slop","Remove AI writing patterns from prose. Use when drafting, editing, or reviewing text to eliminate predictable AI tells and produce more human-like writing.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Fstop-slop\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":71,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7AGAS972A2AN7Q5EW8HEAXK","ogilvy-copywriting","Apply David Ogilvy's advertising principles when writing or reviewing copy, headlines, product descriptions, landing pages, ads, emails, or any persuasive text. Use when the goal is copy that sells, not copy that wins awards. Covers positioning, headlines, promises, brand voice, long-form copy, and visual logic. Source: How to Create Advertising That Sells (1972) + Ogilvy on Advertising.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Fogilvy\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7AGAF12803G5JPVMK79AYJB","frontend-design","Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML\u002FCSS layouts, or when styling\u002Fbeautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Ffrontend-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Ffrontend-design\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":101,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M7AG88WWVWCGJY9WA9CH7EY4","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fobra superpower skills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fobra superpower skills\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":109,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M7AG7ZTNV7XQCWDQ9674FBYB","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fobra superpower skills\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fobra superpower skills\u002Fweb-artifacts-builder\u002FSKILL.md",[],[]]