Compare commits

..
Author SHA1 Message Date
Prad Nukala 5b6a33088c feat(work): add Minimum Path Sum & Longest Common Subsequence solutions; refactor Unique Paths DP implementation 2026-09-28 13:57:07 -04:00
Prad Nukala e9f76a32be feat: complete lc-62 2026-09-28 12:39:28 -04:00
Prad Nukala 951f958bd9 docs(docs): clarify phase-based content paths and frontmatter ownership in documentation 2026-09-28 11:20:55 -04:00
Prad Nukala d2888360e2 docs(docs): add ProblemBadges component, layout slot, and enrich pages with topics/video frontmatter, plus guide placeholders and topic‑landing map. 2026-09-28 11:20:41 -04:00
Prad Nukala b035d1ffa0 feat(config): add optional frontmatter schemas and Guides tab 2026-09-28 11:19:36 -04:00
Prad Nukala 0473a3651f feat(cli): sync LeetCode topic tags, generate guide placeholders, and write video frontmatter instead of embeds 2026-09-28 11:19:32 -04:00
Prad Nukala a9550769f0 docs(agents): correct bullet prefix for finished topic rule 2026-09-25 14:15:49 -04:00
Prad Nukala 51c8c771c6 feat(config): backdate GitHub releases via custom fetch implementation 2026-09-25 14:15:44 -04:00
Prad Nukala 7cedd235b5 docs(cli): clarify changelog dating uses timever tag instead of API publish date 2026-09-25 14:15:41 -04:00
Prad Nukala 107de04587 docs(agents): clarify release body wording for finished topic rule 2026-09-25 14:07:07 -04:00
Prad Nukala 8787246db7 refactor(cli): simplify release topic naming and summary generation 2026-09-25 14:06:09 -04:00
Prad Nukala 85b54b565e feat(config): add Changelog tab to docs navigation 2026-09-25 14:06:05 -04:00
Prad Nukala 8e8522a773 feat(cli): add release name handling for topic releases 2026-09-25 14:05:52 -04:00
120 changed files with 1382 additions and 429 deletions

No files matched your search

