naive-then-optimize
Implement the obvious correct solution first, then optimize while preserving correctness. Use for algorithms, data transformations, and critical code paths.
What this skill does
# Naive-Then-Optimize Skill
## Trigger
Use when implementing algorithms, data transformations, or any code where correctness is critical.
## The Insight
Karpathy: "Write the naive algorithm that is very likely correct first, then ask it to optimize it while preserving correctness."
## Why This Works
1. Naive implementations are easier to verify as correct
2. They serve as a reference/oracle for testing optimized versions
3. Optimization bugs are caught by comparing to naive version
4. You might find the naive version is fast enough
## Process
### Step 1: Implement the Obvious Solution
Don't think about performance. Think about correctness. Write the dumbest, most straightforward code that works.
```typescript
// Naive: O(n²) but obviously correct
function findDuplicates(arr: number[]): number[] {
const duplicates: number[] = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j] && !duplicates.includes(arr[i])) {
duplicates.push(arr[i]);
}
}
}
return duplicates;
}
```
### Step 2: Write Tests Against Naive Implementation
```typescript
describe('findDuplicates', () => {
it('finds duplicates', () => {
expect(findDuplicates([1, 2, 2, 3])).toEqual([2]);
});
it('handles multiple duplicates', () => {
expect(findDuplicates([1, 1, 2, 2, 3])).toEqual([1, 2]);
});
it('handles no duplicates', () => {
expect(findDuplicates([1, 2, 3])).toEqual([]);
});
it('handles empty array', () => {
expect(findDuplicates([])).toEqual([]);
});
});
```
### Step 3: Verify Naive Implementation Passes
Run the tests. They should all pass. If they don't, fix the naive implementation first.
### Step 4: Measure Performance
Is the naive version fast enough? Profile it with realistic data.
```typescript
console.time('naive');
findDuplicates(largeArray);
console.timeEnd('naive');
```
If it's fast enough, **stop here**. Don't optimize code that doesn't need it.
### Step 5: Optimize While Preserving Behavior
Now optimize, but keep the same tests passing:
```typescript
// Optimized: O(n) using a Set
function findDuplicates(arr: number[]): number[] {
const seen = new Set<number>();
const duplicates = new Set<number>();
for (const num of arr) {
if (seen.has(num)) {
duplicates.add(num);
}
seen.add(num);
}
return Array.from(duplicates);
}
```
### Step 6: Property-Based Testing (Optional)
For critical code, test that naive and optimized produce same results:
```typescript
it('optimized matches naive for random inputs', () => {
for (let i = 0; i < 1000; i++) {
const input = generateRandomArray();
const naiveResult = findDuplicatesNaive(input);
const optimizedResult = findDuplicates(input);
expect(optimizedResult.sort()).toEqual(naiveResult.sort());
}
});
```
## When to Use This
- Algorithm implementations
- Data transformations
- Parsers
- Anything where correctness matters more than cleverness
## When to Skip This
- Simple CRUD operations
- Code that's obviously correct
- When the naive version would be identical to the optimized version
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.