diff --git a/app/components/navbar.jsx b/app/components/navbar.jsx index 047bb94..a2928ae 100755 --- a/app/components/navbar.jsx +++ b/app/components/navbar.jsx @@ -21,6 +21,18 @@ const SERVICES = [ iconBg: "bg-purple-100 text-purple-600", href: "/visualizer" }, + { + title: "Design & Analysis of Algorithms", + description: "Complexity analysis and algorithm design techniques", + icon: ( + + + + + ), + iconBg: "bg-blue-100 text-blue-600", + href: "/design-algorithm" + }, { title: "Blogs", description: "Tutorials & guides on development", diff --git a/app/components/ui/DailyDSAEmbed.jsx b/app/components/ui/DailyDSAEmbed.jsx index c499d22..dda4cab 100755 --- a/app/components/ui/DailyDSAEmbed.jsx +++ b/app/components/ui/DailyDSAEmbed.jsx @@ -1,35 +1,48 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; + +const EMBED_ORIGIN = "https://scaleengineer.com"; +// Used until the embed reports its real height, and if the message never lands. +const FALLBACK_HEIGHT = 350; const DailyDSAEmbed = ({ mobile = false, theme = "light" }) => { - const src = `https://scaleengineer.com/embed/daily/dsa?theme=${theme}`; + const [height, setHeight] = useState(FALLBACK_HEIGHT); + const iframeRef = useRef(null); + + const src = `${EMBED_ORIGIN}/embed/daily/dsa?theme=${theme}`; const wrapperClasses = mobile ? "block md:hidden w-full" : "max-w-full hidden md:block"; - const height = mobile ? 350 : 350; + + // The embed posts its document height on load and on every resize. Growing + // the iframe to match keeps the frame from getting its own scrollbar, which + // looked broken next to the article on narrow viewports. + useEffect(() => { + const onMessage = (event) => { + if (event.origin !== EMBED_ORIGIN) return; + if (event.source !== iframeRef.current?.contentWindow) return; + if (event.data?.type !== "se-embed-resize") return; + + const reported = Number(event.data.height); + if (Number.isFinite(reported) && reported > 0) { + setHeight(Math.ceil(reported)); + } + }; + + window.addEventListener("message", onMessage); + return () => window.removeEventListener("message", onMessage); + }, []); return (
- - Daily DSA Challenge by{" "} - - Scale Engineer - - diff --git a/app/components/ui/NewsletterEmbed.jsx b/app/components/ui/NewsletterEmbed.jsx index d1a3e5d..2b4c87c 100755 --- a/app/components/ui/NewsletterEmbed.jsx +++ b/app/components/ui/NewsletterEmbed.jsx @@ -1,12 +1,18 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; + +const EMBED_ORIGIN = "https://scaleengineer.com"; +// Used until the embed reports its real height, and if the message never lands. +const FALLBACK_HEIGHT = 360; const NewsletterEmbed = ({ mobile = false, theme = "light" }) => { const [pageUrl, setPageUrl] = useState(""); // Only mount the iframe on desktop. Hiding it with CSS still downloads it on // phones, which hurts the mobile performance/SEO score. const [isDesktop, setIsDesktop] = useState(false); + const [height, setHeight] = useState(FALLBACK_HEIGHT); + const iframeRef = useRef(null); useEffect(() => { setPageUrl(encodeURIComponent(window.location.href)); @@ -20,20 +26,40 @@ const NewsletterEmbed = ({ mobile = false, theme = "light" }) => { return () => mq.removeEventListener("change", update); }, []); + // The embed posts its document height on load and on every resize. Growing + // the iframe to match keeps the frame from getting its own scrollbar, which + // looked broken next to the article on narrow viewports. + useEffect(() => { + const onMessage = (event) => { + if (event.origin !== EMBED_ORIGIN) return; + if (event.source !== iframeRef.current?.contentWindow) return; + if (event.data?.type !== "se-embed-resize") return; + + const reported = Number(event.data.height); + if (Number.isFinite(reported) && reported > 0) { + setHeight(Math.ceil(reported)); + } + }; + + window.addEventListener("message", onMessage); + return () => window.removeEventListener("message", onMessage); + }, [isDesktop]); + // The mobile variant is retired; the desktop variant is desktop-only. if (mobile || !isDesktop) return null; - const src = `https://scaleengineer.com/embed/subscribe?theme=${theme}&utm_campaign=dsa_visualizer&utm_source=${pageUrl}`; - const height = 360; + const src = `${EMBED_ORIGIN}/embed/subscribe?theme=${theme}&utm_campaign=dsa_visualizer&utm_source=${pageUrl}`; return (
diff --git a/app/design-algorithm/DesignAlgorithmClient.jsx b/app/design-algorithm/DesignAlgorithmClient.jsx new file mode 100755 index 0000000..cdbd920 --- /dev/null +++ b/app/design-algorithm/DesignAlgorithmClient.jsx @@ -0,0 +1,32 @@ +"use client"; +import { useState } from "react"; +import SearchBar from "@/app/components/ui/SearchBar"; +import SectionsDisplay from "@/app/components/SectionsDisplay"; + +const DesignAlgorithmClient = ({ initialSections }) => { + const [filteredSections, setFilteredSections] = useState(initialSections); + const [searchQuery, setSearchQuery] = useState(""); + + return ( + <> + { /* search bar display */ } +
+ +
+ + { /* section display */ } +
+ +
+ + ); +}; + +export default DesignAlgorithmClient; diff --git a/app/design-algorithm/fundamentals/amortized-analysis/code.js b/app/design-algorithm/fundamentals/amortized-analysis/code.js new file mode 100755 index 0000000..6a46fe7 --- /dev/null +++ b/app/design-algorithm/fundamentals/amortized-analysis/code.js @@ -0,0 +1,439 @@ +const codeExamples = { + javascript: `// Amortized analysis, measured rather than asserted. + +// ---- A dynamic array that reports what each append really costs ---- +class DynamicArray { + constructor() { + this.buffer = new Array(1); + this.capacity = 1; + this.size = 0; + this.totalCost = 0; + } + + append(value) { + let cost = 1; // the write itself + + if (this.size === this.capacity) { // full: grow and copy + const bigger = new Array(this.capacity * 2); + for (let i = 0; i < this.size; i++) bigger[i] = this.buffer[i]; + + cost += this.size; // Theta(n) - but only sometimes + this.buffer = bigger; + this.capacity *= 2; + } + + this.buffer[this.size++] = value; + this.totalCost += cost; + return cost; + } +} + +// Aggregate analysis says total < 3n, so the average is O(1). +function measureAppends(n) { + const arr = new DynamicArray(); + for (let i = 0; i < n; i++) arr.append(i); + + console.log(\`n=\${n}\\ttotal=\${arr.totalCost}\\tper append=\${(arr.totalCost / n).toFixed(3)}\`); +} + +// ---- Growing by a CONSTANT instead: the guarantee disappears ---- +function measureConstantGrowth(n, step = 10) { + let capacity = step, size = 0, totalCost = 0; + + for (let i = 0; i < n; i++) { + let cost = 1; + if (size === capacity) { + cost += size; // copy everything, again + capacity += step; // ... only to fill up 10 slots later + } + totalCost += cost; + size++; + } + console.log(\`n=\${n}\\ttotal=\${totalCost}\\tper append=\${(totalCost / n).toFixed(1)} <- grows with n\`); +} + +// ---- Binary counter: a single increment can flip many bits ---- +// Potential method: let Phi = number of 1 bits. An increment flipping k +// trailing 1s has actual cost k+1 and changes Phi by 1-k, so the +// amortized cost is (k+1) + (1-k) = 2. +function measureCounter(n) { + const bits = []; + let flips = 0; + + for (let k = 0; k < n; k++) { + let i = 0; + while (bits[i] === 1) { bits[i] = 0; flips++; i++; } + bits[i] = 1; flips++; + } + console.log(\`n=\${n}\\tflips=\${flips}\\tper increment=\${(flips / n).toFixed(5)}\`); +} + +console.log("Doubling array - per-append cost stays constant:"); +[1000, 10000, 100000, 1000000].forEach(measureAppends); + +console.log("\\nConstant growth - per-append cost does NOT stay constant:"); +[1000, 10000, 100000].forEach((n) => measureConstantGrowth(n)); + +console.log("\\nBinary counter - converges on 2 flips per increment:"); +[100, 10000, 1000000].forEach(measureCounter);`, + + python: `# Amortized analysis, measured rather than asserted. + + +# ---- A dynamic array that reports what each append really costs ---- +class DynamicArray: + def __init__(self): + self.buffer = [None] + self.capacity = 1 + self.size = 0 + self.total_cost = 0 + + def append(self, value): + cost = 1 # the write itself + + if self.size == self.capacity: # full: grow and copy + bigger = [None] * (self.capacity * 2) + for i in range(self.size): + bigger[i] = self.buffer[i] + + cost += self.size # Theta(n) - but only sometimes + self.buffer = bigger + self.capacity *= 2 + + self.buffer[self.size] = value + self.size += 1 + self.total_cost += cost + return cost + + +# Aggregate analysis says total < 3n, so the average is O(1). +def measure_appends(n): + arr = DynamicArray() + for i in range(n): + arr.append(i) + print(f"n={n}\\ttotal={arr.total_cost}\\tper append={arr.total_cost / n:.3f}") + + +# ---- Growing by a CONSTANT instead: the guarantee disappears ---- +def measure_constant_growth(n, step=10): + capacity, size, total_cost = step, 0, 0 + + for _ in range(n): + cost = 1 + if size == capacity: + cost += size # copy everything, again + capacity += step # only to fill up 10 slots later + total_cost += cost + size += 1 + + print(f"n={n}\\ttotal={total_cost}\\tper append={total_cost / n:.1f} <- grows with n") + + +# ---- Binary counter: a single increment can flip many bits ---- +# Potential method: let Phi = number of 1 bits. An increment flipping k +# trailing 1s has actual cost k+1 and changes Phi by 1-k, so the +# amortized cost is (k+1) + (1-k) = 2. +def measure_counter(n): + bits = [0] * 64 + flips = 0 + + for _ in range(n): + i = 0 + while bits[i] == 1: + bits[i] = 0 + flips += 1 + i += 1 + bits[i] = 1 + flips += 1 + + print(f"n={n}\\tflips={flips}\\tper increment={flips / n:.5f}") + + +print("Doubling array - per-append cost stays constant:") +for n in [1000, 10000, 100000]: + measure_appends(n) + +print("\\nConstant growth - per-append cost does NOT stay constant:") +for n in [1000, 10000, 100000]: + measure_constant_growth(n) + +print("\\nBinary counter - converges on 2 flips per increment:") +for n in [100, 10000, 1000000]: + measure_counter(n)`, + + java: `// Amortized analysis, measured rather than asserted. + +import java.util.Arrays; + +public class AmortizedDemo { + + // ---- A dynamic array that reports what each append really costs ---- + static class DynamicArray { + int[] buffer = new int[1]; + int capacity = 1; + int size = 0; + long totalCost = 0; + + int append(int value) { + int cost = 1; // the write itself + + if (size == capacity) { // full: grow and copy + int[] bigger = new int[capacity * 2]; + System.arraycopy(buffer, 0, bigger, 0, size); + + cost += size; // Theta(n) - but only sometimes + buffer = bigger; + capacity *= 2; + } + + buffer[size++] = value; + totalCost += cost; + return cost; + } + } + + // Aggregate analysis says total < 3n, so the average is O(1). + static void measureAppends(int n) { + DynamicArray arr = new DynamicArray(); + for (int i = 0; i < n; i++) arr.append(i); + + System.out.printf("n=%d\\ttotal=%d\\tper append=%.3f%n", + n, arr.totalCost, (double) arr.totalCost / n); + } + + // ---- Growing by a CONSTANT instead: the guarantee disappears ---- + static void measureConstantGrowth(int n, int step) { + long capacity = step, size = 0, totalCost = 0; + + for (int i = 0; i < n; i++) { + long cost = 1; + if (size == capacity) { + cost += size; // copy everything, again + capacity += step; // only to fill up again soon + } + totalCost += cost; + size++; + } + System.out.printf("n=%d\\ttotal=%d\\tper append=%.1f <- grows with n%n", + n, totalCost, (double) totalCost / n); + } + + // ---- Binary counter: a single increment can flip many bits ---- + // Potential method: let Phi = number of 1 bits. An increment flipping k + // trailing 1s has actual cost k+1 and changes Phi by 1-k, so the + // amortized cost is (k+1) + (1-k) = 2. + static void measureCounter(int n) { + int[] bits = new int[64]; + long flips = 0; + + for (int k = 0; k < n; k++) { + int i = 0; + while (bits[i] == 1) { bits[i] = 0; flips++; i++; } + bits[i] = 1; flips++; + } + System.out.printf("n=%d\\tflips=%d\\tper increment=%.5f%n", + n, flips, (double) flips / n); + } + + public static void main(String[] args) { + System.out.println("Doubling array - per-append cost stays constant:"); + for (int n : new int[]{1000, 10000, 100000}) measureAppends(n); + + System.out.println("\\nConstant growth - per-append cost does NOT:"); + for (int n : new int[]{1000, 10000, 100000}) measureConstantGrowth(n, 10); + + System.out.println("\\nBinary counter - converges on 2 per increment:"); + for (int n : new int[]{100, 10000, 1000000}) measureCounter(n); + } +}`, + + c: `/* Amortized analysis, measured rather than asserted. */ + +#include +#include +#include + +/* ---- A dynamic array that reports what each append really costs ---- */ +typedef struct { + int *buffer; + long capacity; + long size; + long totalCost; +} DynamicArray; + +void initArray(DynamicArray *arr) { + arr->buffer = malloc(sizeof(int)); + arr->capacity = 1; + arr->size = 0; + arr->totalCost = 0; +} + +long append(DynamicArray *arr, int value) { + long cost = 1; /* the write itself */ + + if (arr->size == arr->capacity) { /* full: grow and copy */ + int *bigger = malloc(arr->capacity * 2 * sizeof(int)); + memcpy(bigger, arr->buffer, arr->size * sizeof(int)); + + cost += arr->size; /* Theta(n) - but only sometimes */ + free(arr->buffer); + arr->buffer = bigger; + arr->capacity *= 2; + } + + arr->buffer[arr->size++] = value; + arr->totalCost += cost; + return cost; +} + +/* Aggregate analysis says total < 3n, so the average is O(1). */ +void measureAppends(long n) { + DynamicArray arr; + initArray(&arr); + for (long i = 0; i < n; i++) append(&arr, (int) i); + + printf("n=%ld\\ttotal=%ld\\tper append=%.3f\\n", + n, arr.totalCost, (double) arr.totalCost / n); + free(arr.buffer); +} + +/* ---- Growing by a CONSTANT instead: the guarantee disappears ---- */ +void measureConstantGrowth(long n, long step) { + long capacity = step, size = 0, totalCost = 0; + + for (long i = 0; i < n; i++) { + long cost = 1; + if (size == capacity) { + cost += size; /* copy everything, again */ + capacity += step; /* only to fill up again soon */ + } + totalCost += cost; + size++; + } + printf("n=%ld\\ttotal=%ld\\tper append=%.1f <- grows with n\\n", + n, totalCost, (double) totalCost / n); +} + +/* ---- Binary counter: a single increment can flip many bits ---- + Potential method: let Phi = number of 1 bits. An increment flipping k + trailing 1s has actual cost k+1 and changes Phi by 1-k, so the + amortized cost is (k+1) + (1-k) = 2. */ +void measureCounter(long n) { + int bits[64] = {0}; + long flips = 0; + + for (long k = 0; k < n; k++) { + int i = 0; + while (bits[i] == 1) { bits[i] = 0; flips++; i++; } + bits[i] = 1; flips++; + } + printf("n=%ld\\tflips=%ld\\tper increment=%.5f\\n", + n, flips, (double) flips / n); +} + +int main(void) { + printf("Doubling array - per-append cost stays constant:\\n"); + measureAppends(1000); measureAppends(10000); measureAppends(100000); + + printf("\\nConstant growth - per-append cost does NOT:\\n"); + measureConstantGrowth(1000, 10); measureConstantGrowth(10000, 10); + + printf("\\nBinary counter - converges on 2 per increment:\\n"); + measureCounter(100); measureCounter(10000); measureCounter(1000000); + return 0; +}`, + + cpp: `// Amortized analysis, measured rather than asserted. + +#include +#include +#include + +// ---- A dynamic array that reports what each append really costs ---- +class DynamicArray { +public: + long totalCost = 0; + + long append(int value) { + long cost = 1; // the write itself + + if (size_ == capacity_) { // full: grow and copy + std::vector bigger(capacity_ * 2); + for (long i = 0; i < size_; i++) bigger[i] = buffer_[i]; + + cost += size_; // Theta(n) - but only sometimes + buffer_ = std::move(bigger); + capacity_ *= 2; + } + + buffer_[size_++] = value; + totalCost += cost; + return cost; + } + +private: + std::vector buffer_ = std::vector(1); + long capacity_ = 1; + long size_ = 0; +}; + +// Aggregate analysis says total < 3n, so the average is O(1). +void measureAppends(long n) { + DynamicArray arr; + for (long i = 0; i < n; i++) arr.append(static_cast(i)); + + std::cout << "n=" << n << "\\ttotal=" << arr.totalCost << "\\tper append=" + << std::fixed << std::setprecision(3) + << static_cast(arr.totalCost) / n << "\\n"; +} + +// ---- Growing by a CONSTANT instead: the guarantee disappears ---- +void measureConstantGrowth(long n, long step = 10) { + long capacity = step, size = 0, totalCost = 0; + + for (long i = 0; i < n; i++) { + long cost = 1; + if (size == capacity) { + cost += size; // copy everything, again + capacity += step; // only to fill up again soon + } + totalCost += cost; + size++; + } + std::cout << "n=" << n << "\\ttotal=" << totalCost << "\\tper append=" + << std::setprecision(1) + << static_cast(totalCost) / n << " <- grows with n\\n"; +} + +// ---- Binary counter: a single increment can flip many bits ---- +// Potential method: let Phi = number of 1 bits. An increment flipping k +// trailing 1s has actual cost k+1 and changes Phi by 1-k, so the +// amortized cost is (k+1) + (1-k) = 2. +void measureCounter(long n) { + std::vector bits(64, 0); + long flips = 0; + + for (long k = 0; k < n; k++) { + int i = 0; + while (bits[i] == 1) { bits[i] = 0; flips++; i++; } + bits[i] = 1; flips++; + } + std::cout << "n=" << n << "\\tflips=" << flips << "\\tper increment=" + << std::setprecision(5) + << static_cast(flips) / n << "\\n"; +} + +int main() { + std::cout << "Doubling array - per-append cost stays constant:\\n"; + for (long n : {1000L, 10000L, 100000L}) measureAppends(n); + + std::cout << "\\nConstant growth - per-append cost does NOT:\\n"; + for (long n : {1000L, 10000L, 100000L}) measureConstantGrowth(n); + + std::cout << "\\nBinary counter - converges on 2 per increment:\\n"; + for (long n : {100L, 10000L, 1000000L}) measureCounter(n); + return 0; +}`, +}; + +export default codeExamples; diff --git a/app/design-algorithm/fundamentals/amortized-analysis/content.jsx b/app/design-algorithm/fundamentals/amortized-analysis/content.jsx new file mode 100755 index 0000000..e6bc121 --- /dev/null +++ b/app/design-algorithm/fundamentals/amortized-analysis/content.jsx @@ -0,0 +1,694 @@ +"use client"; +import DailyDSAEmbed from "@/app/components/ui/DailyDSAEmbed"; +import { useTheme } from "@/app/contexts/ThemeContext"; +import NewsletterEmbed from "@/app/components/ui/NewsletterEmbed"; +import InContentAd from "@/app/components/ads/InContentAd"; + +// The real cost of the first 32 appends to a doubling array: mostly 1, with a +// spike every power of two. Seeing the spikes next to the flat amortized line +// is the whole argument in one picture. +const appendCosts = (n) => { + const costs = []; + let capacity = 1; + let size = 0; + + for (let i = 0; i < n; i++) { + let cost = 1; + if (size === capacity) { + cost += size; // copy every existing element into the new buffer + capacity *= 2; + } + costs.push(cost); + size++; + } + return costs; +}; + +const CostChart = () => { + const W = 380; + const H = 190; + const PAD_L = 26; + const PAD_R = 10; + const PAD_T = 14; + const PAD_B = 28; + + const costs = appendCosts(32); + const maxCost = Math.max(...costs); + const plotW = W - PAD_L - PAD_R; + const plotH = H - PAD_T - PAD_B; + + const barW = plotW / costs.length; + const toY = (c) => PAD_T + plotH - (c / maxCost) * plotH; + + const total = costs.reduce((sum, c) => sum + c, 0); + const average = total / costs.length; + + return ( +
+ + {/* Axes */} + + + + {costs.map((cost, i) => { + const isSpike = cost > 1; + return ( + + ); + })} + + {/* The amortized average */} + + + amortized ≈ {average.toFixed(2)} + + + + {maxCost} + + + 1 + + + append number + + +
+ Most appends cost 1. The red spikes are resizes, and they double in height + — but they also halve in frequency, which is exactly why the average stays + flat. +
+
+ ); +}; + +const Section = ({ title, children }) => ( +
+

+ + {title} +

+
{children}
+
+); + +const P = ({ children }) => ( +

{children}

+); + +const Formula = ({ children }) => ( +
+ + {children} + +
+); + +const Derivation = ({ steps, caption }) => ( +
+
+ {steps.map((step, index) => ( +
+ + {step.expr} + + {step.note && ( + + {step.note} + + )} +
+ ))} +
+ {caption &&

{caption}

} +
+); + +const CodeSample = ({ children, caption }) => ( +
+
+      {children}
+    
+ {caption &&

{caption}

} +
+); + +const Table = ({ headers, rows, firstColMono = true }) => ( +
+ + + + {headers.map((header, index) => ( + + ))} + + + + {rows.map((row, rowIndex) => ( + + {row.map((cell, cellIndex) => ( + + ))} + + ))} + +
+ {header} +
+ {cell} +
+
+); + +const List = ({ items, ordered = false }) => { + const Tag = ordered ? "ol" : "ul"; + return ( + + {items.map((item, index) => ( +
  • + {item.points} + {item.subpoints && ( +
      + {item.subpoints.map((subitem, subindex) => ( +
    • + {subitem} +
    • + ))} +
    + )} +
  • + ))} +
    + ); +}; + +const Callout = ({ children, tone = "blue" }) => { + const tones = { + blue: "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800", + amber: "bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800", + }; + return ( +
    +

    {children}

    +
    + ); +}; + +const Content = () => { + const { theme } = useTheme(); + + const appendRows = [ + ["1", "1", "1", "No resize needed"], + ["2", "2", "1 + 1", "Capacity full: copy 1 element"], + ["3", "4", "1 + 2", "Capacity full: copy 2 elements"], + ["4", "4", "1", "Room to spare"], + ["5", "8", "1 + 4", "Capacity full: copy 4 elements"], + ["6–8", "8", "1 each", "Room to spare"], + ["9", "16", "1 + 8", "Capacity full: copy 8 elements"], + ]; + + const differences = [ + { + points: "Average-case analysis assumes a probability distribution over inputs.", + subpoints: [ + "Quick sort is O(n log n) on average because we assume the pivot is usually reasonable. An unlucky input still costs O(n²).", + ], + }, + { + points: "Amortized analysis assumes nothing and involves no probability.", + subpoints: [ + "It is a worst-case guarantee about a whole sequence. No adversary can construct an input that makes n appends cost more than O(n) in total.", + ], + }, + { + points: "The guarantee is about the sequence, not any single operation.", + subpoints: [ + "One individual append genuinely can cost Θ(n). Amortized analysis never claims otherwise — it claims those expensive operations cannot happen often.", + ], + }, + ]; + + const methodRows = [ + [ + "Aggregate", + "Total cost of n operations, divided by n", + "Simplest, but gives one average for all operation types", + "Binary counter, dynamic array", + ], + [ + "Accounting", + "Overcharge cheap operations, store the surplus as credit", + "Different operations can have different amortized costs", + "Stack with multipop, dynamic array", + ], + [ + "Potential", + "Define Φ over the data structure; amortized = actual + ΔΦ", + "Most powerful and most mechanical; no bookkeeping of individual credits", + "Splay trees, Fibonacci heaps, union-find", + ], + ]; + + const counterRows = [ + ["0", "0 0 0 0", "—", "—"], + ["1", "0 0 0 1", "1", "1"], + ["2", "0 0 1 0", "2", "3"], + ["3", "0 0 1 1", "1", "4"], + ["4", "0 1 0 0", "3", "7"], + ["5", "0 1 0 1", "1", "8"], + ["6", "0 1 1 0", "2", "10"], + ["7", "0 1 1 1", "1", "11"], + ["8", "1 0 0 0", "4", "15"], + ]; + + const classicRows = [ + ["Dynamic array append", "Θ(n) on resize", "O(1)", "Resizes double in cost but halve in frequency"], + ["Binary counter increment", "Θ(log n) bit flips", "O(1)", "Bit i only flips every 2ⁱ increments"], + ["Stack with multipop", "Θ(n) for one multipop", "O(1)", "Each element can only be popped once after being pushed"], + ["Hash table insert with rehash", "Θ(n) on rehash", "O(1)", "Same doubling argument as the dynamic array"], + ["Union-Find (rank + path compression)", "Θ(log n)", "O(α(n))", "α is the inverse Ackermann function — effectively ≤ 4"], + ["Splay tree operations", "Θ(n)", "O(log n)", "A costly splay restructures the tree, making later ones cheap"], + ["Fibonacci heap extract-min", "Θ(n)", "O(log n)", "Consolidation is deferred until an extract forces it"], + ]; + + const limits = [ + { + points: "Real-time and safety-critical systems.", + subpoints: [ + "A pacemaker or an anti-lock braking controller cannot accept one operation taking 100× longer, even if the average is excellent. These systems need worst-case-per-operation bounds.", + ], + }, + { + points: "Interactive latency and tail percentiles.", + subpoints: [ + "A resize that stalls one request in a thousand shows up as a p99 latency spike. The amortized average is genuinely O(1) and the user experience is still bad.", + ], + }, + { + points: "Short sequences.", + subpoints: [ + "The guarantee is about long runs. If you perform three operations and one of them triggers a resize, the amortized bound has not had room to pay off.", + ], + }, + ]; + + const mistakes = [ + { + points: "Confusing amortized with average-case.", + subpoints: [ + "Average-case involves probability over inputs. Amortized is a deterministic worst-case bound on a sequence, with no randomness anywhere.", + ], + }, + { + points: 'Saying "append is O(1)" without qualification.', + subpoints: [ + "A single append is O(n) in the worst case. The correct phrasing is O(1) amortized, and dropping the qualifier is exactly what confuses people who then see a latency spike.", + ], + }, + { + points: "Letting credit go negative in the accounting method.", + subpoints: [ + "The proof only works if the balance is non-negative at every point in the sequence. Verifying that is the actual work of the method.", + ], + }, + { + points: "Choosing a potential function that can decrease below its start.", + subpoints: [ + "Φ must satisfy Φ(Dᵢ) ≥ Φ(D₀) for all i, usually arranged by making Φ(D₀) = 0 and Φ non-negative. Otherwise the telescoping sum does not bound the real cost.", + ], + }, + { + points: "Assuming growth by a constant amount works too.", + subpoints: [ + "Growing a array by adding 10 slots instead of doubling makes n appends cost Θ(n²) in total. Only geometric growth gives O(1) amortized.", + ], + }, + ]; + + const faqs = [ + { + q: "What is amortized analysis?", + a: "It is a way of measuring the cost of an operation by averaging it over a worst-case sequence of operations, rather than looking at a single operation in isolation. It is used when an occasional expensive operation is guaranteed to be paid for by many cheap ones — like appending to a dynamic array, where the rare resize is offset by all the appends that fit without resizing.", + }, + { + q: "Is amortized analysis the same as average-case analysis?", + a: "No, and this is the most common confusion. Average-case analysis assumes a probability distribution over inputs and tells you what happens typically. Amortized analysis involves no probability at all: it is a worst-case guarantee about the total cost of a sequence. No adversarial input can make n appends to a dynamic array cost more than O(n) overall.", + }, + { + q: "Why is appending to a dynamic array O(1) amortized?", + a: "When the array is full it allocates a buffer of double the size and copies everything across, which costs Θ(n). But doubling means the next resize is twice as far away. Over n appends the copies total 1 + 2 + 4 + ... + n, which is less than 2n, so the whole sequence costs O(n) and each append averages O(1).", + }, + { + q: "What are the three methods of amortized analysis?", + a: "Aggregate analysis totals the cost of n operations and divides by n. The accounting method assigns each operation an amortized charge, banking the surplus from cheap operations as credit to pay for expensive ones. The potential method defines a function Φ over the data structure's state, with the amortized cost being the actual cost plus the change in Φ. All three give the same answers; they differ in convenience.", + }, + { + q: "What is the potential method?", + a: "You define a potential function Φ that maps the data structure's state to a number representing stored-up work. The amortized cost of an operation is its actual cost plus Φ(after) − Φ(before). Because the Φ terms telescope across a sequence, the total amortized cost bounds the total actual cost whenever Φ never drops below its starting value.", + }, + { + q: "When is an amortized bound not good enough?", + a: "When any individual operation being slow is unacceptable. Real-time systems, safety-critical controllers and latency-sensitive services all care about the worst single operation, not the average across a sequence — a resize that stalls one request in a thousand still shows up as a p99 latency spike even though the amortized cost is O(1).", + }, + ]; + + return ( +
    +
    + + +
    +
    +
    +

    + Some data structures have an operation that is usually trivial and + occasionally enormous. Appending to a dynamic array normally writes one + slot, but when the buffer fills it allocates a bigger one and copies + everything across. Quoting the worst case for that operation gives + O(n), which is technically correct and deeply misleading — it suggests + that building a list of a million items costs a trillion operations, + when it actually costs about two million. +

    +

    + Amortized analysis measures the average cost per operation across a + worst-case sequence of operations. Instead of asking "how bad + can one append be?", it asks "how bad can n appends be, in + total?" — and then divides. When the expensive cases are + structurally guaranteed to be rare, that average is the honest number. +

    +
    + +
    +

    + A dynamic array keeps a buffer with some capacity. Appending writes one + element; if the buffer is full, it first allocates one of double the + capacity and copies every existing element across: +

    + {`function append(arr, value) { + if (arr.size === arr.capacity) { + const bigger = new Array(arr.capacity * 2); // Θ(n) work, + for (let i = 0; i < arr.size; i++) { // but only when full + bigger[i] = arr.buffer[i]; + } + arr.buffer = bigger; + arr.capacity *= 2; + } + + arr.buffer[arr.size] = value; // Θ(1) the rest of the time + arr.size++; +}`} + + +

    + The picture contains the entire argument. The spikes double in height — + but they also double in spacing. Each resize is twice as expensive as + the last and happens half as often, and those two effects cancel + exactly. +

    + + +
    +

    + The simplest method: add up the cost of the whole sequence, then + divide by the number of operations. For n appends, the writes cost n, + and the copies happen at sizes 1, 2, 4, 8, … up to n: +

    + +

    + Running this for real confirms it: the total cost of n appends divided + by n settles at about 2.05 and stays there, whether n is a thousand or + a million. The bound of 3 is comfortable, and the important point is + that it is a constant — it does not creep upward with n. +

    + + The reason doubling works is that the growth is geometric. If + you instead grew the buffer by a fixed 10 slots each time, you would + resize n/10 times, copying an average of n/2 elements each time — + Θ(n²) in total, and Θ(n) amortized per append. The choice of growth + factor is what creates the guarantee. + +
    + +
    +

    + A second classic. Incrementing a binary counter flips a trailing run of + 1s to 0 and then one 0 to 1, so a single increment can flip Θ(log n) + bits. Watch what actually happens over a sequence: +

    +
    +

    + After 8 increments only 15 bits have flipped, not 8 × 4. The reason is + visible in the table: bit 0 flips every time, bit 1 flips every second + increment, bit 2 every fourth, and so on: +

    + +

    + Measured over 100,000 increments, the ratio is 1.99998 flips per + increment — converging on 2 exactly as the series predicts. +

    + + + + +
    +

    + Also called the banker's method. You invent a charge for + each operation — its amortized cost — which may be more or less than + what the operation really costs. The surplus is stored as{" "} + credit on the data structure and later spent on expensive + operations. +

    +

    + One rule makes the method valid: the credit balance must never go + negative. If it never does, the total amount charged is an upper + bound on the total real cost, which is exactly what an amortized bound + claims. +

    +

    For the dynamic array, charge 3 units per append and spend them as:

    + +

    + When a resize of a size-n buffer happens, the n elements to be copied + are covered: the n/2 elements added since the last resize carry 2 units + each, which is enough for themselves and for one older element apiece. + The balance never goes negative, so append is O(1) amortized. +

    +

    + The method's advantage over aggregate analysis is that different + operations can carry different charges. For a stack supporting push, + pop and multipop(k), charge 2 for a push (1 to push, 1 banked for the + eventual pop) and 0 for pop and multipop. Every pop is then paid for by + the credit its push left behind — so even a multipop that removes a + thousand elements is free, because those thousand pushes already paid. +

    +
    + +
    +

    + The physicist's method, and the most powerful of the three. + Instead of tracking credit on individual elements, define a{" "} + potential function Φ that maps the whole state of the data + structure to a number — the stored-up work it represents. +

    + amortized cost = actual cost + Φ(after) − Φ(before) +

    + Summed over a sequence, the Φ terms telescope: every intermediate value + appears once positive and once negative, leaving only Φ(end) − Φ(start). + So as long as Φ never drops below its starting value — usually + arranged by setting Φ(D₀) = 0 and keeping Φ ≥ 0 — the total amortized + cost is an upper bound on the total real cost. +

    +

    + Binary counter. Let Φ be the number of 1 bits. An increment that + flips k trailing 1s to 0 and one 0 to 1 has actual cost k + 1, and + changes the bit count by 1 − k: +

    + +

    + The k vanishing is the whole trick. An expensive increment is expensive + precisely because it destroys many 1 bits, and destroying them releases + exactly the potential needed to pay for the work. +

    +

    + Dynamic array. Let Φ = 2·size − capacity. Immediately after a + resize, size is half of capacity so Φ = 0; as appends fill the buffer, + Φ climbs to equal capacity by the time the next resize is due — having + accumulated precisely enough potential to fund the copy. Working through + both cases gives an amortized cost of 3 per append, agreeing with the + accounting method. +

    +
    + +
    +
    +

    + All three are provably equivalent in power — any bound one can + establish, the others can too. Aggregate analysis is the one to reach + for when every operation is the same kind. The accounting method suits + structures with several operation types. The potential method is the + standard choice for anything genuinely difficult, because once Φ is + chosen the rest is mechanical. +

    + + +
    +

    + These two are constantly conflated, and the distinction matters: +

    + + + Quick sort is O(n log n) average-case: get unlucky and you still + pay O(n²). A dynamic array is O(1) amortized: there is no bad + luck available, because no sequence of n appends can cost more than + O(n) in total. One is a statement about probability; the other is a + guarantee. + +
    + +
    +
    +

    + Union-Find is the most striking entry. With union by rank and path + compression, a sequence of m operations costs O(m·α(n)), where α is the + inverse Ackermann function — a function that grows so slowly it is below + 5 for any n that could be written down in this universe. The + per-operation worst case is still logarithmic; only the amortized + analysis reveals that the structure is effectively constant-time. +

    + + +
    +

    + Amortized analysis answers "how much work in total?". Some + systems need to ask "how long will this one call + take?", and for them the average is the wrong statistic: +

    + +

    + The engineering response is not to abandon the structure but to spread + the cost deliberately — incremental or background resizing, or + preallocating capacity up front when the final size is known. Both + convert a rare large stall into a small predictable overhead on every + operation. +

    +
    + +
    + +
    + +
    +
    + {faqs.map((faq, index) => ( +
    +

    + {faq.q} +

    +

    {faq.a}

    +
    + ))} +
    +
    + +
    + +
    + + + + + ); +}; + +export default Content; diff --git a/app/design-algorithm/fundamentals/amortized-analysis/page.jsx b/app/design-algorithm/fundamentals/amortized-analysis/page.jsx new file mode 100755 index 0000000..075eb0d --- /dev/null +++ b/app/design-algorithm/fundamentals/amortized-analysis/page.jsx @@ -0,0 +1,153 @@ +import Navbar from "@/app/components/navbarinner"; +import ModuleHeader from "@/app/components/modules/Header"; +import Footer from "@/app/components/footer"; +import BackToTop from "@/app/components/ui/backtotop"; +import ExploreOther from "@/app/components/ui/exploreOther"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; +import Content from "./content"; + +export const metadata = { + alternates: { + canonical: "/design-algorithm/fundamentals/amortized-analysis", + }, + title: "Amortized Analysis — Aggregate, Accounting and Potential Methods", + description: + "Learn amortized analysis: why an occasional expensive operation does not make a data structure slow. Covers the dynamic array doubling argument, the binary counter, all three methods (aggregate, accounting, potential), how amortized differs from average-case, and when an amortized bound is not good enough.", + keywords: [ + "Amortized Analysis", + "Amortized Time Complexity", + "Aggregate Analysis", + "Accounting Method", + "Banker's Method", + "Potential Method", + "Potential Function", + "Amortized vs Average Case", + "Dynamic Array Doubling", + "Dynamic Array Amortized O(1)", + "Binary Counter Increment", + "Stack Multipop", + "Union Find Inverse Ackermann", + "Splay Tree Amortized", + "Fibonacci Heap", + "Hash Table Rehashing", + "Algorithm Analysis", + "Design and Analysis of Algorithms", + "DAA Amortized Analysis", + "Tail Latency", + "DSA Interview Preparation", + ], + robots: "index, follow", +}; + +// FAQ answers mirror the "Frequently Asked Questions" section in content.jsx. +// Keep the two in sync — structured data that does not match the visible page +// is a manual-action risk. +const faqJsonLd = { + "@context": "https://schema.org", + "@type": "FAQPage", + mainEntity: [ + { + "@type": "Question", + name: "What is amortized analysis?", + acceptedAnswer: { + "@type": "Answer", + text: "It is a way of measuring the cost of an operation by averaging it over a worst-case sequence of operations, rather than looking at a single operation in isolation. It is used when an occasional expensive operation is guaranteed to be paid for by many cheap ones — like appending to a dynamic array, where the rare resize is offset by all the appends that fit without resizing.", + }, + }, + { + "@type": "Question", + name: "Is amortized analysis the same as average-case analysis?", + acceptedAnswer: { + "@type": "Answer", + text: "No, and this is the most common confusion. Average-case analysis assumes a probability distribution over inputs and tells you what happens typically. Amortized analysis involves no probability at all: it is a worst-case guarantee about the total cost of a sequence. No adversarial input can make n appends to a dynamic array cost more than O(n) overall.", + }, + }, + { + "@type": "Question", + name: "Why is appending to a dynamic array O(1) amortized?", + acceptedAnswer: { + "@type": "Answer", + text: "When the array is full it allocates a buffer of double the size and copies everything across, which costs Theta(n). But doubling means the next resize is twice as far away. Over n appends the copies total 1 + 2 + 4 + ... + n, which is less than 2n, so the whole sequence costs O(n) and each append averages O(1).", + }, + }, + { + "@type": "Question", + name: "What are the three methods of amortized analysis?", + acceptedAnswer: { + "@type": "Answer", + text: "Aggregate analysis totals the cost of n operations and divides by n. The accounting method assigns each operation an amortized charge, banking the surplus from cheap operations as credit to pay for expensive ones. The potential method defines a function Phi over the data structure's state, with the amortized cost being the actual cost plus the change in Phi. All three give the same answers; they differ in convenience.", + }, + }, + { + "@type": "Question", + name: "What is the potential method in amortized analysis?", + acceptedAnswer: { + "@type": "Answer", + text: "You define a potential function Phi that maps the data structure's state to a number representing stored-up work. The amortized cost of an operation is its actual cost plus Phi(after) minus Phi(before). Because the Phi terms telescope across a sequence, the total amortized cost bounds the total actual cost whenever Phi never drops below its starting value.", + }, + }, + { + "@type": "Question", + name: "When is an amortized bound not good enough?", + acceptedAnswer: { + "@type": "Answer", + text: "When any individual operation being slow is unacceptable. Real-time systems, safety-critical controllers and latency-sensitive services all care about the worst single operation, not the average across a sequence — a resize that stalls one request in a thousand still shows up as a p99 latency spike even though the amortized cost is O(1).", + }, + }, + ], +}; + +export default function Page() { + const paths = [ + { name: "Home", href: "/" }, + { name: "Design & Algorithm", href: "/design-algorithm" }, + { name: "Amortized Analysis", href: "" }, + ]; + + return ( + <> +