+5 -6
View File
@@ -5,14 +5,13 @@ description: Write the `## Approach` section — a Mermaid flowchart that traces
# Problem approach diagrams # Problem approach diagrams
Every solution page (`apps/docs/content/(<category>)/<num>-<slug>.mdx`) has three Every solution page (`apps/docs/content/(<phase>)/<topic>/<num>-<slug>.mdx`) has a
hand-owned sections around the script-owned one: hand-owned section before the script-owned one:
``` ```
frontmatter → <Badge> → ::::warning (maybe) → ### Example N / ### Constraints frontmatter → ::::warning (maybe) → ### Example N / ### Constraints
## Approach ← this skill (Mermaid flowchart of the code below) ## Approach ← this skill (Mermaid flowchart of the code below)
## Solution ← bun run sync owns this; never edit inside it ## Solution ← bun run sync owns this; never edit inside it
## Explanation ← bun run videos --write (NeetCode embed); not this skill
``` ```
`sync.ts` regenerates only `## Solution`, so an `## Approach` placed **before** it `sync.ts` regenerates only `## Solution`, so an `## Approach` placed **before** it
@@ -144,7 +143,7 @@ there (then `bun run sync`).
- Do not write prose approaches, complexity tables or alternative algorithms — the - Do not write prose approaches, complexity tables or alternative algorithms — the
section is one flowchart (plus the warning callout when the code is broken). section is one flowchart (plus the warning callout when the code is broken).
- Do not touch `## Solution` or anything after it; `## Explanation` is filled by - Do not touch `## Solution` or anything after it, nor the frontmatter `topics:` /
`bun run videos --write`. `video:` keys (`bun run sync` / `bun run videos --write` own them).
- Do not add an approach to `reference/` pages or `index.mdx` — only numbered - Do not add an approach to `reference/` pages or `index.mdx` — only numbered
solution pages (`title: 'NN. …'`) carry one. solution pages (`title: 'NN. …'`) carry one.
+6 -6
View File
@@ -38,7 +38,7 @@ flowchart LR
- **Determinism = idempotency.** Drill/gate sampling uses a seeded PRNG (`rng()` in `apps/api/src/srs.ts`, FNV-1a → mulberry32, seed = date / ISO week); the digest is keyed by ET date in `email_log`; one-tap links are unique on (problem, date, kind). - **Determinism = idempotency.** Drill/gate sampling uses a seeded PRNG (`rng()` in `apps/api/src/srs.ts`, FNV-1a → mulberry32, seed = date / ISO week); the digest is keyed by ET date in `email_log`; one-tap links are unique on (problem, date, kind).
- **DST-proof crons:** each event has two UTC crons; code fires only on the computed ET hour (`etHour`), unit-checked in `apps/api/src/srs.test.ts`. - **DST-proof crons:** each event has two UTC crons; code fires only on the computed ET hour (`etHour`), unit-checked in `apps/api/src/srs.test.ts`.
- **Chained workflows:** `GITHUB_TOKEN`-driven issue closes fire no `issues` events, so `close-topics.yml` chains off `workflow_run` of Close Solved instead. The Worker's webhook uses its own `GH_PAT`, so its events flow normally. - **Chained workflows:** `GITHUB_TOKEN`-driven issue closes fire no `issues` events, so `close-topics.yml` chains off `workflow_run` of Close Solved instead. The Worker's webhook uses its own `GH_PAT`, so its events flow normally.
- **One "finished topic" rule, two consumers.** `apps/cli/topics.ts` (`coreSet()`: every `set:core` sub-issue closed, zero core = never) is read by `close-topics.ts` (closes the topic issue) and `release-topics.ts` (the `release` job of `close-solved.yml`). The release reads the sub-issues, not the topic issue, so the push that finishes a topic releases it in the same run instead of waiting for Close Topics to chain after it. Version = [timever](https://gist.github.com/twolfson/de1b004dd22536b8e668) (`YYYYMMDD.HHMMSS.NNNNNNNNN`, UTC) of the instant the last core problem closed; the tag is annotated and backdated to that instant, on the last first-parent main commit before it; the body is a changelog snapshot at that instant (a one-sentence summary first — Blume's changelog makes it the page's meta description — then closed on the finish day / earlier / open at release, with solution links at the tag). A release is found by its `<!-- release-topics: #N -->` body marker, never by tag name, so re-closing a core problem never mints a second one; an existing release keeps its tag and only has its body rewritten when the render changes. The docs `/changelog` is these releases (`githubReleases` in `apps/docs/blume.config.ts`, fetched at build with `GITHUB_TOKEN`), dated by `published_at` — which the API cannot backdate, so the Aug 24 – Sep 24 backfill reads Sep 25 there, and its true finish time lives in the version and the summary. - **One "finished topic" rule, two consumers.** `apps/cli/topics.ts` (`coreSet()`: every `set:core` sub-issue closed, zero core = never) is read by `close-topics.ts` (closes the topic issue) and `release-topics.ts` (the `release` job of `close-solved.yml`). The release reads the sub-issues, not the topic issue, so the push that finishes a topic releases it in the same run instead of waiting for Close Topics to chain after it. Version = [timever](https://gist.github.com/twolfson/de1b004dd22536b8e668) (`YYYYMMDD.HHMMSS.NNNNNNNNN`, UTC) of the instant the last core problem closed; the tag is annotated and backdated to that instant, on the last first-parent main commit before it; the body is a changelog snapshot at that instant (a one-sentence summary first — Blume's changelog makes it the page's meta description — then closed on the finish day / earlier / open at release, with solution links at the tag). A release is found by its `<!-- release-topics: #N -->` body marker, never by tag name, so re-closing a core problem never mints a second one; an existing release keeps its tag and has its name (the topic title) and body rewritten whenever the render changes. The docs `/changelog` is these releases (`githubReleases` in `apps/docs/blume.config.ts`, fetched at build with `GITHUB_TOKEN`), dated by the timever tag, not `published_at` (which the API cannot backdate): `releasesDatedByTag` rewrites each timever release's `published_at` before Blume maps it, via `custom(githubReleasesSource(…))` because the config-level `githubReleases()` takes no `fetchImpl`. Changing the tag format breaks the changelog dates.
## Key Directories ## Key Directories
@@ -46,7 +46,7 @@ flowchart LR
|---|---| |---|---|
| `work/<1\|3\|7>/<Difficulty>/<Category>/<num>.<slug>.{js,py}` | Solutions, e.g. `work/1/Easy/Array/1.two-sum.py`. The top directory is the spaced-repetition bucket: `1` = first solve, `3`/`7` = the blind re-solves of that problem 3 and 7 days later. Machine-parsed header comment (title / `Difficulty:` / URL / `─` rule / statement) — preserve its exact shape | | `work/<1\|3\|7>/<Difficulty>/<Category>/<num>.<slug>.{js,py}` | Solutions, e.g. `work/1/Easy/Array/1.two-sum.py`. The top directory is the spaced-repetition bucket: `1` = first solve, `3`/`7` = the blind re-solves of that problem 3 and 7 days later. Machine-parsed header comment (title / `Difficulty:` / URL / `─` rule / statement) — preserve its exact shape |
| `apps/cli/` | Flat Bun TS workspace: automation entries (shebang + top-level await) and libraries (no shebang, side-effect-free on import). Root `bun run` scripts delegate here | | `apps/cli/` | Flat Bun TS workspace: automation entries (shebang + top-level await) and libraries (no shebang, side-effect-free on import). Root `bun run` scripts delegate here |
| `apps/docs/` | Blume site (`blume.config.ts`, `content/`, `components/` + `components.ts`, `islands/`, `public/`). `content/(0N-<phase>)/<topic>/<num>-<slug>.mdx` plus one `meta.ts` per phase and per topic folder, all generated by sync: the phase folder is a `(group)` (sidebar section, no route segment), the topic folder is the README campaign topic slug (`tree-dfs/`, `heap-priority-queue/`) and a real route segment (`/tree-dfs/invert-binary-tree`), the `meta.ts` files carry the exact labels, phase/topic numbers and icons so the sidebar reads in curriculum order with each topic a collapsible group, and the page badge is the `work/` data-structure category. A hand-written `(0N-<phase>)/<topic>/index.mdx` (`hidden: true`) is that topic's landing page: Blume ≥ 1.7.3 links the sidebar group row to it (`sliding-window/index.mdx` → `/sliding-window`) and the hidden flag drops the duplicate row. Two kinds of custom MDX component, both import-free on every page: `islands/<Name>.tsx` is hydrated React (auto-discovered; `ProgressDashboard`, `DependencySpine` — the README topic map as data, zoom/pan, nodes link to whatever route Blume's `/api/docs/navigation.json` reports for the topic folder, inert until a topic has pages), `components/<Name>.astro` registered in `components.ts` is static markup plus a custom element for behaviour, the way Blume's own `Frame` is built (`Carousel`/`CarouselImage`: `src` takes a URL, `/file.png`, or the page-relative `../../public/file.png`) | | `apps/docs/` | Blume site (`blume.config.ts`, `content/`, `components/` + `components.ts`, `islands/`, `public/`). `content/(0N-<phase>)/<topic>/<num>-<slug>.mdx` plus one `meta.ts` per phase and per topic folder, all generated by sync: the phase folder is a `(group)` (sidebar section, no route segment), the topic folder is the README campaign topic slug (`tree-dfs/`, `heap-priority-queue/`) and a real route segment (`/tree-dfs/invert-binary-tree`), the `meta.ts` files carry the exact labels, phase/topic numbers and icons so the sidebar reads in curriculum order with each topic a collapsible group. A problem page's badge row (above the title) is rendered, not written: the `PageHeader` slot (`components/ProblemBadges.astro`, wired in `components.ts`) reads the page's `topics:` (LeetCode's topic tags, from sync) and `video:` (NeetCode YouTube id, from `bun run videos`) frontmatter — both declared via `frontmatter.extend` in `blume.config.ts`, hand-rolled Standard Schemas, no zod — and links a tag the campaign teaches to its topic landing page (accent), any other tag to its guide page `/guides/<slug>` (neutral; LeetCode's problem list if the guide is gone), and the video as a red `Explanation` badge. Which tags the campaign teaches is ONE map, `apps/docs/topic-landings.ts` (tag slug → landing routes), read by both that component and sync. `content/guides/<slug>.mdx` (the `Guides` header tab) is one page per tag outside that map: sync creates a placeholder when the file is missing or empty and never touches it again (hand-owned; a guide whose tag no page carries any more is left alone), with frontmatter `list:` — the tag's LeetCode problem list, rendered by the same slot as an orange `LeetCode list` badge; sync also writes `guides/meta.ts`. A hand-written `(0N-<phase>)/<topic>/index.mdx` (`hidden: true`) is that topic's landing page: Blume ≥ 1.7.3 links the sidebar group row to it (`sliding-window/index.mdx` → `/sliding-window`) and the hidden flag drops the duplicate row. Two kinds of custom MDX component, both import-free on every page: `islands/<Name>.tsx` is hydrated React (auto-discovered; `ProgressDashboard`, `DependencySpine` — the README topic map as data, zoom/pan, nodes link to whatever route Blume's `/api/docs/navigation.json` reports for the topic folder, inert until a topic has pages), `components/<Name>.astro` registered in `components.ts` is static markup plus a custom element for behaviour, the way Blume's own `Frame` is built (`Carousel`/`CarouselImage`: `src` takes a URL, `/file.png`, or the page-relative `../../public/file.png`) |
| `apps/api/` | Cloudflare Worker workspace: `src/` modules, `data/schedule.json` (the plan: `date → { topics | problems | gate | sweep }`, human-edited, bundled at deploy), `migrations/` (append-only; `0002` is the +3/+7 ladder rebuild) | | `apps/api/` | Cloudflare Worker workspace: `src/` modules, `data/schedule.json` (the plan: `date → { topics | problems | gate | sweep }`, human-edited, bundled at deploy), `migrations/` (append-only; `0002` is the +3/+7 ladder rebuild) |
| `.github/workflows/` | deploy (docs → Pages with `GITHUB_TOKEN` for the releases-backed changelog, Worker → Cloudflare, on every main push), close-solved (issues + `/admin/solved` + Project `Set`/`Difficulty`, needs `SRS_ADMIN_KEY` and `PROJECT_PAT`; then the `release` job: timever tag + release per finished topic, `contents: write`), close-topics, sync-d1 (issue edits → `/admin/reconcile`), spaced-repetition (daily 06:00 ET cron → today's review issue; `GITHUB_TOKEN` only, no secrets) | | `.github/workflows/` | deploy (docs → Pages with `GITHUB_TOKEN` for the releases-backed changelog, Worker → Cloudflare, on every main push), close-solved (issues + `/admin/solved` + Project `Set`/`Difficulty`, needs `SRS_ADMIN_KEY` and `PROJECT_PAT`; then the `release` job: timever tag + release per finished topic, `contents: write`), close-topics, sync-d1 (issue edits → `/admin/reconcile`), spaced-repetition (daily 06:00 ET cron → today's review issue; `GITHUB_TOKEN` only, no secrets) |
| `.githooks/` | Tracked git hooks; `bun install` points `core.hooksPath` here (root `prepare` script, no husky). `pre-commit` runs `bun run sync` and stages only what sync changed (pages, `apps/docs/redirects.ts`), so a solution, its page and its `/<num>` short link land in one commit; it refuses to run while `work/1` has anything unstaged (sync reads the tree, so the page would not match the commit), and leaves pre-existing dirt under `apps/docs/content` (in-progress `## Approach` prose) unstaged. `git commit --no-verify` for a deliberate partial commit | | `.githooks/` | Tracked git hooks; `bun install` points `core.hooksPath` here (root `prepare` script, no husky). `pre-commit` runs `bun run sync` and stages only what sync changed (pages, `apps/docs/redirects.ts`), so a solution, its page and its `/<num>` short link land in one commit; it refuses to run while `work/1` has anything unstaged (sync reads the tree, so the page would not match the commit), and leaves pre-existing dirt under `apps/docs/content` (in-progress `## Approach` prose) unstaged. `git commit --no-verify` for a deliberate partial commit |
@@ -71,9 +71,9 @@ bun run submit # submit ONE solution to LeetCode (newest scaffold first
# hidden; last_submitted stamped in the db on exit 0) # hidden; last_submitted stamped in the db on exit 0)
bun run sync # work/1 → apps/docs/content/ pages + apps/docs/redirects.ts (/<num> short bun run sync # work/1 → apps/docs/content/ pages + apps/docs/redirects.ts (/<num> short
# links; re-solves are never published) # links; re-solves are never published)
bun run videos # docs pages with no <YouTube> embed → NeetCode video per page bun run videos # docs pages with no `video:` frontmatter → NeetCode video per page
# (channel search scraped, no API key; --write appends the # (channel search scraped, no API key; --write adds the
# `## Explanation` embed; "no NeetCode match" pages stay untouched) # `video:` key; "no NeetCode match" pages stay untouched)
bun run dev|build # Blume docs site (runs in apps/docs/) bun run dev|build # Blume docs site (runs in apps/docs/)
bun run close-solved -- --dry-run # issue reconcilers (also DRY_RUN=1) bun run close-solved -- --dry-run # issue reconcilers (also DRY_RUN=1)
bun run close-topics -- --dry-run bun run close-topics -- --dry-run
@@ -110,7 +110,7 @@ curl -X POST -H "Authorization: Bearer $LINK_KEY" \
- `apps/api/src/index.ts` — router + cron dispatch; `apps/api/wrangler.jsonc` — bindings (`DB`, `EMAIL`), crons, vars; secrets `GH_PAT`/`WEBHOOK_SECRET`/`LINK_KEY` via `wrangler secret put`. - `apps/api/src/index.ts` — router + cron dispatch; `apps/api/wrangler.jsonc` — bindings (`DB`, `EMAIL`), crons, vars; secrets `GH_PAT`/`WEBHOOK_SECRET`/`LINK_KEY` via `wrangler secret put`.
- `apps/api/src/digest.ts` / `apps/api/src/email.tsx` — the daily digest, split data/presentation. `digest.ts` reads D1 into a `DigestData`; `email.tsx` owns every colour and every sentence, and renders both the HTML and (via its own `plainDigest`, not React Email's `plainText` mode, which flattens the tables) the text alternative. The retrieval rules hold by construction: `DigestRow` has no title and no issue field, so a review or drill line *cannot* leak the topic or a solution link. Subject is `(Day N/56) LeetCode Daily Digest`. - `apps/api/src/digest.ts` / `apps/api/src/email.tsx` — the daily digest, split data/presentation. `digest.ts` reads D1 into a `DigestData`; `email.tsx` owns every colour and every sentence, and renders both the HTML and (via its own `plainDigest`, not React Email's `plainText` mode, which flattens the tables) the text alternative. The retrieval rules hold by construction: `DigestRow` has no title and no issue field, so a review or drill line *cannot* leak the topic or a solution link. Subject is `(Day N/56) LeetCode Daily Digest`.
- `apps/api/src/png.ts` — hand-rolled PNG encoder (RGB8, one IDAT, zlib via `CompressionStream("deflate")`, CRC32, 5×7 bitmap font). It exists because every major email client refuses remote SVG, so `/chart/heatmap.png` rasters the heatmap for the digest while `/chart/heatmap.svg` keeps serving the README byte-for-byte. Both come from one `heatmapCells()` so the two pictures cannot drift. - `apps/api/src/png.ts` — hand-rolled PNG encoder (RGB8, one IDAT, zlib via `CompressionStream("deflate")`, CRC32, 5×7 bitmap font). It exists because every major email client refuses remote SVG, so `/chart/heatmap.png` rasters the heatmap for the digest while `/chart/heatmap.svg` keeps serving the README byte-for-byte. Both come from one `heatmapCells()` so the two pictures cannot drift.
- `apps/cli/sync.ts` — work→docs contract: on existing pages only the `<Badge>` line and the `## Solution` section are script-owned, the latter bounded by `solutionEnd()` at the next unfenced top-level heading; human prose before it and any sections after it are never touched. Never hand-write solution pages or edit inside `## Solution`. Two classifications, two homes: the sidebar group is the README topic (`readmeTopics()`, first listing wins for a problem under two topics; a warm-up outside the plan groups under its category at `order: 0`, ahead of topic 1) and the badge is the `work/1/<Difficulty>/<Category>/` category. Topics nest under their README phase (`## Phase N — Name` headings, shortened via `PHASE_ALIASES`): `content/(0N-<phase>)/<topic>/`, both `meta.ts` script-owned and rewritten every run (phase: `Phase N: Name`, `order: N`; topic: label, curriculum order, `TOPIC_ICONS` icon, `display: "group"`). The phase folder is a Blume `(group)` — no route segment, so `/tree-dfs` is unchanged and a landing page there is one level deep, never at `/` — and the topic folder is the real segment; never put a topic `index.mdx` directly inside a `(group)`. A page is `rename`d when its topic or phase changes; a folder every page has left is deleted (climbing into an emptied phase folder) unless it still holds a hand-written `index.mdx` (sync never writes, moves, or deletes one — so page-relative asset paths in a moved landing page are yours to fix). Slugs come from `slugify()`, which glues a leading number to the next token (`1d-dynamic-programming`) because Blume strips `<digits>-` prefixes from routes. The two hand-owned sections around the solution have their own owners: `## Approach` (a Mermaid flowchart tracing the page's code, placed *before* `## Solution` so a re-sync keeps it) is written per the `problem-approach` skill (`/problem-approach` fills every page missing one); `## Explanation` (the NeetCode `<YouTube>` embed, after `## Solution`) is appended by `bun run videos --write` (`apps/cli/videos.ts`). - `apps/cli/sync.ts` — work→docs contract: on existing pages only the frontmatter `icon:` and the `## Solution` section are regenerated, and `topics:` (LeetCode's `topicTags` as `{ name, slug }`, fetched by GraphQL) is filled once — on create, or on any run that finds it missing — never refreshed (delete the key to refetch; offline, the page is written without it and the next sync retries). `## Solution` is the latter bounded by `solutionEnd()` at the next unfenced top-level heading; human prose before it and any sections after it are never touched. Never hand-write solution pages or edit inside `## Solution`. Two classifications, two homes: the sidebar group is the README topic (`readmeTopics()`, first listing wins for a problem under two topics; a warm-up outside the plan groups under its category at `order: 0`, ahead of topic 1) and the `work/1/<Difficulty>/<Category>/` category, which only places an unplanned problem — the page's topic badges are LeetCode's tags, not either classification. Topics nest under their README phase (`## Phase N — Name` headings, shortened via `PHASE_ALIASES`): `content/(0N-<phase>)/<topic>/`, both `meta.ts` script-owned and rewritten every run (phase: `Phase N: Name`, `order: N`; topic: label, curriculum order, `TOPIC_ICONS` icon, `display: "group"`). The phase folder is a Blume `(group)` — no route segment, so `/tree-dfs` is unchanged and a landing page there is one level deep, never at `/` — and the topic folder is the real segment; never put a topic `index.mdx` directly inside a `(group)`. A page is `rename`d when its topic or phase changes; a folder every page has left is deleted (climbing into an emptied phase folder) unless it still holds a hand-written `index.mdx` (sync never writes, moves, or deletes one — so page-relative asset paths in a moved landing page are yours to fix). Slugs come from `slugify()`, which glues a leading number to the next token (`1d-dynamic-programming`) because Blume strips `<digits>-` prefixes from routes. The hand-owned parts have their own owners: `## Approach` (a Mermaid flowchart tracing the page's code, placed *before* `## Solution` so a re-sync keeps it) is written per the `problem-approach` skill (`/problem-approach` fills every page missing one); the frontmatter `video:` (the NeetCode walkthrough, rendered as the red `Explanation` badge) is added by `bun run videos --write` (`apps/cli/videos.ts`).
- `apps/cli/work.ts` — the `work/` layout: bucket paths, `isSolution()`/`solvedInBucket()` (the stub test, shared with `close-solved.ts`), `firstSolved()` (one `git log`, ET dates, keyed by LC number so past layout moves don't matter), and `reviewQueues()` (what each window still owes). Everything that needs to know where a solution file lives, or when it was solved, goes through here. - `apps/cli/work.ts` — the `work/` layout: bucket paths, `isSolution()`/`solvedInBucket()` (the stub test, shared with `close-solved.ts`), `firstSolved()` (one `git log`, ET dates, keyed by LC number so past layout moves don't matter), and `reviewQueues()` (what each window still owes). Everything that needs to know where a solution file lives, or when it was solved, goes through here.
- `apps/api/src/stats.ts` / `apps/cli/stats.ts` / `apps/cli/tui.ts` / `apps/cli/api.ts` — the read side. `buildStats()` is the ONE aggregation: phases, ladder, difficulty, per-topic temperature, gates, the 14-day due queue, and `heat` (every campaign day, zeros and future days included — the docs page windows the tail off it rather than asking a second question). Two readers consume it, the docs island and `bun run stats`, so its shape is both their contract: change all three together. `tui.ts` is hand-rolled ANSI (bars, sparklines, heat cells, alternate screen) on charts.ts's palette, and every chart differs by GLYPH as well as by colour so a piped or `NO_COLOR` dashboard still reads. The TUI recomputes nothing: the only local fact it shows is the `work/` solution count, which is inventory, not schedule. - `apps/api/src/stats.ts` / `apps/cli/stats.ts` / `apps/cli/tui.ts` / `apps/cli/api.ts` — the read side. `buildStats()` is the ONE aggregation: phases, ladder, difficulty, per-topic temperature, gates, the 14-day due queue, and `heat` (every campaign day, zeros and future days included — the docs page windows the tail off it rather than asking a second question). Two readers consume it, the docs island and `bun run stats`, so its shape is both their contract: change all three together. `tui.ts` is hand-rolled ANSI (bars, sparklines, heat cells, alternate screen) on charts.ts's palette, and every chart differs by GLYPH as well as by colour so a piped or `NO_COLOR` dashboard still reads. The TUI recomputes nothing: the only local fact it shows is the `work/` solution count, which is inventory, not schedule.
- `README.md` live charts are Worker endpoints (`/chart/*.svg`, `/badge/gate.svg`, 5-min Camo cache); the docs `/progress` page fetches `/api/stats` client-side (`apps/docs/islands/ProgressDashboard.tsx`). - `README.md` live charts are Worker endpoints (`/chart/*.svg`, `/badge/gate.svg`, 5-min Camo cache); the docs `/progress` page fetches `/api/stats` client-side (`apps/docs/islands/ProgressDashboard.tsx`).
+19 -12
View File
@@ -19,9 +19,9 @@
* The tag is annotated and backdated (tagger date = finish), so * The tag is annotated and backdated (tagger date = finish), so
* `git tag --sort=taggerdate` reads as the campaign's history even for tags * `git tag --sort=taggerdate` reads as the campaign's history even for tags
* minted by a backfill. The release's own published date cannot be backdated * minted by a backfill. The release's own published date cannot be backdated
* (the API has no field for it), and the docs changelog (githubReleases in * (the API has no field for it), so the docs changelog dates each entry from
* apps/docs/blume.config.ts) dates entries by it — so a backfilled entry * this timever tag instead (`releasesDatedByTag` in apps/docs/blume.config.ts)
* carries its real finish time in the version and the body's first sentence. * — the tag format is that contract.
* *
* Reconciles instead of reacting: every finished topic without a release gets * Reconciles instead of reacting: every finished topic without a release gets
* one, so a first run backfills the whole campaign; an existing release keeps * one, so a first run backfills the whole campaign; an existing release keeps
@@ -111,15 +111,16 @@ finished.sort((a, b) => a.finishedAt.localeCompare(b.finishedAt) || a.topic.numb
// ── existing releases ──────────────────────────────────────────── // ── existing releases ────────────────────────────────────────────
/** Topic -> its release. The body is kept in sync with render() on every run. */ /** Topic -> its release. Name and body are kept in sync with the render on every run. */
const released = new Map<number, { id: number; tag: string; body: string }>(); const released = new Map<number, { id: number; tag: string; name: string; body: string }>();
for await (const raw of gh.list(`/repos/${gh.repo}/releases`)) { for await (const raw of gh.list(`/repos/${gh.repo}/releases`)) {
if (!raw || typeof raw !== "object") continue; if (!raw || typeof raw !== "object") continue;
if (!("id" in raw) || typeof raw.id !== "number") continue; if (!("id" in raw) || typeof raw.id !== "number") continue;
if (!("tag_name" in raw) || typeof raw.tag_name !== "string") continue; if (!("tag_name" in raw) || typeof raw.tag_name !== "string") continue;
if (!("body" in raw) || typeof raw.body !== "string") continue; if (!("body" in raw) || typeof raw.body !== "string") continue;
const name = "name" in raw && typeof raw.name === "string" ? raw.name : "";
const m = raw.body.match(/<!-- release-topics: #(\d+) -->/); const m = raw.body.match(/<!-- release-topics: #(\d+) -->/);
if (m) released.set(Number(m[1]), { id: raw.id, tag: raw.tag_name, body: raw.body }); if (m) released.set(Number(m[1]), { id: raw.id, tag: raw.tag_name, name, body: raw.body });
} }
// ── timever ────────────────────────────────────────────────────── // ── timever ──────────────────────────────────────────────────────
@@ -243,8 +244,13 @@ for (const f of finished) {
const { topic } = f; const { topic } = f;
const finishedEt = etDate(new Date(f.finishedAt)); const finishedEt = etDate(new Date(f.finishedAt));
const existing = released.get(topic.number); const existing = released.get(topic.number);
// An existing release keeps its tag and commit; only its body is reconciled. // An existing release keeps its tag and commit; only its name and body are
// reconciled. Its tag may postdate this clone (released by another run), so
// fetch it when missing — read-only, so a dry run does it too.
const tag = existing?.tag ?? tags.get(topic.number)!; const tag = existing?.tag ?? tags.get(topic.number)!;
if (existing && Bun.spawnSync(["git", "rev-parse", "-q", "--verify", `refs/tags/${tag}`], { cwd: ROOT }).exitCode !== 0) {
git("fetch", "-q", "origin", `refs/tags/${tag}:refs/tags/${tag}`);
}
const sha = existing const sha = existing
? git("rev-parse", `${tag}^{commit}`) ? git("rev-parse", `${tag}^{commit}`)
: git("rev-list", "-1", "--first-parent", `--before=${f.finishedAt}`, "HEAD"); : git("rev-list", "-1", "--first-parent", `--before=${f.finishedAt}`, "HEAD");
@@ -263,17 +269,18 @@ for (const f of finished) {
files.set(Number(lc), [...(files.get(Number(lc)) ?? []), path]); files.set(Number(lc), [...(files.get(Number(lc)) ?? []), path]);
} }
const body = render(f, tag, sha, files); const body = render(f, tag, sha, files);
const name = topic.title;
if (existing) { if (existing) {
if (existing.body === body) { if (existing.body === body && existing.name === name) {
report.push([`#${topic.number}`, topic.title, finishedEt, tag, "released"]); report.push([`#${topic.number}`, topic.title, finishedEt, tag, "released"]);
} else if (DRY) { } else if (DRY) {
previews.push(`## ${tag} — ${topic.title}\n\n${body}`); previews.push(`## ${name} (${tag})\n\n${body}`);
report.push([`#${topic.number}`, topic.title, finishedEt, tag, "would update"]); report.push([`#${topic.number}`, topic.title, finishedEt, tag, "would update"]);
} else { } else {
await gh.api(`/repos/${gh.repo}/releases/${existing.id}`, { await gh.api(`/repos/${gh.repo}/releases/${existing.id}`, {
method: "PATCH", method: "PATCH",
body: JSON.stringify({ body }), body: JSON.stringify({ name, body }),
}); });
report.push([`#${topic.number}`, topic.title, finishedEt, tag, "updated"]); report.push([`#${topic.number}`, topic.title, finishedEt, tag, "updated"]);
updated++; updated++;
@@ -282,7 +289,7 @@ for (const f of finished) {
} }
if (DRY) { if (DRY) {
previews.push(`## ${tag} — ${topic.title}\n\n${body}`); previews.push(`## ${name} (${tag})\n\n${body}`);
report.push([`#${topic.number}`, topic.title, finishedEt, tag, "would release"]); report.push([`#${topic.number}`, topic.title, finishedEt, tag, "would release"]);
continue; continue;
} }
@@ -303,7 +310,7 @@ for (const f of finished) {
method: "POST", method: "POST",
body: JSON.stringify({ body: JSON.stringify({
tag_name: tag, tag_name: tag,
name: topic.title, name,
body, body,
make_latest: topic.number === latest ? "true" : "false", make_latest: topic.number === latest ? "true" : "false",
}), }),
+133 -20
View File
@@ -2,20 +2,32 @@
/** /**
* Sync work/1 leetcode solutions into apps/docs/content/ pages. * Sync work/1 leetcode solutions into apps/docs/content/ pages.
* *
* - New problems get a full page (frontmatter, badge, warning, examples, * - New problems get a full page (frontmatter, warning, examples,
* constraints, solution) in the gold-standard format. * constraints, solution) in the gold-standard format.
* - Already-ported pages only get their script-owned parts regenerated — the * - Already-ported pages only get their script-owned parts regenerated — the
* frontmatter `icon:` (`PAGE_ICON`), the `<Badge>` line and the * frontmatter `icon:` (`PAGE_ICON`) and the `## Solution` section — so
* `## Solution` section — so hand-curated prose is never touched. * hand-curated prose is never touched.
* - When a problem is solved in both JavaScript and Python the solution * - When a problem is solved in both JavaScript and Python the solution
* renders as a <CodeGroup> (Python first); single-language solutions * renders as a <CodeGroup> (Python first); single-language solutions
* render as a plain fence. * render as a plain fence.
* - Every page carries LeetCode's own topic tags as frontmatter `topics:`
* (`{ name, slug }` per tag, LeetCode's order), fetched from the GraphQL
* `topicTags` once — when the page is created, or on any later run that
* finds the key missing — and never refreshed after, so a sync with nothing
* new makes no request. Delete the key to refetch it. The page itself
* renders no badges: the docs `PageHeader` slot
* (`apps/docs/components/ProblemBadges.astro`) turns `topics:` and the
* `video:` key `videos.ts` writes into the badge row above the title.
* - Every tag a page carries that no campaign topic teaches (not a key of
* `apps/docs/topic-landings.ts`) gets a placeholder guide page,
* `guides/<slug>.mdx`, with `list:` pointing at LeetCode's problem list for
* the tag. Created once (a missing or empty file), then hand-owned; the tag's
* badge on a problem page links to it.
* *
* Two classifications, two homes. The sidebar group is the campaign TOPIC * The sidebar group is the campaign TOPIC from the README table (`tree-dfs/`,
* from the README table (`tree-dfs/`, ordered by topic number via a * ordered by topic number via a script-owned `meta.ts`). A problem outside the
* script-owned `meta.ts`); the page badge is the data-structure CATEGORY the * plan (warm-ups) has no topic, so it groups under the data-structure CATEGORY
* file sits under in `work/1/<Difficulty>/<Category>/`. A problem outside the * its file sits under in `work/1/<Difficulty>/<Category>/` instead.
* plan (warm-ups) has no topic, so it groups under its category instead.
* *
* Topics nest under their README PHASE: `(01-linear-structures)/tree-dfs/`. * Topics nest under their README PHASE: `(01-linear-structures)/tree-dfs/`.
* The phase folder is a Blume `(group)` — a sidebar section with its own * The phase folder is a Blume `(group)` — a sidebar section with its own
@@ -38,6 +50,8 @@
import { mkdir, readdir, rename, rmdir, unlink } from "node:fs/promises"; import { mkdir, readdir, rename, rmdir, unlink } from "node:fs/promises";
import { basename, dirname, join } from "node:path"; import { basename, dirname, join } from "node:path";
import { TOPIC_LANDINGS } from "../docs/topic-landings.ts";
const ROOT = join(import.meta.dir, "..", ".."); const ROOT = join(import.meta.dir, "..", "..");
const WORK = join(ROOT, "work", "1"); const WORK = join(ROOT, "work", "1");
const DOCS = join(ROOT, "apps", "docs", "content"); const DOCS = join(ROOT, "apps", "docs", "content");
@@ -316,6 +330,83 @@ function groupMeta(topic: Topic): string {
return `import { defineMeta } from "blume";\n\nexport default defineMeta({ ${fields.join(", ")} });\n`; return `import { defineMeta } from "blume";\n\nexport default defineMeta({ ${fields.join(", ")} });\n`;
} }
// ── LeetCode topic tags ──────────────────────────────────────────
/** One of LeetCode's topic tags. `slug` is not derivable from `name` (`Graph Theory` → `graph`). */
interface TopicTag {
name: string;
slug: string;
}
/**
* The problem's topic tags, in LeetCode's order — or undefined, warned, when
* LeetCode cannot answer (offline commit, unknown slug): the page is written
* without `topics:` and the next sync fills it in.
*/
async function fetchTopicTags(sol: Solution): Promise<TopicTag[] | undefined> {
try {
const res = await fetch("https://leetcode.com/graphql", {
method: "POST",
headers: {
"content-type": "application/json",
"user-agent": "Mozilla/5.0",
referer: `https://leetcode.com/problems/${sol.slug}/`,
},
body: JSON.stringify({
query: "query topicTags($titleSlug: String!) { question(titleSlug: $titleSlug) { topicTags { name slug } } }",
variables: { titleSlug: sol.slug },
}),
});
if (!res.ok) throw new Error(`POST /graphql -> ${res.status} ${res.statusText}`);
const data = (await res.json()) as { data?: { question?: { topicTags?: TopicTag[] } | null } };
const tags = data.data?.question?.topicTags;
if (!Array.isArray(tags)) throw new Error("POST /graphql -> no such question");
return tags.map(({ name, slug }) => ({ name, slug }));
} catch (err) {
console.warn(`no topics for ${sol.num}.${sol.slug}: ${err instanceof Error ? err.message : err}`);
return undefined;
}
}
/** The frontmatter `topics:` block, one flow mapping per tag (JSON strings are valid YAML). */
function topicsYaml(tags: TopicTag[]): string {
if (tags.length === 0) return "topics: []";
return ["topics:", ...tags.map((t) => ` - { name: ${JSON.stringify(t.name)}, slug: ${JSON.stringify(t.slug)} }`)].join("\n");
}
/** The frontmatter's `topics:` as sync wrote them (or a human edited them); [] when absent. */
function frontmatterTopics(page: string): TopicTag[] {
const fm = page.match(/^---\n([\s\S]*?)\n---/)?.[1];
const data: unknown = fm ? Bun.YAML.parse(fm) : undefined;
if (!data || typeof data !== "object" || !("topics" in data) || !Array.isArray(data.topics)) return [];
return data.topics.filter((t): t is TopicTag => typeof t?.name === "string" && typeof t?.slug === "string");
}
// ── guides ───────────────────────────────────────────────────────
/**
* Placeholder for a tag no campaign topic teaches: the `/guides/<slug>` page a
* problem's topic badge links to. `list:` is the tag's LeetCode problem list,
* rendered as a badge by the docs `PageHeader` slot. Written once — the page
* is hand-owned from then on.
*/
function guidePage(tag: TopicTag): string {
return [
"---",
`title: ${JSON.stringify(tag.name)}`,
`list: ${JSON.stringify(`https://leetcode.com/problem-list/${tag.slug}/`)}`,
"---",
"",
":::note",
`This guide has not been written yet. The LeetCode list above has every problem tagged ${tag.name}.`,
":::",
"",
].join("\n");
}
/** Folder meta for `guides/`: its own header tab (`navigation.tabs` in blume.config.ts), so only the label. */
const GUIDES_META = `import { defineMeta } from "blume";\n\nexport default defineMeta({ title: "Guides" });\n`;
// ── inline-code formatting heuristics ──────────────────────────── // ── inline-code formatting heuristics ────────────────────────────
/** Identifiers worth backticking in prose, harvested from the code. */ /** Identifiers worth backticking in prose, harvested from the code. */
@@ -420,11 +511,7 @@ function warningText(h: Header): string {
/** Sidebar/page icon for every problem page (Lucide, resolved by Blume). */ /** Sidebar/page icon for every problem page (Lucide, resolved by Blume). */
const PAGE_ICON = "dot"; const PAGE_ICON = "dot";
function badgeLine(sol: Solution): string { function renderPage(sol: Solution, tags: TopicTag[] | undefined): string {
return `<Badge variant="accent">${sol.category}</Badge>`;
}
function renderPage(sol: Solution): string {
const h = sol.header; const h = sol.header;
const ids = identifiers(sol); const ids = identifiers(sol);
const description = h.statement[0]?.replace(/\.\s*$/, "") ?? ""; const description = h.statement[0]?.replace(/\.\s*$/, "") ?? "";
@@ -435,13 +522,12 @@ function renderPage(sol: Solution): string {
`title: '${h.num}. ${h.title.replaceAll("'", "''")}'`, `title: '${h.num}. ${h.title.replaceAll("'", "''")}'`,
/[:#]/.test(description) ? `description: '${description.replaceAll("'", "''")}'` : `description: ${description}`, /[:#]/.test(description) ? `description: '${description.replaceAll("'", "''")}'` : `description: ${description}`,
`icon: ${PAGE_ICON}`, `icon: ${PAGE_ICON}`,
...(tags ? [topicsYaml(tags)] : []),
"sidebar:", "sidebar:",
` label: '${h.title.replaceAll("'", "''")}'`, ` label: '${h.title.replaceAll("'", "''")}'`,
` badge: '${h.difficulty}'`, ` badge: '${h.difficulty}'`,
"---", "---",
"", "",
badgeLine(sol),
"",
); );
const warning = warningText(h); const warning = warningText(h);
@@ -523,10 +609,19 @@ function ensureIcon(page: string): string {
return next + page.slice(fm[0].length); return next + page.slice(fm[0].length);
} }
/** Insert `topics:` before `sidebar:` when the frontmatter lacks it; an existing list is kept as is. */
async function ensureTopics(page: string, sol: Solution): Promise<string> {
const fm = page.match(/^---\n[\s\S]*?\n---/);
if (!fm || /^topics:/m.test(fm[0])) return page;
const tags = await fetchTopicTags(sol);
if (!tags) return page;
return fm[0].replace(/^sidebar:$/m, `${topicsYaml(tags)}\nsidebar:`) + page.slice(fm[0].length);
}
/** /**
* Offset just past the script-owned `## Solution` section: the next top-level * Offset just past the script-owned `## Solution` section: the next top-level
* heading that is not inside a code fence, or end of file. Sections a human * heading that is not inside a code fence, or end of file. Sections a human
* appends after the solution (`## Explanation`, …) survive regeneration. * appends after the solution survive regeneration.
*/ */
function solutionEnd(page: string, from: number): number { function solutionEnd(page: string, from: number): number {
const lines = page.slice(from).split("\n"); const lines = page.slice(from).split("\n");
@@ -555,6 +650,7 @@ const groups = new Map<string, Topic>(); // topic folder -> topic, for meta.ts
const phases = new Map<string, Phase>(); // phase folder -> phase, for meta.ts const phases = new Map<string, Phase>(); // phase folder -> phase, for meta.ts
const vacated = new Set<string>(); // folders a page moved out of; removed below if empty const vacated = new Set<string>(); // folders a page moved out of; removed below if empty
const redirects: string[] = []; // `{ from: "/<num>", to: "/<topic>/<slug>" }` rows, numeric order const redirects: string[] = []; // `{ from: "/<num>", to: "/<topic>/<slug>" }` rows, numeric order
const tags = new Map<string, TopicTag>(); // every tag slug any problem page carries -> tag
for (const sol of ordered) { for (const sol of ordered) {
const langs = Object.keys(sol.code).sort().join("+"); const langs = Object.keys(sol.code).sort().join("+");
@@ -579,7 +675,7 @@ for (const sol of ordered) {
} }
const tail = page.slice(solutionEnd(page, at)); const tail = page.slice(solutionEnd(page, at));
const body = page.slice(0, at) + solutionSection(sol) + (tail ? `\n${tail}` : ""); const body = page.slice(0, at) + solutionSection(sol) + (tail ? `\n${tail}` : "");
const next = ensureIcon(ensureLabel(body, sol.header)).replace(/^<Badge variant="accent">.*<\/Badge>$/m, badgeLine(sol)); const next = await ensureTopics(ensureIcon(ensureLabel(body, sol.header)), sol);
const actions: string[] = []; const actions: string[] = [];
if (existing !== name) { if (existing !== name) {
await rename(join(DOCS, existing), join(DOCS, name)); await rename(join(DOCS, existing), join(DOCS, name));
@@ -591,9 +687,12 @@ for (const sol of ordered) {
actions.push("updated"); actions.push("updated");
} }
report.push([workRef, name, actions.join(" + ") || "skipped (in sync)"]); report.push([workRef, name, actions.join(" + ") || "skipped (in sync)"]);
for (const tag of frontmatterTopics(next)) tags.set(tag.slug, tag);
} else { } else {
await Bun.write(join(DOCS, name), renderPage(sol)); const page = renderPage(sol, await fetchTopicTags(sol));
await Bun.write(join(DOCS, name), page);
report.push([workRef, name, "created"]); report.push([workRef, name, "created"]);
for (const tag of frontmatterTopics(page)) tags.set(tag.slug, tag);
} }
// The route drops the phase `(group)` and the page's number prefix. // The route drops the phase `(group)` and the page's number prefix.
redirects.push(` { from: "/${sol.num}", to: ${JSON.stringify(`/${slugify(topic.name)}/${sol.slug}`)} },`); redirects.push(` { from: "/${sol.num}", to: ${JSON.stringify(`/${slugify(topic.name)}/${sol.slug}`)} },`);
@@ -615,11 +714,25 @@ for (const sol of ordered) {
} }
} }
// Script-owned folder metas — one per live phase and topic folder — rewritten // One guide page per tag that no campaign topic teaches, created when missing
// only when they differ. // (an empty file counts as missing) and never rewritten. A guide whose tag no
// page carries any more is left alone: it is hand-owned.
const guideTags = [...tags.values()]
.filter((tag) => !TOPIC_LANDINGS[tag.slug])
.sort((a, b) => a.slug.localeCompare(b.slug));
for (const tag of guideTags) {
const file = Bun.file(join(DOCS, "guides", `${tag.slug}.mdx`));
if ((await file.exists()) && file.size > 0) continue;
await Bun.write(file, guidePage(tag));
report.push([`tag ${tag.slug}`, `guides/${tag.slug}.mdx`, "created"]);
}
// Script-owned folder metas — one per live phase and topic folder, plus
// guides/ — rewritten only when they differ.
const metas: [label: string, dir: string, meta: string][] = [ const metas: [label: string, dir: string, meta: string][] = [
...[...phases].map(([dir, phase]): [string, string, string] => [`phase ${phase.order}`, dir, phaseMeta(phase)]), ...[...phases].map(([dir, phase]): [string, string, string] => [`phase ${phase.order}`, dir, phaseMeta(phase)]),
...[...groups].map(([dir, topic]): [string, string, string] => [`topic ${topic.order ?? "-"}`, dir, groupMeta(topic)]), ...[...groups].map(([dir, topic]): [string, string, string] => [`topic ${topic.order ?? "-"}`, dir, groupMeta(topic)]),
...(guideTags.length ? [["guides", "guides", GUIDES_META] as [string, string, string]] : []),
]; ];
for (const [label, dir, meta] of metas) { for (const [label, dir, meta] of metas) {
const path = join(DOCS, dir, "meta.ts"); const path = join(DOCS, dir, "meta.ts");
+22 -24
View File
@@ -2,24 +2,23 @@
/** /**
* Find the NeetCode explanation video for every docs page that has none. * Find the NeetCode explanation video for every docs page that has none.
* *
* A finished solution page ends with `## Explanation` holding one * A finished solution page carries frontmatter `video: <YouTube id>` —
* `<YouTube id="…" title="…" />` — NeetCode's walkthrough of the problem. * NeetCode's walkthrough of the problem — which the docs `PageHeader` slot
* `sync.ts` never writes that section (it owns only `## Solution`), so pages * (`apps/docs/components/ProblemBadges.astro`) renders as the red
* accumulate without one. This script lists every numbered page lacking a * "Explanation" badge beside the topic badges. `sync.ts` never writes that key
* `<YouTube` embed and looks each up on NeetCode's two channels, main channel * (it owns `icon:`, `topics:` and `## Solution`), so pages accumulate without
* first, accepting only a title that names the page's exact LC number * one. This script lists every numbered page lacking `video:` and looks each
* (`… - Leetcode 226 - …`) and is not a #short. No YouTube API key: the * up on NeetCode's two channels, main channel first, accepting only a title
* channel search page embeds its results as `ytInitialData` JSON, which is * that names the page's exact LC number (`… - Leetcode 226 - …`) and is not a
* all we parse. Ranking is the channel's own — the first exact-number match * #short. No YouTube API key: the channel search page embeds its results as
* wins. * `ytInitialData` JSON, which is all we parse. Ranking is the channel's own —
* the first exact-number match wins.
* *
* bun apps/cli/videos.ts # report: page → video (or "no match") * bun apps/cli/videos.ts # report: page → video (or "no match")
* bun apps/cli/videos.ts --write # also append `## Explanation` + embed * bun apps/cli/videos.ts --write # also add `video:` to the frontmatter
* *
* --write appends at end of file (below `## Solution`, where sync.ts leaves * --write inserts the key before `sidebar:`. A page with no match is left
* human sections alone) and adds the `## Explanation` heading only when the * untouched, so re-runs are no-ops once every page has its video.
* page lacks it. A page with no match is left untouched, so re-runs are
* no-ops once every page has its embed.
*/ */
import { join } from "node:path"; import { join } from "node:path";
@@ -126,23 +125,21 @@ interface Page {
text: string; text: string;
} }
/** Numbered solution pages without a `<YouTube` embed, by LC number. */ /** The page's frontmatter block, `---` to `---`. */
const FRONTMATTER = /^---\n[\s\S]*?\n---/;
/** Numbered solution pages without a `video:` key, by LC number. */
async function pagesMissingVideo(): Promise<Page[]> { async function pagesMissingVideo(): Promise<Page[]> {
const pages: Page[] = []; const pages: Page[] = [];
for (const rel of await Array.fromAsync(new Bun.Glob("**/*.mdx").scan(DOCS))) { for (const rel of await Array.fromAsync(new Bun.Glob("**/*.mdx").scan(DOCS))) {
const text = await Bun.file(join(DOCS, rel)).text(); const text = await Bun.file(join(DOCS, rel)).text();
const t = text.match(/^title: '(\d+)\./m); const t = text.match(/^title: '(\d+)\./m);
if (t && !text.includes("<YouTube")) pages.push({ num: Number(t[1]), rel, text }); const fm = text.match(FRONTMATTER)?.[0] ?? "";
if (t && !/^video:/m.test(fm)) pages.push({ num: Number(t[1]), rel, text });
} }
return pages.sort((a, b) => a.num - b.num); return pages.sort((a, b) => a.num - b.num);
} }
function withEmbed(page: Page, video: Video): string {
const embed = `<YouTube id="${video.id}" title="${video.title.replaceAll('"', "'")}" />`;
const heading = /^## Explanation\s*$/m.test(page.text) ? "" : "## Explanation\n\n";
return `${page.text.replace(/\s*$/, "\n")}\n${heading}${embed}\n`;
}
// ── main ───────────────────────────────────────────────────────── // ── main ─────────────────────────────────────────────────────────
const missing = await pagesMissingVideo(); const missing = await pagesMissingVideo();
@@ -162,7 +159,8 @@ for (const page of missing) {
found++; found++;
let status = ""; let status = "";
if (WRITE) { if (WRITE) {
await Bun.write(join(DOCS, page.rel), withEmbed(page, video)); const next = page.text.replace(FRONTMATTER, (fm) => fm.replace(/^sidebar:$/m, `video: ${JSON.stringify(video.id)}\nsidebar:`));
await Bun.write(join(DOCS, page.rel), next);
status = "written"; status = "written";
} }
rows.push([page.rel, `https://youtu.be/${video.id}`, `${video.title} (${video.channel})`, status]); rows.push([page.rel, `https://youtu.be/${video.id}`, `${video.title} (${video.channel})`, status]);
+105 -6
View File
@@ -1,7 +1,43 @@
import { defineConfig } from "blume"; import { defineConfig } from "blume";
import { filesystem, githubReleases } from "blume/sources"; import type { StandardSchema } from "blume/core/standard-schema.ts";
import { custom, filesystem } from "blume/sources";
import { githubReleasesSource } from "blume/sources/github-releases.ts";
import redirects from "./redirects"; import redirects from "./redirects";
/**
* GitHub releases → /changelog, dated by the topic's real finish instant.
*
* Blume dates a release entry by `published_at`, which the GitHub API cannot
* backdate — so the topic releases backfilled on one day (apps/cli/
* release-topics.ts) would all read that day. Their tags are timever
* (`YYYYMMDD.HHMMSS.NNNNNNNNN`, UTC) of the moment the topic finished, so this
* fetch rewrites each timever release's `published_at` to that instant before
* Blume maps it; anything else passes through untouched. The config-level
* `githubReleases()` accepts no `fetchImpl`, hence the `custom()` wrap of the
* underlying source (the `blume/sources/*.ts` path the Blume docs use for
* custom sources), with the context the built-in adapter would receive.
*/
const TIMEVER = /^(\d{4})(\d{2})(\d{2})\.(\d{2})(\d{2})(\d{2})\.\d{9}$/;
const releasesDatedByTag: typeof fetch = async (input, init) => {
const res = await fetch(input, init);
if (!res.ok) return res;
const releases: unknown = await res.json();
if (Array.isArray(releases)) {
for (const release of releases) {
const m =
typeof release?.tag_name === "string"
? release.tag_name.match(TIMEVER)
: null;
if (m)
release.published_at = `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`;
}
}
// Blume reads only `ok` and the JSON body, so the original headers (whose
// content-length/encoding describe the upstream bytes) are not carried over.
return Response.json(releases, { status: res.status });
};
// Blume's defaults (`inter`, `ibm-plex-mono`) are fetched from fonts.gstatic.com // Blume's defaults (`inter`, `ibm-plex-mono`) are fetched from fonts.gstatic.com
// on every build, which has timed out on the Pages runner and, fully offline, // on every build, which has timed out on the Pages runner and, fully offline,
// silently ships no fonts at all. The same two families from Fontsource, as // silently ships no fonts at all. The same two families from Fontsource, as
@@ -30,6 +66,49 @@ const plexMono = {
], ],
}; };
/**
* Custom frontmatter, rendered as the badge row by
* components/ProblemBadges.astro. Problem pages: `topics:` is LeetCode's topic
* tags (written by apps/cli/sync.ts), `video:` the NeetCode walkthrough's
* YouTube id (apps/cli/videos.ts). Guide pages (content/guides/, created by
* sync): `list:` is the tag's LeetCode problem list. Blume rejects undeclared
* keys and takes any Standard Schema; these are hand-rolled so the docs
* workspace needs no zod. All optional — every other page carries none.
*/
const optional = <T>(
message: string,
valid: (value: unknown) => value is T,
): StandardSchema<unknown, T | undefined> => ({
"~standard": {
version: 1,
vendor: "prdlk",
validate: (value) =>
value === undefined || valid(value)
? { value }
: { issues: [{ message }] },
},
});
const topicsSchema = optional(
"expected a list of { name, slug } LeetCode topic tags",
(value): value is { name: string; slug: string }[] =>
Array.isArray(value) &&
value.every(
(t) => typeof t?.name === "string" && typeof t?.slug === "string",
),
);
const videoSchema = optional(
"expected an 11-character YouTube video id",
(value): value is string =>
typeof value === "string" && /^[\w-]{11}$/.test(value),
);
const listSchema = optional(
"expected a https://leetcode.com/problem-list/<slug>/ URL",
(value): value is string =>
typeof value === "string" &&
/^https:\/\/leetcode\.com\/problem-list\/[\w-]+\/$/.test(value),
);
export default defineConfig({ export default defineConfig({
title: "prdlk", title: "prdlk",
description: "Documentation for my LeetCode solutions", description: "Documentation for my LeetCode solutions",
@@ -43,14 +122,30 @@ export default defineConfig({
}, },
lastModified: "git", lastModified: "git",
redirects, redirects,
frontmatter: {
extend: { topics: topicsSchema, video: videoSchema, list: listSchema },
},
content: { content: {
sources: [ sources: [
filesystem({ root: "content" }), filesystem({ root: "content" }),
githubReleases({ custom(
prefix: "changelog", githubReleasesSource(
owner: "prdlk", {
repo: "leetcode", name: "changelog",
}), prefix: "changelog",
owner: "prdlk",
repo: "leetcode",
fetchImpl: releasesDatedByTag,
},
// What resolve.ts hands the built-in adapter: `.blume/cache/<name>/`,
// and a refresh on every load (the source reads nothing else).
{
projectRoot: import.meta.dirname,
cacheDir: `${import.meta.dirname}/.blume/cache/changelog`,
mode: "build",
},
),
),
], ],
}, },
theme: { theme: {
@@ -60,5 +155,9 @@ export default defineConfig({
sidebar: { sidebar: {
display: "flat", // "flat" | "group" | "page" display: "flat", // "flat" | "group" | "page"
}, },
tabs: [
{ label: "Guides", path: "/guides" },
{ label: "Changelog", path: "/changelog" },
],
}, },
}); });
+7 -3
View File
@@ -1,7 +1,7 @@
/** /**
* Project MDX components, available on every page with no import. Static * Project MDX components, available on every page with no import, and layout
* `.astro` files ship no framework JS (a custom element carries any * slot overrides. Static `.astro` files ship no framework JS (a custom element
* behaviour); interactive React lives in `islands/` instead. * carries any behaviour); interactive React lives in `islands/` instead.
*/ */
import { defineComponents } from "blume"; import { defineComponents } from "blume";
@@ -10,4 +10,8 @@ export default defineComponents({
Carousel: "./components/Carousel.astro", Carousel: "./components/Carousel.astro",
CarouselImage: "./components/CarouselImage.astro", CarouselImage: "./components/CarouselImage.astro",
}, },
layout: {
// Problem pages' topic + explanation badges, from `topics:` / `video:` frontmatter.
PageHeader: "./components/ProblemBadges.astro",
},
}); });
+92
View File
@@ -0,0 +1,92 @@
---
/**
* The `PageHeader` slot: the badge row above a page's title. Blume hands the
* slot only the route, so the page's frontmatter is looked up through the
* route manifest — the same `getEntry` call Blume's own page template makes.
* Pages with none of the keys below (landing pages, the changelog) render
* nothing.
*
* - `topics:` (problem pages, written by `apps/cli/sync.ts`) is LeetCode's own
* topic tags. A tag the campaign teaches (`topic-landings.ts`) links to that
* topic's landing page and reads accent; any other tag links to its guide
* page, `/guides/<slug>` (sync creates one per such tag), and reads neutral.
* - `video:` (problem pages, written by `apps/cli/videos.ts`) is the NeetCode
* walkthrough's YouTube id, the red "Explanation" badge at the end of the row.
* - `list:` (guide pages, written by sync on create) is the tag's LeetCode
* problem list, an orange "LeetCode list" badge.
*
* A tag naming two campaign topics (`Depth-First Search` is both Tree DFS and
* Graph DFS) links to the page's own topic — its route's first segment — when
* that is one of them; otherwise DFS/BFS prefer the tree topic for a problem
* LeetCode also tags `Tree` and the graph topic for the rest. A route the site
* does not serve (a landing or guide page removed) falls back to LeetCode's
* problem list for the tag, so a badge never links to a 404.
*/
import { getEntry } from "astro:content";
import data from "blume:data";
import Badge from "blume/components/content/Badge.astro";
import { withBase } from "blume/components/islands/base-path.ts";
import { TOPIC_LANDINGS } from "../topic-landings.ts";
interface Props {
route: string;
}
interface TopicTag {
name: string;
slug: string;
}
const { route } = Astro.props;
const at = data.routes.find((r: { path: string }) => r.path === route);
const entry = at ? await getEntry(at.collection, at.entryId) : undefined;
const tags: TopicTag[] = entry?.data.topics ?? [];
const video: string | undefined = entry?.data.video;
const list: string | undefined = entry?.data.list;
const served = new Set(data.routes.map((r: { path: string }) => r.path));
const own = `/${route.split("/")[1]}`;
const prefer = tags.some((t) => t.slug === "tree") ? "/tree-" : "/graph-";
const badges = tags.map((tag) => {
const landings = (TOPIC_LANDINGS[tag.slug] ?? []).filter((path) => served.has(path));
const landing = landings.includes(own) ? own : (landings.find((p) => p.startsWith(prefer)) ?? landings[0]);
if (landing) return { name: tag.name, href: withBase(landing), accent: true, external: false };
const guide = `/guides/${tag.slug}`;
if (served.has(guide)) return { name: tag.name, href: withBase(guide), accent: false, external: false };
return { name: tag.name, href: `https://leetcode.com/problem-list/${tag.slug}/`, accent: false, external: true };
});
const linkClass = "no-underline transition-opacity hover:opacity-80";
---
{
(badges.length > 0 || video || list) && (
<div class="not-prose mx-auto mb-4 flex max-w-content flex-wrap gap-1.5">
{badges.map((b) => (
<a
href={b.href}
target={b.external ? "_blank" : undefined}
rel={b.external ? "noopener" : undefined}
class={linkClass}
>
<Badge variant={b.accent ? "accent" : "default"}>{b.name}</Badge>
</a>
))}
{video && (
<a href={`https://www.youtube.com/watch?v=${video}`} target="_blank" rel="noopener" class={linkClass}>
<Badge variant="danger" icon="youtube">
Explanation
</Badge>
</a>
)}
{list && (
<a href={list} target="_blank" rel="noopener" class={linkClass}>
<Badge variant="warning" icon="list">
LeetCode list
</Badge>
</a>
)}
</div>
)
}
@@ -2,13 +2,15 @@
title: '153. Find Minimum in Rotated Sorted Array' title: '153. Find Minimum in Rotated Sorted Array'
description: 'Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:' description: 'Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:'
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Binary Search", slug: "binary-search" }
video: "nIVW4P8b1VA"
sidebar: sidebar:
label: 'Find Minimum in Rotated Sorted Array' label: 'Find Minimum in Rotated Sorted Array'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
:::: ::::
@@ -69,7 +71,3 @@ class Solution:
return nums[lowest_index] return nums[lowest_index]
``` ```
## Explanation
<YouTube id="nIVW4P8b1VA" title="Find Minimum in Rotated Sorted Array - Binary Search - Leetcode 153 - Python" />
@@ -2,13 +2,15 @@
title: '33. Search in Rotated Sorted Array' title: '33. Search in Rotated Sorted Array'
description: There is an integer array nums sorted in ascending order (with distinct values) description: There is an integer array nums sorted in ascending order (with distinct values)
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Binary Search", slug: "binary-search" }
video: "U8XENwh8Oy8"
sidebar: sidebar:
label: 'Search in Rotated Sorted Array' label: 'Search in Rotated Sorted Array'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
You must write an algorithm with O(log n) runtime complexity. You must write an algorithm with O(log n) runtime complexity.
:::: ::::
@@ -93,7 +95,3 @@ var search = function(nums, target) {
return -1; return -1;
}; };
``` ```
## Explanation
<YouTube id="U8XENwh8Oy8" title="Search in rotated sorted array - Leetcode 33 - Python" />
@@ -2,13 +2,15 @@
title: '35. Search Insert Position' title: '35. Search Insert Position'
description: Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order description: Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Binary Search", slug: "binary-search" }
video: "K-RYzDZkzCI"
sidebar: sidebar:
label: 'Search Insert Position' label: 'Search Insert Position'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
You must write an algorithm with O(log n) runtime complexity. You must write an algorithm with O(log n) runtime complexity.
:::: ::::
@@ -66,7 +68,3 @@ class Solution:
return (l + r) // 2 + 1 return (l + r) // 2 + 1
``` ```
## Explanation
<YouTube id="K-RYzDZkzCI" title="Search Insert Position - Binary Search - Leetcode 35 - Python" />
@@ -2,13 +2,15 @@
title: '704. Binary Search' title: '704. Binary Search'
description: Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1 description: Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Binary Search", slug: "binary-search" }
video: "s4DPM8ct1pI"
sidebar: sidebar:
label: 'Binary Search' label: 'Binary Search'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
You must write an algorithm with O(log n) runtime complexity. You must write an algorithm with O(log n) runtime complexity.
:::: ::::
@@ -71,7 +73,3 @@ var search = function(nums, target) {
return -1; return -1;
}; };
``` ```
## Explanation
<YouTube id="s4DPM8ct1pI" title="Binary Search - Leetcode 704 - Python" />
@@ -2,13 +2,16 @@
title: '74. Search a 2D Matrix' title: '74. Search a 2D Matrix'
description: 'You are given an m x n integer matrix matrix with the following two properties:' description: 'You are given an m x n integer matrix matrix with the following two properties:'
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Binary Search", slug: "binary-search" }
- { name: "Matrix", slug: "matrix" }
video: "Ber2pi2C0j0"
sidebar: sidebar:
label: 'Search a 2D Matrix' label: 'Search a 2D Matrix'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
You must write a solution in O(log(m * n)) time complexity. You must write a solution in O(log(m * n)) time complexity.
:::: ::::
@@ -86,7 +89,3 @@ class Solution:
return True return True
return False return False
``` ```
## Explanation
<YouTube id="Ber2pi2C0j0" title="Search a 2D Matrix - Leetcode 74 - Python" />
@@ -2,13 +2,15 @@
title: '875. Koko Eating Bananas' title: '875. Koko Eating Bananas'
description: Koko loves to eat bananas. There are n piles of bananas, the i^th pile has piles[i] bananas. The guards have gone and will come back in h hours description: Koko loves to eat bananas. There are n piles of bananas, the i^th pile has piles[i] bananas. The guards have gone and will come back in h hours
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Binary Search", slug: "binary-search" }
video: "U2SozAs9RzA"
sidebar: sidebar:
label: 'Koko Eating Bananas' label: 'Koko Eating Bananas'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `piles = [3,6,7,11], h = 8` - Input: `piles = [3,6,7,11], h = 8`
- Output: `4` - Output: `4`
@@ -77,7 +79,3 @@ var minEatingSpeed = function(piles, h) {
return l; return l;
}; };
``` ```
## Explanation
<YouTube id="U2SozAs9RzA" title="Koko Eating Bananas - Binary Search - Leetcode 875 - Python" />
@@ -2,13 +2,15 @@
title: '1. Two Sum' title: '1. Two Sum'
description: You are given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target description: You are given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Hash Table", slug: "hash-table" }
video: "KLlXCFG5TnA"
sidebar: sidebar:
label: 'Two Sum' label: 'Two Sum'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
Can you come up with an algorithm that is less than O(n^2) time complexity? Can you come up with an algorithm that is less than O(n^2) time complexity?
:::: ::::
@@ -60,7 +62,3 @@ class Solution:
seen[num] = i seen[num] = i
return [] return []
``` ```
## Explanation
<YouTube id="KLlXCFG5TnA" title="Two Sum - Leetcode 1 - HashMap - Python" />
@@ -2,13 +2,14 @@
title: '1832. Check if the Sentence Is Pangram' title: '1832. Check if the Sentence Is Pangram'
description: A pangram is a sentence where every letter of the English alphabet appears at least once description: A pangram is a sentence where every letter of the English alphabet appears at least once
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
sidebar: sidebar:
label: 'Check if the Sentence Is Pangram' label: 'Check if the Sentence Is Pangram'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `sentence = "thequickbrownfoxjumpsoverthelazydog"` - Input: `sentence = "thequickbrownfoxjumpsoverthelazydog"`
- Output: `true` - Output: `true`
@@ -2,13 +2,16 @@
title: '217. Contains Duplicate' title: '217. Contains Duplicate'
description: Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct description: Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Hash Table", slug: "hash-table" }
- { name: "Sorting", slug: "sorting" }
video: "3OamzN90kPg"
sidebar: sidebar:
label: 'Contains Duplicate' label: 'Contains Duplicate'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `nums = [1,2,3,1]` - Input: `nums = [1,2,3,1]`
- Output: `true` - Output: `true`
@@ -48,7 +51,3 @@ class Solution:
def containsDuplicate(self, nums: List[int]) -> bool: def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) != len(nums) return len(set(nums)) != len(nums)
``` ```
## Explanation
<YouTube id="3OamzN90kPg" title="Contains Duplicate - Leetcode 217 - Python" />
@@ -2,13 +2,16 @@
title: '242. Valid Anagram' title: '242. Valid Anagram'
description: Given two strings s and t, return true if t is an anagram of s, and false otherwise description: Given two strings s and t, return true if t is an anagram of s, and false otherwise
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
- { name: "Sorting", slug: "sorting" }
video: "9UtInBqnCgA"
sidebar: sidebar:
label: 'Valid Anagram' label: 'Valid Anagram'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Hash Table</Badge>
::::warning ::::warning
What if the inputs contain Unicode characters? How would you adapt your solution to such a case? What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
:::: ::::
@@ -60,7 +63,3 @@ var isAnagram = function(s, t) {
return true; return true;
}; };
``` ```
## Explanation
<YouTube id="9UtInBqnCgA" title="Valid Anagram - Leetcode 242 - Python" />
@@ -2,13 +2,21 @@
title: '347. Top K Frequent Elements' title: '347. Top K Frequent Elements'
description: Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order description: Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Hash Table", slug: "hash-table" }
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
- { name: "Sorting", slug: "sorting" }
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
- { name: "Bucket Sort", slug: "bucket-sort" }
- { name: "Counting", slug: "counting" }
- { name: "Quickselect", slug: "quickselect" }
video: "YPTqKIgVk-k"
sidebar: sidebar:
label: 'Top K Frequent Elements' label: 'Top K Frequent Elements'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
Your algorithm's time complexity must be better than O(n log n), where n is the array's size. Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
:::: ::::
@@ -60,7 +68,3 @@ var topKFrequent = function (nums, k) {
.slice(0, k); .slice(0, k);
}; };
``` ```
## Explanation
<YouTube id="YPTqKIgVk-k" title="Top K Frequent Elements - Bucket Sort - Leetcode 347 - Python" />
@@ -2,13 +2,17 @@
title: '387. First Unique Character in a String' title: '387. First Unique Character in a String'
description: Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1 description: Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
- { name: "Queue", slug: "queue" }
- { name: "Counting", slug: "counting" }
video: "rBENYgWy3xU"
sidebar: sidebar:
label: 'First Unique Character in a String' label: 'First Unique Character in a String'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `s = "leetcode"` - Input: `s = "leetcode"`
- Output: `0` - Output: `0`
@@ -58,7 +62,3 @@ var firstUniqChar = function (s) {
return -1; return -1;
}; };
``` ```
## Explanation
<YouTube id="rBENYgWy3xU" title="First Unique Character in a String - Leetcode 387 - Python" />
@@ -2,13 +2,19 @@
title: '451. Sort Characters By Frequency' title: '451. Sort Characters By Frequency'
description: Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string description: Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
- { name: "Sorting", slug: "sorting" }
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
- { name: "Bucket Sort", slug: "bucket-sort" }
- { name: "Counting", slug: "counting" }
video: "OXdXc9HTrIg"
sidebar: sidebar:
label: 'Sort Characters By Frequency' label: 'Sort Characters By Frequency'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `s = "tree"` - Input: `s = "tree"`
- Output: `"eert"` - Output: `"eert"`
@@ -60,7 +66,3 @@ var frequencySort = function (s) {
.join(""); .join("");
}; };
``` ```
## Explanation
<YouTube id="OXdXc9HTrIg" title="Sort Characters By Frequency - Leetcode 451 - Python" />
@@ -2,13 +2,17 @@
title: '49. Group Anagrams' title: '49. Group Anagrams'
description: Given an array of strings strs, group the anagrams together. You can return the answer in any order description: Given an array of strings strs, group the anagrams together. You can return the answer in any order
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
- { name: "Sorting", slug: "sorting" }
video: "vzdNOK2oB2E"
sidebar: sidebar:
label: 'Group Anagrams' label: 'Group Anagrams'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `strs = ["eat","tea","tan","ate","nat","bat"]` - Input: `strs = ["eat","tea","tan","ate","nat","bat"]`
- Output: `[["bat"],["nat","tan"],["ate","eat","tea"]]` - Output: `[["bat"],["nat","tan"],["ate","eat","tea"]]`
@@ -65,7 +69,3 @@ var groupAnagrams = function(strs) {
return Object.values(anagrams); return Object.values(anagrams);
}; };
``` ```
## Explanation
<YouTube id="vzdNOK2oB2E" title="Group Anagrams - Categorize Strings by Count - Leetcode 49" />
@@ -2,13 +2,16 @@
title: '739. Daily Temperatures' title: '739. Daily Temperatures'
description: Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the i^th day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead description: Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the i^th day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Stack", slug: "stack" }
- { name: "Monotonic Stack", slug: "monotonic-stack" }
video: "cTBiBSnjO3c"
sidebar: sidebar:
label: 'Daily Temperatures' label: 'Daily Temperatures'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `temperatures = [73,74,75,71,69,72,76,73]` - Input: `temperatures = [73,74,75,71,69,72,76,73]`
- Output: `[1,1,4,2,1,1,0,0]` - Output: `[1,1,4,2,1,1,0,0]`
@@ -54,7 +57,3 @@ class Solution:
stack.append(i) stack.append(i)
return ans return ans
``` ```
## Explanation
<YouTube id="cTBiBSnjO3c" title="Daily Temperatures - Monotonic Stack - Leetcode 739 - Python" />
@@ -2,13 +2,17 @@
title: '853. Car Fleet' title: '853. Car Fleet'
description: There are n cars at given miles away from the starting mile 0, traveling to reach the mile target description: There are n cars at given miles away from the starting mile 0, traveling to reach the mile target
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Stack", slug: "stack" }
- { name: "Sorting", slug: "sorting" }
- { name: "Monotonic Stack", slug: "monotonic-stack" }
video: "Pr6T-3yB9RM"
sidebar: sidebar:
label: 'Car Fleet' label: 'Car Fleet'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]` - Input: `target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]`
- Output: `3` - Output: `3`
@@ -62,7 +66,3 @@ class Solution:
return len(stack) return len(stack)
``` ```
## Explanation
<YouTube id="Pr6T-3yB9RM" title="Car Fleet - Leetcode 853 - Python" />
@@ -2,13 +2,15 @@
title: '238. Product of Array Except Self' title: '238. Product of Array Except Self'
description: Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i] description: Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Prefix Sum", slug: "prefix-sum" }
video: "bNvIQI2wAjk"
sidebar: sidebar:
label: 'Product of Array Except Self' label: 'Product of Array Except Self'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
You must write an algorithm that runs in O(n) time and without using the division operation. You must write an algorithm that runs in O(n) time and without using the division operation.
Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.) Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
@@ -63,7 +65,3 @@ var productExceptSelf = function(nums) {
return answer; return answer;
}; };
``` ```
## Explanation
<YouTube id="bNvIQI2wAjk" title="Product of Array Except Self - Leetcode 238 - Python" />
@@ -2,13 +2,16 @@
title: '303. Range Sum Query - Immutable' title: '303. Range Sum Query - Immutable'
description: Given an integer array nums, handle multiple queries of the following type description: Given an integer array nums, handle multiple queries of the following type
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Design", slug: "design" }
- { name: "Prefix Sum", slug: "prefix-sum" }
video: "2pndAmo_sMA"
sidebar: sidebar:
label: 'Range Sum Query - Immutable' label: 'Range Sum Query - Immutable'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `["NumArray", "sumRange", "sumRange", "sumRange"]` `[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]` - Input: `["NumArray", "sumRange", "sumRange", "sumRange"]` `[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]`
- Output: `[null, 1, -1, -3]` - Output: `[null, 1, -1, -3]`
@@ -66,7 +69,3 @@ class NumArray {
* var param_1 = obj.sumRange(left,right) * var param_1 = obj.sumRange(left,right)
*/ */
``` ```
## Explanation
<YouTube id="2pndAmo_sMA" title="Range Sum Query Immutable - Leetcode 303 - Python" />
@@ -2,13 +2,16 @@
title: '560. Subarray Sum Equals K' title: '560. Subarray Sum Equals K'
description: Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k description: Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Hash Table", slug: "hash-table" }
- { name: "Prefix Sum", slug: "prefix-sum" }
video: "fFVZt-6sgyo"
sidebar: sidebar:
label: 'Subarray Sum Equals K' label: 'Subarray Sum Equals K'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `nums = [1,1,1], k = 2` - Input: `nums = [1,1,1], k = 2`
- Output: `2` - Output: `2`
@@ -65,7 +68,3 @@ var subarraySum = function(nums, k) {
return count return count
}; };
``` ```
## Explanation
<YouTube id="fFVZt-6sgyo" title="Subarray Sum Equals K - Prefix Sums - Leetcode 560 - Python" />
@@ -2,13 +2,15 @@
title: '121. Best Time to Buy and Sell Stock' title: '121. Best Time to Buy and Sell Stock'
description: You are given an array prices where prices[i] is the price of a given stock on the i^th day description: You are given an array prices where prices[i] is the price of a given stock on the i^th day
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Dynamic Programming", slug: "dynamic-programming" }
video: "1pkOgXD63yU"
sidebar: sidebar:
label: 'Best Time to Buy and Sell Stock' label: 'Best Time to Buy and Sell Stock'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `prices = [7,1,5,3,6,4]` - Input: `prices = [7,1,5,3,6,4]`
- Output: `5` - Output: `5`
@@ -55,7 +57,3 @@ class Solution:
ans = max(ans, curr) ans = max(ans, curr)
return ans return ans
``` ```
## Explanation
<YouTube id="1pkOgXD63yU" title="Sliding Window: Best Time to Buy and Sell Stock - Leetcode 121 - Python" />
@@ -2,13 +2,16 @@
title: '3. Longest Substring Without Repeating Characters' title: '3. Longest Substring Without Repeating Characters'
description: Given a string s, find the length of the longest substring without duplicate characters description: Given a string s, find the length of the longest substring without duplicate characters
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
- { name: "Sliding Window", slug: "sliding-window" }
video: "wiGpQwVHdE0"
sidebar: sidebar:
label: 'Longest Substring Without Repeating Characters' label: 'Longest Substring Without Repeating Characters'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `s = "abcabcbb"` - Input: `s = "abcabcbb"`
- Output: `3` - Output: `3`
@@ -61,7 +64,3 @@ class Solution:
return ans return ans
``` ```
## Explanation
<YouTube id="wiGpQwVHdE0" title="Longest Substring Without Repeating Characters - Leetcode 3 - Python" />
@@ -2,13 +2,16 @@
title: '424. Longest Repeating Character Replacement' title: '424. Longest Repeating Character Replacement'
description: You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times description: You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
- { name: "Sliding Window", slug: "sliding-window" }
video: "gqXU1UyA8pk"
sidebar: sidebar:
label: 'Longest Repeating Character Replacement' label: 'Longest Repeating Character Replacement'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `s = "ABAB", k = 2` - Input: `s = "ABAB", k = 2`
- Output: `4` - Output: `4`
@@ -61,7 +64,3 @@ class Solution:
res = max(res, r - l + 1) res = max(res, r - l + 1)
return res return res
``` ```
## Explanation
<YouTube id="gqXU1UyA8pk" title="Longest Repeating Character Replacement - Leetcode 424 - Python" />
@@ -2,13 +2,17 @@
title: '567. Permutation in String' title: '567. Permutation in String'
description: Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise description: Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "String", slug: "string" }
- { name: "Sliding Window", slug: "sliding-window" }
video: "UbyhOgBN834"
sidebar: sidebar:
label: 'Permutation in String' label: 'Permutation in String'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `s1 = "ab", s2 = "eidbaooo"` - Input: `s1 = "ab", s2 = "eidbaooo"`
- Output: `true` - Output: `true`
@@ -68,7 +72,3 @@ class Solution:
return False return False
``` ```
## Explanation
<YouTube id="UbyhOgBN834" title="Permutation in String - Leetcode 567 - Python" />
@@ -2,13 +2,16 @@
title: '150. Evaluate Reverse Polish Notation' title: '150. Evaluate Reverse Polish Notation'
description: You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation description: You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Math", slug: "math" }
- { name: "Stack", slug: "stack" }
video: "iu0082c4HDE"
sidebar: sidebar:
label: 'Evaluate Reverse Polish Notation' label: 'Evaluate Reverse Polish Notation'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `tokens = ["2","1","+","3","*"]` - Input: `tokens = ["2","1","+","3","*"]`
- Output: `9` - Output: `9`
@@ -69,7 +72,3 @@ class Solution:
return stack[0] return stack[0]
``` ```
## Explanation
<YouTube id="iu0082c4HDE" title="Evaluate Reverse Polish Notation - Leetcode 150 - Python" />
@@ -2,13 +2,15 @@
title: '155. Min Stack' title: '155. Min Stack'
description: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time description: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time
icon: dot icon: dot
topics:
- { name: "Stack", slug: "stack" }
- { name: "Design", slug: "design" }
video: "qkLl7nAwDPo"
sidebar: sidebar:
label: 'Min Stack' label: 'Min Stack'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Stack</Badge>
::::warning ::::warning
You must implement a solution with O(1) time complexity for each function. You must implement a solution with O(1) time complexity for each function.
:::: ::::
@@ -77,7 +79,3 @@ class MinStack:
# param_3 = obj.top() # param_3 = obj.top()
# param_4 = obj.getMin() # param_4 = obj.getMin()
``` ```
## Explanation
<YouTube id="qkLl7nAwDPo" title="Design Min Stack - Amazon Interview Question - Leetcode 155 - Python" />
@@ -2,13 +2,16 @@
title: '20. Valid Parentheses' title: '20. Valid Parentheses'
description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid
icon: dot icon: dot
topics:
- { name: "String", slug: "string" }
- { name: "Stack", slug: "stack" }
- { name: "Bracket Sequences", slug: "bracket-sequences" }
video: "WTzjTskDFMg"
sidebar: sidebar:
label: 'Valid Parentheses' label: 'Valid Parentheses'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">String</Badge>
### Example 1: ### Example 1:
- Input: `s = "()"` - Input: `s = "()"`
- Output: `true` - Output: `true`
@@ -71,7 +74,3 @@ class Solution:
return True if not stack else False return True if not stack else False
``` ```
## Explanation
<YouTube id="WTzjTskDFMg" title="Valid Parentheses - Stack - Leetcode 20 - Python" />
@@ -2,13 +2,16 @@
title: '11. Container With Most Water' title: '11. Container With Most Water'
description: You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i^th line are (i, 0) and (i, height[i]) description: You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i^th line are (i, 0) and (i, height[i])
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "Greedy", slug: "greedy" }
video: "UuiTKBwPgAo"
sidebar: sidebar:
label: 'Container With Most Water' label: 'Container With Most Water'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
Notice that you may not slant the container. Notice that you may not slant the container.
:::: ::::
@@ -63,7 +66,3 @@ class Solution:
return res return res
``` ```
## Explanation
<YouTube id="UuiTKBwPgAo" title="Container with Most Water - Leetcode 11 - Python" />
@@ -2,13 +2,15 @@
title: '125. Valid Palindrome' title: '125. Valid Palindrome'
description: A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers description: A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers
icon: dot icon: dot
topics:
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "String", slug: "string" }
video: "jJXJ16kPFWg"
sidebar: sidebar:
label: 'Valid Palindrome' label: 'Valid Palindrome'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Two Pointers</Badge>
### Example 1: ### Example 1:
- Input: `s = "A man, a plan, a canal: Panama"` - Input: `s = "A man, a plan, a canal: Panama"`
- Output: `true` - Output: `true`
@@ -64,7 +66,3 @@ var isPalindrome = function(s) {
return true; return true;
}; };
``` ```
## Explanation
<YouTube id="jJXJ16kPFWg" title="Valid Palindrome - Leetcode 125 - Python" />
@@ -2,13 +2,16 @@
title: '15. 3Sum' title: '15. 3Sum'
description: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0 description: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "Sorting", slug: "sorting" }
video: "jzZsG8n2R9A"
sidebar: sidebar:
label: '3Sum' label: '3Sum'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
Notice that the solution set must not contain duplicate triplets. Notice that the solution set must not contain duplicate triplets.
:::: ::::
@@ -99,7 +102,3 @@ class Solution:
return result return result
``` ```
## Explanation
<YouTube id="jzZsG8n2R9A" title="3Sum - Leetcode 15 - Python" />
@@ -2,13 +2,16 @@
title: '167. Two Sum II - Input Array Is Sorted' title: '167. Two Sum II - Input Array Is Sorted'
description: Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length description: Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "Binary Search", slug: "binary-search" }
video: "cQ1Oz4ckceM"
sidebar: sidebar:
label: 'Two Sum II - Input Array Is Sorted' label: 'Two Sum II - Input Array Is Sorted'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
Your solution must use only constant extra space. Your solution must use only constant extra space.
:::: ::::
@@ -70,7 +73,3 @@ class Solution:
j-=1 j-=1
return [] return []
``` ```
## Explanation
<YouTube id="cQ1Oz4ckceM" title="TWO SUM II - Amazon Coding Interview Question - Leetcode 167 - Python" />
@@ -2,13 +2,15 @@
title: '344. Reverse String' title: '344. Reverse String'
description: Write a function that reverses a string. The input string is given as an array of characters s description: Write a function that reverses a string. The input string is given as an array of characters s
icon: dot icon: dot
topics:
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "String", slug: "string" }
video: "_d0T_2Lk2qA"
sidebar: sidebar:
label: 'Reverse String' label: 'Reverse String'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Two Pointers</Badge>
:::warning :::warning
You must do this by modifying the input array in-place with O(1) extra memory. You must do this by modifying the input array in-place with O(1) extra memory.
::: :::
@@ -56,7 +58,3 @@ var reverseString = function(s) {
} }
}; };
``` ```
## Explanation
<YouTube id="_d0T_2Lk2qA" title="Reverse String - 3 Ways - Leetcode 344 - Python" />
@@ -2,13 +2,16 @@
title: '392. Is Subsequence' title: '392. Is Subsequence'
description: Given two strings s and t, return true if s is a subsequence of t, or false otherwise description: Given two strings s and t, return true if s is a subsequence of t, or false otherwise
icon: dot icon: dot
topics:
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "String", slug: "string" }
- { name: "Dynamic Programming", slug: "dynamic-programming" }
video: "99RVfqklbCE"
sidebar: sidebar:
label: 'Is Subsequence' label: 'Is Subsequence'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Two Pointers</Badge>
::::warning ::::warning
Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 10^9, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code? Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 10^9, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
:::: ::::
@@ -59,7 +62,3 @@ class Solution:
return i == len(s) return i == len(s)
``` ```
## Explanation
<YouTube id="99RVfqklbCE" title="Is Subsequence - Leetcode 392" />
@@ -2,13 +2,16 @@
title: '977. Squares of a Sorted Array' title: '977. Squares of a Sorted Array'
description: Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order description: Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "Sorting", slug: "sorting" }
video: "FPCZsG_AkUg"
sidebar: sidebar:
label: 'Squares of a Sorted Array' label: 'Squares of a Sorted Array'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach? Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
:::: ::::
@@ -69,7 +72,3 @@ var sortedSquares = function(nums) {
return ans; return ans;
}; };
``` ```
## Explanation
<YouTube id="FPCZsG_AkUg" title="Squares of a Sorted Array - Leetcode 977 - Python" />
@@ -2,13 +2,17 @@
title: '146. LRU Cache' title: '146. LRU Cache'
description: Design a data structure that follows the constraints of a Least Recently Used (LRU) cache description: Design a data structure that follows the constraints of a Least Recently Used (LRU) cache
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "Linked List", slug: "linked-list" }
- { name: "Design", slug: "design" }
- { name: "Doubly-Linked List", slug: "doubly-linked-list" }
video: "7ABFKPK2hD4"
sidebar: sidebar:
label: 'LRU Cache' label: 'LRU Cache'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `` - Input: ``
- Output: `` - Output: ``
@@ -110,7 +114,3 @@ class LRUCache:
# param_1 = obj.get(key) # param_1 = obj.get(key)
# obj.put(key,value) # obj.put(key,value)
``` ```
## Explanation
<YouTube id="7ABFKPK2hD4" title="LRU Cache - Twitch Interview Question - Leetcode 146" />
@@ -2,13 +2,16 @@
title: '2. Add Two Numbers' title: '2. Add Two Numbers'
description: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list description: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list
icon: dot icon: dot
topics:
- { name: "Linked List", slug: "linked-list" }
- { name: "Math", slug: "math" }
- { name: "Recursion", slug: "recursion" }
video: "wgFPrzTjm7s"
sidebar: sidebar:
label: 'Add Two Numbers' label: 'Add Two Numbers'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Linked List</Badge>
### Example 1: ### Example 1:
- Input: `l1 = [2,4,3], l2 = [5,6,4]` - Input: `l1 = [2,4,3], l2 = [5,6,4]`
- Output: `[7,0,8]` - Output: `[7,0,8]`
@@ -70,7 +73,3 @@ class Solution:
return dummy.next return dummy.next
``` ```
## Explanation
<YouTube id="wgFPrzTjm7s" title="Add Two Numbers - Leetcode 2 - Python" />
@@ -2,13 +2,17 @@
title: '141. Linked List Cycle' title: '141. Linked List Cycle'
description: Given head, the head of a linked list, determine if the linked list has a cycle in it description: Given head, the head of a linked list, determine if the linked list has a cycle in it
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "Linked List", slug: "linked-list" }
- { name: "Two Pointers", slug: "two-pointers" }
- { name: "Floyd's Cycle Finding Algorithm", slug: "floyds-cycle-finding-algorithm" }
video: "gBTe7lFR3vc"
sidebar: sidebar:
label: 'Linked List Cycle' label: 'Linked List Cycle'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Hash Table</Badge>
::::warning ::::warning
Can you solve it using O(1) (i.e. constant) memory? Can you solve it using O(1) (i.e. constant) memory?
:::: ::::
@@ -69,7 +73,3 @@ class Solution:
return True return True
return False return False
``` ```
## Explanation
<YouTube id="gBTe7lFR3vc" title="Linked List Cycle - Floyd's Tortoise and Hare - Leetcode 141 - Python" />
@@ -2,13 +2,15 @@
title: '206. Reverse Linked List' title: '206. Reverse Linked List'
description: Given the head of a singly linked list, reverse the list, and return the reversed list description: Given the head of a singly linked list, reverse the list, and return the reversed list
icon: dot icon: dot
topics:
- { name: "Linked List", slug: "linked-list" }
- { name: "Recursion", slug: "recursion" }
video: "G0_I-ZF0S38"
sidebar: sidebar:
label: 'Reverse Linked List' label: 'Reverse Linked List'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Linked List</Badge>
::::warning ::::warning
A linked list can be reversed either iteratively or recursively. Could you implement both? A linked list can be reversed either iteratively or recursively. Could you implement both?
:::: ::::
@@ -62,7 +64,3 @@ class Solution:
curr = next_ curr = next_
return prev return prev
``` ```
## Explanation
<YouTube id="G0_I-ZF0S38" title="Reverse Linked List - Iterative AND Recursive - Leetcode 206 - Python" />
@@ -2,13 +2,15 @@
title: '21. Merge Two Sorted Lists' title: '21. Merge Two Sorted Lists'
description: You are given the heads of two sorted linked lists list1 and list2 description: You are given the heads of two sorted linked lists list1 and list2
icon: dot icon: dot
topics:
- { name: "Linked List", slug: "linked-list" }
- { name: "Recursion", slug: "recursion" }
video: "XIdigk956u0"
sidebar: sidebar:
label: 'Merge Two Sorted Lists' label: 'Merge Two Sorted Lists'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Linked List</Badge>
### Example 1: ### Example 1:
- Input: `list1 = [1,2,4], list2 = [1,3,4]` - Input: `list1 = [1,2,4], list2 = [1,3,4]`
- Output: `[1,1,2,3,4,4]` - Output: `[1,1,2,3,4,4]`
@@ -82,7 +84,3 @@ class Solution:
current.next = list1 or list2 current.next = list1 or list2
return head return head
``` ```
## Explanation
<YouTube id="XIdigk956u0" title="Merge Two Sorted Lists - Leetcode 21 - Python" />
@@ -2,13 +2,16 @@
title: '48. Rotate Image' title: '48. Rotate Image'
description: You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise) description: You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise)
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Math", slug: "math" }
- { name: "Matrix", slug: "matrix" }
video: "fMSJSS7eO1w"
sidebar: sidebar:
label: 'Rotate Image' label: 'Rotate Image'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `matrix = [[1,2,3],[4,5,6],[7,8,9]]` - Input: `matrix = [[1,2,3],[4,5,6],[7,8,9]]`
- Output: `[[7,4,1],[8,5,2],[9,6,3]]` - Output: `[[7,4,1],[8,5,2],[9,6,3]]`
@@ -52,7 +55,3 @@ class Solution:
for r in range(n): for r in range(n):
matrix[r].reverse() matrix[r].reverse()
``` ```
## Explanation
<YouTube id="fMSJSS7eO1w" title="Rotate Image - Matrix - Leetcode 48" />
@@ -2,13 +2,16 @@
title: '54. Spiral Matrix' title: '54. Spiral Matrix'
description: Given an m x n matrix, return all elements of the matrix in spiral order description: Given an m x n matrix, return all elements of the matrix in spiral order
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Matrix", slug: "matrix" }
- { name: "Simulation", slug: "simulation" }
video: "BJnMZNwUk1M"
sidebar: sidebar:
label: 'Spiral Matrix' label: 'Spiral Matrix'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `matrix = [[1,2,3],[4,5,6],[7,8,9]]` - Input: `matrix = [[1,2,3],[4,5,6],[7,8,9]]`
- Output: `[1,2,3,6,9,8,7,4,5]` - Output: `[1,2,3,6,9,8,7,4,5]`
@@ -76,7 +79,3 @@ class Solution:
return res return res
``` ```
## Explanation
<YouTube id="BJnMZNwUk1M" title="Spiral Matrix - Microsoft Interview Question - Leetcode 54" />
@@ -2,13 +2,16 @@
title: '73. Set Matrix Zeroes' title: '73. Set Matrix Zeroes'
description: Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's description: Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Hash Table", slug: "hash-table" }
- { name: "Matrix", slug: "matrix" }
video: "T41rL0L3Pnw"
sidebar: sidebar:
label: 'Set Matrix Zeroes' label: 'Set Matrix Zeroes'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
::::warning ::::warning
You must do it in place. You must do it in place.
:::: ::::
@@ -95,7 +98,3 @@ class Solution:
for r in range(m): for r in range(m):
matrix[r][0] = 0 matrix[r][0] = 0
``` ```
## Explanation
<YouTube id="T41rL0L3Pnw" title="Set Matrix Zeroes - In-place - Leetcode 73" />
@@ -2,13 +2,17 @@
title: '230. Kth Smallest Element in a BST' title: '230. Kth Smallest Element in a BST'
description: Given the root of a binary search tree, and an integer k, return the k^th smallest value (1-indexed) of all the values of the nodes in the tree description: Given the root of a binary search tree, and an integer k, return the k^th smallest value (1-indexed) of all the values of the nodes in the tree
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Binary Search Tree", slug: "binary-search-tree" }
- { name: "Binary Tree", slug: "binary-tree" }
video: "5LUXSvjmGCw"
sidebar: sidebar:
label: 'Kth Smallest Element in a BST' label: 'Kth Smallest Element in a BST'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Tree</Badge>
::::warning ::::warning
If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize? If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
:::: ::::
@@ -70,7 +74,3 @@ class Solution:
return cur.val return cur.val
cur = cur.right cur = cur.right
``` ```
## Explanation
<YouTube id="5LUXSvjmGCw" title="Kth Smallest Element in a BST - Leetcode 230 - Python" />
@@ -2,13 +2,19 @@
title: '235. Lowest Common Ancestor of a Binary Search Tree' title: '235. Lowest Common Ancestor of a Binary Search Tree'
description: Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST description: Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Binary Search Tree", slug: "binary-search-tree" }
- { name: "Binary Tree", slug: "binary-tree" }
- { name: "Binary Lifting", slug: "binary-lifting" }
- { name: "Lowest Common Ancestor", slug: "lowest-common-ancestor" }
video: "gs2LMfuOR9k"
sidebar: sidebar:
label: 'Lowest Common Ancestor of a Binary Search Tree' label: 'Lowest Common Ancestor of a Binary Search Tree'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Tree</Badge>
### Example 1: ### Example 1:
- Input: `root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8` - Input: `root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8`
- Output: `6` - Output: `6`
@@ -71,7 +77,3 @@ class Solution:
else: else:
return cur return cur
``` ```
## Explanation
<YouTube id="gs2LMfuOR9k" title="Lowest Common Ancestor of a Binary Search Tree - Leetcode 235 - Python" />
@@ -2,13 +2,17 @@
title: '98. Validate Binary Search Tree' title: '98. Validate Binary Search Tree'
description: Given the root of a binary tree, determine if it is a valid binary search tree (BST) description: Given the root of a binary tree, determine if it is a valid binary search tree (BST)
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Binary Search Tree", slug: "binary-search-tree" }
- { name: "Binary Tree", slug: "binary-tree" }
video: "s6ATEkipzow"
sidebar: sidebar:
label: 'Validate Binary Search Tree' label: 'Validate Binary Search Tree'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Tree</Badge>
### Example 1: ### Example 1:
- Input: `root = [2,1,3]` - Input: `root = [2,1,3]`
- Output: `true` - Output: `true`
@@ -62,7 +66,3 @@ class Solution:
return valid(root, float("-inf"), float("inf")) return valid(root, float("-inf"), float("inf"))
``` ```
## Explanation
<YouTube id="s6ATEkipzow" title="Validate Binary Search Tree - Depth First Search - Leetcode 98" />
@@ -2,13 +2,18 @@
title: '215. Kth Largest Element in an Array' title: '215. Kth Largest Element in an Array'
description: Given an integer array nums and an integer k, return the k^th largest element in the array description: Given an integer array nums and an integer k, return the k^th largest element in the array
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
- { name: "Sorting", slug: "sorting" }
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
- { name: "Quickselect", slug: "quickselect" }
video: "XEmy13g1Qxc"
sidebar: sidebar:
label: 'Kth Largest Element in an Array' label: 'Kth Largest Element in an Array'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `nums = [3,2,1,5,6,4], k = 2` - Input: `nums = [3,2,1,5,6,4], k = 2`
- Output: `5` - Output: `5`
@@ -54,7 +59,3 @@ class Solution:
return -heapq.heappop(nums) return -heapq.heappop(nums)
``` ```
## Explanation
<YouTube id="XEmy13g1Qxc" title="Kth Largest Element in an Array - Quick Select - Leetcode 215 - Python" />
@@ -2,13 +2,18 @@
title: '23. Merge k Sorted Lists' title: '23. Merge k Sorted Lists'
description: You are given an array of k linked-lists lists, each linked-list is sorted in ascending order description: You are given an array of k linked-lists lists, each linked-list is sorted in ascending order
icon: dot icon: dot
topics:
- { name: "Linked List", slug: "linked-list" }
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
- { name: "Merge Sort", slug: "merge-sort" }
- { name: "Tournament Sort", slug: "tournament-sort" }
video: "q5a5OiGbT6Q"
sidebar: sidebar:
label: 'Merge k Sorted Lists' label: 'Merge k Sorted Lists'
badge: 'Hard' badge: 'Hard'
--- ---
<Badge variant="accent">Linked List</Badge>
### Example 1: ### Example 1:
- Input: `lists = [[1,4,5],[1,3,4],[2,6]]` - Input: `lists = [[1,4,5],[1,3,4],[2,6]]`
- Output: `[1,1,2,3,4,4,5,6]` - Output: `[1,1,2,3,4,4,5,6]`
@@ -89,7 +94,3 @@ class Solution:
# Space: O(n) # Space: O(n)
return D.next return D.next
``` ```
## Explanation
<YouTube id="q5a5OiGbT6Q" title="Merge K Sorted Lists - Leetcode 23 - Python" />
@@ -2,13 +2,21 @@
title: '973. K Closest Points to Origin' title: '973. K Closest Points to Origin'
description: Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0) description: Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0)
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Math", slug: "math" }
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
- { name: "Geometry", slug: "geometry" }
- { name: "Sorting", slug: "sorting" }
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
- { name: "Quickselect", slug: "quickselect" }
- { name: "K-D Tree", slug: "k-d-tree" }
video: "rI2EBUEMfTk"
sidebar: sidebar:
label: 'K Closest Points to Origin' label: 'K Closest Points to Origin'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `points = [[1,3],[-2,2]], k = 1` - Input: `points = [[1,3],[-2,2]], k = 1`
- Output: `[[-2,2]]` - Output: `[[-2,2]]`
@@ -64,7 +72,3 @@ class Solution:
return res return res
``` ```
## Explanation
<YouTube id="rI2EBUEMfTk" title="K Closest Points to Origin - Heap / Priority Queue - Leetcode 973 - Python" />
@@ -2,13 +2,16 @@
title: '102. Binary Tree Level Order Traversal' title: '102. Binary Tree Level Order Traversal'
description: Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level) description: Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level)
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Binary Tree", slug: "binary-tree" }
video: "6ZnyEApgFYg"
sidebar: sidebar:
label: 'Binary Tree Level Order Traversal' label: 'Binary Tree Level Order Traversal'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Tree</Badge>
### Example 1: ### Example 1:
- Input: `root = [3,9,20,null,null,15,7]` - Input: `root = [3,9,20,null,null,15,7]`
- Output: `[[3],[9,20],[15,7]]` - Output: `[[3],[9,20],[15,7]]`
@@ -80,7 +83,3 @@ class Solution:
return res return res
``` ```
## Explanation
<YouTube id="6ZnyEApgFYg" title="Binary Tree Level Order Traversal - BFS - Leetcode 102" />
@@ -2,13 +2,17 @@
title: '1448. Count Good Nodes in Binary Tree' title: '1448. Count Good Nodes in Binary Tree'
description: Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X description: Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Binary Tree", slug: "binary-tree" }
video: "7cp5imvDzl4"
sidebar: sidebar:
label: 'Count Good Nodes in Binary Tree' label: 'Count Good Nodes in Binary Tree'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Tree</Badge>
### Example 1: ### Example 1:
- Input: `root = [3,1,4,3,null,1,5]` - Input: `root = [3,1,4,3,null,1,5]`
- Output: `4` - Output: `4`
@@ -67,7 +71,3 @@ class Solution:
return dfs(root, root.val) return dfs(root, root.val)
``` ```
## Explanation
<YouTube id="7cp5imvDzl4" title="Microsoft's Most Asked Question 2021 - Count Good Nodes in a Binary Tree - Leetcode 1448 - Python" />
@@ -2,13 +2,17 @@
title: '199. Binary Tree Right Side View' title: '199. Binary Tree Right Side View'
description: Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom description: Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Binary Tree", slug: "binary-tree" }
video: "d4zLyf32e3I"
sidebar: sidebar:
label: 'Binary Tree Right Side View' label: 'Binary Tree Right Side View'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Tree</Badge>
### Example 1: ### Example 1:
- Input: `root = [1,2,3,null,5,null,4]` - Input: `root = [1,2,3,null,5,null,4]`
- Output: `[1,3,4]` - Output: `[1,3,4]`
@@ -83,7 +87,3 @@ class Solution:
return res return res
``` ```
## Explanation
<YouTube id="d4zLyf32e3I" title="Binary Tree Right Side View - Breadth First Search - Leetcode 199" />
@@ -2,13 +2,17 @@
title: '104. Maximum Depth of Binary Tree' title: '104. Maximum Depth of Binary Tree'
description: Given the root of a binary tree, return its maximum depth description: Given the root of a binary tree, return its maximum depth
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Binary Tree", slug: "binary-tree" }
video: "hTM3phVI6YQ"
sidebar: sidebar:
label: 'Maximum Depth of Binary Tree' label: 'Maximum Depth of Binary Tree'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Tree</Badge>
### Example 1: ### Example 1:
- Input: `root = [3,9,20,null,null,15,7]` - Input: `root = [3,9,20,null,null,15,7]`
- Output: `3` - Output: `3`
@@ -48,7 +52,3 @@ class Solution:
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
``` ```
## Explanation
<YouTube id="hTM3phVI6YQ" title="Maximum Depth of Binary Tree - 3 Solutions - Leetcode 104 - Python" />
@@ -2,13 +2,17 @@
title: '226. Invert Binary Tree' title: '226. Invert Binary Tree'
description: Given the root of a binary tree, invert the tree, and return its root description: Given the root of a binary tree, invert the tree, and return its root
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Binary Tree", slug: "binary-tree" }
video: "OnSn2XEQ4MY"
sidebar: sidebar:
label: 'Invert Binary Tree' label: 'Invert Binary Tree'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Tree</Badge>
### Example 1: ### Example 1:
- Input: `root = [4,2,7,1,3,6,9]` - Input: `root = [4,2,7,1,3,6,9]`
- Output: `[4,7,2,9,6,3,1]` - Output: `[4,7,2,9,6,3,1]`
@@ -59,7 +63,3 @@ class Solution:
return root return root
``` ```
## Explanation
<YouTube id="OnSn2XEQ4MY" title="Invert Binary Tree - Depth First Search - Leetcode 226" />
@@ -2,13 +2,17 @@
title: '236. Lowest Common Ancestor of a Binary Tree' title: '236. Lowest Common Ancestor of a Binary Tree'
description: Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree description: Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree
icon: dot icon: dot
topics:
- { name: "Tree", slug: "tree" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Binary Tree", slug: "binary-tree" }
- { name: "Binary Lifting", slug: "binary-lifting" }
- { name: "Lowest Common Ancestor", slug: "lowest-common-ancestor" }
sidebar: sidebar:
label: 'Lowest Common Ancestor of a Binary Tree' label: 'Lowest Common Ancestor of a Binary Tree'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Tree</Badge>
### Example 1: ### Example 1:
- Input: `root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1` - Input: `root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1`
- Output: `3` - Output: `3`
@@ -2,13 +2,17 @@
title: '208. Implement Trie (Prefix Tree)' title: '208. Implement Trie (Prefix Tree)'
description: A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker description: A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
- { name: "Design", slug: "design" }
- { name: "Trie", slug: "trie" }
video: "oobqoCJlHA0"
sidebar: sidebar:
label: 'Implement Trie (Prefix Tree)' label: 'Implement Trie (Prefix Tree)'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `` - Input: ``
- Output: `` - Output: ``
@@ -107,7 +111,3 @@ class Trie:
# param_2 = obj.search(word) # param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix) # param_3 = obj.startsWith(prefix)
``` ```
## Explanation
<YouTube id="oobqoCJlHA0" title="Implement Trie (Prefix Tree) - Leetcode 208" />
@@ -2,13 +2,17 @@
title: '211. Design Add and Search Words Data Structure' title: '211. Design Add and Search Words Data Structure'
description: Design a data structure that supports adding new words and finding if a string matches any previously added string description: Design a data structure that supports adding new words and finding if a string matches any previously added string
icon: dot icon: dot
topics:
- { name: "String", slug: "string" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Design", slug: "design" }
- { name: "Trie", slug: "trie" }
video: "BTf05gs_8iU"
sidebar: sidebar:
label: 'Design Add and Search Words Data Structure' label: 'Design Add and Search Words Data Structure'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">String</Badge>
### Constraints: ### Constraints:
- `1 <= word.length <= 25` - `1 <= word.length <= 25`
@@ -101,7 +105,3 @@ class WordDictionary:
# obj.addWord(word) # obj.addWord(word)
# param_3 = obj.search(word) # param_3 = obj.search(word)
``` ```
## Explanation
<YouTube id="BTf05gs_8iU" title="Design Add and Search Words Data Structure - Leetcode 211 - Python" />
@@ -2,13 +2,16 @@
title: '127. Word Ladder' title: '127. Word Ladder'
description: 'A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:' description: 'A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:'
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "String", slug: "string" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Bidirectional Search", slug: "bidirectional-search" }
sidebar: sidebar:
label: 'Word Ladder' label: 'Word Ladder'
badge: 'Hard' badge: 'Hard'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]` - Input: `beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]`
- Output: `5` - Output: `5`
@@ -2,13 +2,15 @@
title: '994. Rotting Oranges' title: '994. Rotting Oranges'
description: 'You are given an m x n grid where each cell can have one of three values:' description: 'You are given an m x n grid where each cell can have one of three values:'
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Matrix", slug: "matrix" }
sidebar: sidebar:
label: 'Rotting Oranges' label: 'Rotting Oranges'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `grid = [[2,1,1],[1,1,0],[0,1,1]]` - Input: `grid = [[2,1,1],[1,1,0],[0,1,1]]`
- Output: `4` - Output: `4`
@@ -2,13 +2,16 @@
title: '133. Clone Graph' title: '133. Clone Graph'
description: Given a reference of a node in a connected undirected graph description: Given a reference of a node in a connected undirected graph
icon: dot icon: dot
topics:
- { name: "Hash Table", slug: "hash-table" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Graph Theory", slug: "graph" }
sidebar: sidebar:
label: 'Clone Graph' label: 'Clone Graph'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Hash Table</Badge>
### Example 1: ### Example 1:
- Input: `adjList = [[2,4],[1,3],[2,4],[1,3]]` - Input: `adjList = [[2,4],[1,3],[2,4],[1,3]]`
- Output: `[[2,4],[1,3],[2,4],[1,3]]` - Output: `[[2,4],[1,3],[2,4],[1,3]]`
@@ -2,13 +2,17 @@
title: '200. Number of Islands' title: '200. Number of Islands'
description: Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands description: Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Union-Find", slug: "union-find" }
- { name: "Matrix", slug: "matrix" }
sidebar: sidebar:
label: 'Number of Islands' label: 'Number of Islands'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ]` - Input: `grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ]`
- Output: `1` - Output: `1`
@@ -2,13 +2,16 @@
title: '417. Pacific Atlantic Water Flow' title: '417. Pacific Atlantic Water Flow'
description: There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges description: There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Matrix", slug: "matrix" }
sidebar: sidebar:
label: 'Pacific Atlantic Water Flow' label: 'Pacific Atlantic Water Flow'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]` - Input: `heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]`
- Output: `[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]` - Output: `[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]`
@@ -2,13 +2,17 @@
title: '207. Course Schedule' title: '207. Course Schedule'
description: There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai description: There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai
icon: dot icon: dot
topics:
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Graph Theory", slug: "graph" }
- { name: "Topological Sort", slug: "topological-sort" }
- { name: "Directed Acyclic Graph", slug: "directed-acyclic-graph" }
sidebar: sidebar:
label: 'Course Schedule' label: 'Course Schedule'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Depth-First Search</Badge>
### Example 1: ### Example 1:
- Input: `numCourses = 2, prerequisites = [[1,0]]` - Input: `numCourses = 2, prerequisites = [[1,0]]`
- Output: `true` - Output: `true`
@@ -2,13 +2,16 @@
title: '210. Course Schedule II' title: '210. Course Schedule II'
description: There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai description: There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai
icon: dot icon: dot
topics:
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Graph Theory", slug: "graph" }
- { name: "Topological Sort", slug: "topological-sort" }
sidebar: sidebar:
label: 'Course Schedule II' label: 'Course Schedule II'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Depth-First Search</Badge>
### Example 1: ### Example 1:
- Input: `numCourses = 2, prerequisites = [[1,0]]` - Input: `numCourses = 2, prerequisites = [[1,0]]`
- Output: `[0,1]` - Output: `[0,1]`
@@ -2,13 +2,16 @@
title: '323. Number of Connected Components in an Undirected Graph' title: '323. Number of Connected Components in an Undirected Graph'
description: You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph description: You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph
icon: dot icon: dot
topics:
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Union-Find", slug: "union-find" }
- { name: "Graph Theory", slug: "graph" }
sidebar: sidebar:
label: 'Number of Connected Components in an Undirected Graph' label: 'Number of Connected Components in an Undirected Graph'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Depth-First Search</Badge>
### Example 1: ### Example 1:
- Input: `n = 5, edges = [[0,1],[1,2],[3,4]]` - Input: `n = 5, edges = [[0,1],[1,2],[3,4]]`
- Output: `2` - Output: `2`
@@ -2,13 +2,16 @@
title: '684. Redundant Connection' title: '684. Redundant Connection'
description: In this problem, a tree is an undirected graph that is connected and has no cycles description: In this problem, a tree is an undirected graph that is connected and has no cycles
icon: dot icon: dot
topics:
- { name: "Depth-First Search", slug: "depth-first-search" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Union-Find", slug: "union-find" }
- { name: "Graph Theory", slug: "graph" }
sidebar: sidebar:
label: 'Redundant Connection' label: 'Redundant Connection'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Depth-First Search</Badge>
### Example 1: ### Example 1:
- Input: `edges = [[1,2],[1,3],[2,3]]` - Input: `edges = [[1,2],[1,3],[2,3]]`
- Output: `[2,3]` - Output: `[2,3]`
@@ -2,13 +2,14 @@
title: '198. House Robber' title: '198. House Robber'
description: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night description: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Dynamic Programming", slug: "dynamic-programming" }
sidebar: sidebar:
label: 'House Robber' label: 'House Robber'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `nums = [1,2,3,1]` - Input: `nums = [1,2,3,1]`
- Output: `4` - Output: `4`
@@ -2,13 +2,17 @@
title: '322. Coin Change' title: '322. Coin Change'
description: You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money description: You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Dynamic Programming", slug: "dynamic-programming" }
- { name: "Breadth-First Search", slug: "breadth-first-search" }
- { name: "Knapsack Problem", slug: "knapsack-problem" }
- { name: "Complete Knapsack", slug: "complete-knapsack" }
sidebar: sidebar:
label: 'Coin Change' label: 'Coin Change'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `coins = [1,2,5], amount = 11` - Input: `coins = [1,2,5], amount = 11`
- Output: `3` - Output: `3`
@@ -2,13 +2,15 @@
title: '70. Climbing Stairs' title: '70. Climbing Stairs'
description: You are climbing a staircase. It takes n steps to reach the top description: You are climbing a staircase. It takes n steps to reach the top
icon: dot icon: dot
topics:
- { name: "Math", slug: "math" }
- { name: "Dynamic Programming", slug: "dynamic-programming" }
- { name: "Memoization", slug: "memoization" }
sidebar: sidebar:
label: 'Climbing Stairs' label: 'Climbing Stairs'
badge: 'Easy' badge: 'Easy'
--- ---
<Badge variant="accent">Math</Badge>
### Example 1: ### Example 1:
- Input: `n = 2` - Input: `n = 2`
- Output: `2` - Output: `2`
@@ -2,13 +2,14 @@
title: '39. Combination Sum' title: '39. Combination Sum'
description: Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order description: Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Backtracking", slug: "backtracking" }
sidebar: sidebar:
label: 'Combination Sum' label: 'Combination Sum'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `candidates = [2,3,6,7], target = 7` - Input: `candidates = [2,3,6,7], target = 7`
- Output: `[[2,2,3],[7]]` - Output: `[[2,2,3],[7]]`
@@ -2,13 +2,14 @@
title: '46. Permutations' title: '46. Permutations'
description: Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order description: Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Backtracking", slug: "backtracking" }
sidebar: sidebar:
label: 'Permutations' label: 'Permutations'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `nums = [1,2,3]` - Input: `nums = [1,2,3]`
- Output: `[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]` - Output: `[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]`
@@ -2,13 +2,15 @@
title: '78. Subsets' title: '78. Subsets'
description: Given an integer array nums of unique elements, return all possible subsets (the power set) description: Given an integer array nums of unique elements, return all possible subsets (the power set)
icon: dot icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Backtracking", slug: "backtracking" }
- { name: "Bit Manipulation", slug: "bit-manipulation" }
sidebar: sidebar:
label: 'Subsets' label: 'Subsets'
badge: 'Medium' badge: 'Medium'
--- ---
<Badge variant="accent">Array</Badge>
### Example 1: ### Example 1:
- Input: `nums = [1,2,3]` - Input: `nums = [1,2,3]`
- Output: `[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]` - Output: `[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]`
@@ -0,0 +1,49 @@
---
title: '1143. Longest Common Subsequence'
description: Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0
icon: dot
topics:
- { name: "String", slug: "string" }
- { name: "Dynamic Programming", slug: "dynamic-programming" }
- { name: "Longest Common Subsequence", slug: "longest-common-subsequence" }
sidebar:
label: 'Longest Common Subsequence'
badge: 'Medium'
---
### Example 1:
- Input: `text1 = "abcde", text2 = "ace"`
- Output: `3`
- Explanation: The longest common subsequence is "ace" and its length is `3`.
### Example 2:
- Input: `text1 = "abc", text2 = "abc"`
- Output: `3`
- Explanation: The longest common subsequence is "abc" and its length is `3`.
### Example 3:
- Input: `text1 = "abc", text2 = "def"`
- Output: `0`
- Explanation: There is no such common subsequence, so the result is `0`.
### Constraints:
- `1 <= text1.length, text2.length <= 1000`
- `text1` and `text2` consist of only lowercase English characters.
## Solution
```py
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)]
for i in range(len(text1) - 1, -1, -1):
for j in range(len(text2) - 1, -1, -1):
if text1[i] == text2[j]:
dp[i][j] = 1 + dp[i + 1][j + 1]
else:
dp[i][j] = max(dp[i][j + 1], dp[i + 1][j])
return dp[0][0]
```
@@ -0,0 +1,45 @@
---
title: '62. Unique Paths'
description: There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time
icon: dot
topics:
- { name: "Math", slug: "math" }
- { name: "Dynamic Programming", slug: "dynamic-programming" }
- { name: "Combinatorics", slug: "combinatorics" }
sidebar:
label: 'Unique Paths'
badge: 'Medium'
---
### Example 1:
- Input: `m = 3, n = 7`
- Output: `28`
### Example 2:
- Input: `m = 3, n = 2`
- Output: `3`
- Explanation: From the top-left corner, there are a total of `3` ways to reach the bottom-right corner: `1`. Right -> Down -> Down `2`. Down -> Down -> Right `3`. Down -> Right -> Down
### Constraints:
- `1 <= m, n <= 100`
## Solution
```py
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0 for _ in range(n)] for _ in range(m)]
for c in range(n):
dp[0][c] = 1
for r in range(m):
dp[r][0] = 1
for r in range(1, m):
for c in range(1, n):
dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
return dp[-1][-1]
```
@@ -0,0 +1,53 @@
---
title: '64. Minimum Path Sum'
description: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path
icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Dynamic Programming", slug: "dynamic-programming" }
- { name: "Matrix", slug: "matrix" }
sidebar:
label: 'Minimum Path Sum'
badge: 'Medium'
---
### Example 1:
- Input: `grid = [[1,3,1],[1,5,1],[4,2,1]]`
- Output: `7`
- Explanation: Because the path `1` &rarr; `3` &rarr; `1` &rarr; `1` &rarr; `1` minimizes the sum.
### Example 2:
- Input: `grid = [[1,2,3],[4,5,6]]`
- Output: `12`
### Constraints:
- `m == grid.length`
- `n == grid[i].length`
- `1 <= m, n <= 200`
- `0 <= grid[i][j] <= 200`
## Solution
```py
class Solution:
def minPathSum(self, grid: list[list[int]]) -> int:
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
dp = [[0 for _ in range(n)] for _ in range(m)]
for c in range(n):
dp[0][c] = dp[0][c - 1] + grid[0][c] if c else grid[0][c]
for r in range(m):
dp[r][0] = dp[r - 1][0] + grid[r][0] if r else grid[r][0]
for r in range(1, m):
for c in range(1, n):
dp[r][c] = min(dp[r - 1][c], dp[r][c - 1]) + grid[r][c]
return dp[-1][-1]
```
@@ -0,0 +1,3 @@
import { defineMeta } from "blume";
export default defineMeta({ title: "Multi-D / Grid DP", order: 22, icon: "table", display: "group" });
+8
View File
@@ -0,0 +1,8 @@
---
title: "Array"
list: "https://leetcode.com/problem-list/array/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Array.
:::
@@ -0,0 +1,8 @@
---
title: "Bidirectional Search"
list: "https://leetcode.com/problem-list/bidirectional-search/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Bidirectional Search.
:::
@@ -0,0 +1,8 @@
---
title: "Binary Lifting"
list: "https://leetcode.com/problem-list/binary-lifting/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Binary Lifting.
:::
+8
View File
@@ -0,0 +1,8 @@
---
title: "Binary Tree"
list: "https://leetcode.com/problem-list/binary-tree/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Binary Tree.
:::
@@ -0,0 +1,8 @@
---
title: "Bit Manipulation"
list: "https://leetcode.com/problem-list/bit-manipulation/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Bit Manipulation.
:::
@@ -0,0 +1,8 @@
---
title: "Bracket Sequences"
list: "https://leetcode.com/problem-list/bracket-sequences/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Bracket Sequences.
:::
+8
View File
@@ -0,0 +1,8 @@
---
title: "Bucket Sort"
list: "https://leetcode.com/problem-list/bucket-sort/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Bucket Sort.
:::
@@ -0,0 +1,8 @@
---
title: "Combinatorics"
list: "https://leetcode.com/problem-list/combinatorics/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Combinatorics.
:::
@@ -0,0 +1,8 @@
---
title: "Complete Knapsack"
list: "https://leetcode.com/problem-list/complete-knapsack/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Complete Knapsack.
:::
+8
View File
@@ -0,0 +1,8 @@
---
title: "Counting"
list: "https://leetcode.com/problem-list/counting/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Counting.
:::
+8
View File
@@ -0,0 +1,8 @@
---
title: "Design"
list: "https://leetcode.com/problem-list/design/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Design.
:::
@@ -0,0 +1,8 @@
---
title: "Directed Acyclic Graph"
list: "https://leetcode.com/problem-list/directed-acyclic-graph/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Directed Acyclic Graph.
:::
@@ -0,0 +1,8 @@
---
title: "Divide and Conquer"
list: "https://leetcode.com/problem-list/divide-and-conquer/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Divide and Conquer.
:::
@@ -0,0 +1,8 @@
---
title: "Doubly-Linked List"
list: "https://leetcode.com/problem-list/doubly-linked-list/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Doubly-Linked List.
:::
@@ -0,0 +1,8 @@
---
title: "Floyd's Cycle Finding Algorithm"
list: "https://leetcode.com/problem-list/floyds-cycle-finding-algorithm/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Floyd's Cycle Finding Algorithm.
:::
+8
View File
@@ -0,0 +1,8 @@
---
title: "Geometry"
list: "https://leetcode.com/problem-list/geometry/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Geometry.
:::
+8
View File
@@ -0,0 +1,8 @@
---
title: "Graph Theory"
list: "https://leetcode.com/problem-list/graph/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged Graph Theory.
:::
+8
View File
@@ -0,0 +1,8 @@
---
title: "K-D Tree"
list: "https://leetcode.com/problem-list/k-d-tree/"
---
:::note
This guide has not been written yet. The LeetCode list above has every problem tagged K-D Tree.
:::
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more