> ## Documentation Index
> Fetch the complete documentation index at: https://resources.latex-cloud-studio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Algorithms, Complexity, and CS Notation in LaTeX

> Learn algorithm notation, complexity classes, and computer science symbols in LaTeX. For step-by-step pseudocode with algorithmicx, see the dedicated guide.

export const RenderedOutput = ({title = "Rendered output", ctaHref, ctaLabel = "Open LaTeX Cloud Studio", children}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const trackEditorCta = () => {
    const target = new URL(ctaHref, window.location.href);
    globalThis.posthog?.capture?.("docs_app_cta_clicked", {
      source_page: window.location.pathname,
      source_section: "rendered_output",
      cta_variant: "first_compiled_example",
      target_url: target.toString(),
      target_utm_source: target.searchParams.get("utm_source"),
      target_utm_medium: target.searchParams.get("utm_medium"),
      target_utm_campaign: target.searchParams.get("utm_campaign"),
      target_utm_content: target.searchParams.get("utm_content")
    }, {
      transport: "sendBeacon",
      send_instantly: true
    });
  };
  return <details className="rendered-output" onToggle={event => setIsExpanded(event.currentTarget.open)}>
      <summary className="rendered-output__summary">
        <span className="rendered-output__title">{title}</span>
        <span className="rendered-output__hint" aria-hidden="true">View compiled result</span>
      </summary>
      {isExpanded && <div className="rendered-output__content">
          {children}
          {ctaHref && <aside className="rendered-output__cta" aria-label="Continue in the LaTeX editor">
              <span>
                <strong>Ready to use this syntax?</strong>
                Continue in the browser editor when you want to adapt the example in a real project.
              </span>
              <a href={ctaHref} onClick={trackEditorCta}>{ctaLabel}<span aria-hidden="true"> →</span></a>
            </aside>}
        </div>}
    </details>;
};

export const LatexSource = ({filename, source}) => {
  const [copyStatus, setCopyStatus] = useState("Copy");
  const copySource = async () => {
    try {
      await navigator.clipboard.writeText(source);
      setCopyStatus("Copied");
    } catch {
      setCopyStatus("Select and copy");
    }
  };
  return <figure className="latex-source">
      <figcaption className="latex-source__header">
        <span className="latex-source__filename">{filename}</span>
        <button type="button" className="latex-source__copy" onClick={copySource} aria-live="polite">
          {copyStatus}
        </button>
      </figcaption>
      <pre className="latex-source__pre" aria-label={`LaTeX source: ${filename}`} tabIndex="0">
        <code className="language-latex">{source}</code>
      </pre>
    </figure>;
};

export const LatexPreview = ({src, alt, caption, width, height}) => {
  const minZoom = 1;
  const maxZoom = 3;
  const zoomStep = 0.5;
  const measureSvgContent = async (assetSrc, pageWidth, pageHeight) => {
    const cacheKey = "__latexCloudSvgContentBoxCache";
    const contentBoxCache = globalThis[cacheKey] ?? new Map();
    globalThis[cacheKey] = contentBoxCache;
    if (contentBoxCache.has(assetSrc)) return contentBoxCache.get(assetSrc);
    const measurement = (async () => {
      const assetUrl = new URL(assetSrc, window.location.href);
      if (assetUrl.origin !== window.location.origin) {
        throw new Error("Rendered output must use a same-origin SVG asset.");
      }
      const response = await fetch(assetUrl, {
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error(`Rendered output request failed with ${response.status}.`);
      const source = await response.text();
      const documentNode = new DOMParser().parseFromString(source, "image/svg+xml");
      if (documentNode.querySelector("parsererror")) throw new Error("Rendered output is not valid SVG.");
      const sourceSvg = documentNode.documentElement;
      sourceSvg.querySelectorAll("script, foreignObject").forEach(node => node.remove());
      [sourceSvg, ...sourceSvg.querySelectorAll("*")].forEach(node => {
        [...node.attributes].forEach(attribute => {
          if ((/^on/i).test(attribute.name)) node.removeAttribute(attribute.name);
          if ((attribute.name === "href" || attribute.name === "xlink:href") && !attribute.value.startsWith("#")) {
            node.removeAttribute(attribute.name);
          }
        });
      });
      const measurementHost = document.createElement("div");
      measurementHost.className = "latex-preview__measurement-host";
      const measuredSvg = document.importNode(sourceSvg, true);
      measuredSvg.setAttribute("aria-hidden", "true");
      measurementHost.appendChild(measuredSvg);
      document.body.appendChild(measurementHost);
      try {
        const measuredElements = [...measuredSvg.children].filter(node => !["defs", "desc", "metadata", "style", "title"].includes(node.tagName.toLowerCase()));
        const elementBounds = measuredElements.map(node => node.getBBox()).filter(box => [box.x, box.y, box.width, box.height].every(Number.isFinite) && box.width > 0 && box.height > 0);
        if (elementBounds.length === 0) {
          throw new Error("Rendered output has no measurable visible content.");
        }
        const sortedBounds = [...elementBounds].sort((left, right) => left.y - right.y);
        const clusterGap = pageHeight * 0.045;
        const clusters = [];
        sortedBounds.forEach(box => {
          const current = clusters[clusters.length - 1];
          if (!current || box.y - current.bottom > clusterGap) {
            clusters.push({
              boxes: [box],
              bottom: box.y + box.height
            });
            return;
          }
          current.boxes.push(box);
          current.bottom = Math.max(current.bottom, box.y + box.height);
        });
        const contentClusters = clusters.filter(cluster => {
          const clusterBox = cluster.boxes.reduce((combined, box) => {
            const right = Math.max(combined.x + combined.width, box.x + box.width);
            const bottom = Math.max(combined.y + combined.height, box.y + box.height);
            const x = Math.min(combined.x, box.x);
            const y = Math.min(combined.y, box.y);
            return {
              x,
              y,
              width: right - x,
              height: bottom - y
            };
          });
          const centerY = clusterBox.y + clusterBox.height / 2;
          const isMarginFurniture = cluster.boxes.length <= 2 && clusterBox.width < pageWidth * 0.2 && clusterBox.height < pageHeight * 0.04 && (centerY < pageHeight * 0.08 || centerY > pageHeight * 0.8);
          return !isMarginFurniture;
        });
        const visibleBounds = (contentClusters.length > 0 ? contentClusters : clusters).flatMap(cluster => cluster.boxes);
        const bounds = visibleBounds.reduce((combined, box) => {
          const right = Math.max(combined.x + combined.width, box.x + box.width);
          const bottom = Math.max(combined.y + combined.height, box.y + box.height);
          const x = Math.min(combined.x, box.x);
          const y = Math.min(combined.y, box.y);
          return {
            x,
            y,
            width: right - x,
            height: bottom - y
          };
        });
        const clampValue = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, value));
        const padding = Math.max(8, Math.min(pageWidth, pageHeight) * 0.025);
        const x = clampValue(bounds.x - padding, 0, pageWidth);
        const y = clampValue(bounds.y - padding, 0, pageHeight);
        const right = clampValue(bounds.x + bounds.width + padding, 0, pageWidth);
        const bottom = clampValue(bounds.y + bounds.height + padding, 0, pageHeight);
        return {
          x,
          y,
          width: right - x,
          height: bottom - y
        };
      } finally {
        measurementHost.remove();
      }
    })();
    contentBoxCache.set(assetSrc, measurement);
    measurement.catch(() => contentBoxCache.delete(assetSrc));
    return measurement;
  };
  const renderPreviewAsset = ({contentBox: assetContentBox, loading}) => {
    if (!assetContentBox) {
      return <img className="latex-preview__asset" src={src} alt={alt} width={width} height={height} loading={loading} draggable="false" />;
    }
    return <svg className="latex-preview__asset" viewBox={`${assetContentBox.x} ${assetContentBox.y} ${assetContentBox.width} ${assetContentBox.height}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label={alt}>
        <image href={src} x="0" y="0" width={width} height={height} />
      </svg>;
  };
  const [isOpen, setIsOpen] = useState(false);
  const [frameMode, setFrameMode] = useState("content");
  const [viewMode, setViewMode] = useState("fit");
  const [zoom, setZoom] = useState(minZoom);
  const [contentBox, setContentBox] = useState(null);
  const [measurementStatus, setMeasurementStatus] = useState("loading");
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const viewportRef = useRef(null);
  const previousFocusRef = useRef(null);
  const dragRef = useRef(null);
  useEffect(() => {
    let isCurrent = true;
    setMeasurementStatus("loading");
    measureSvgContent(src, width, height).then(box => {
      if (!isCurrent) return;
      setContentBox(box);
      setMeasurementStatus("ready");
    }).catch(() => {
      if (!isCurrent) return;
      setContentBox(null);
      setFrameMode("page");
      setMeasurementStatus("error");
    });
    return () => {
      isCurrent = false;
    };
  }, [height, src, width]);
  const closeViewer = useCallback(() => {
    setIsOpen(false);
  }, []);
  const openViewer = () => {
    previousFocusRef.current = document.activeElement;
    setFrameMode(contentBox ? "content" : "page");
    setViewMode("fit");
    setZoom(minZoom);
    setIsOpen(true);
  };
  const applyZoom = useCallback(nextZoom => {
    const boundedZoom = Math.min(maxZoom, Math.max(minZoom, nextZoom));
    setViewMode("custom");
    setZoom(boundedZoom);
  }, []);
  const zoomIn = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom + zoomStep : zoom + zoomStep);
  }, [applyZoom, viewMode, zoom]);
  const zoomOut = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom : zoom - zoomStep);
  }, [applyZoom, viewMode, zoom]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();
    return () => {
      document.body.style.overflow = previousOverflow;
      previousFocusRef.current?.focus?.();
    };
  }, [isOpen]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const handleKeyDown = event => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeViewer();
        return;
      }
      if ((event.key === "+" || event.key === "=") && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomIn();
        return;
      }
      if (event.key === "-" && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomOut();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')];
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeViewer, isOpen, zoomIn, zoomOut]);
  const startDrag = event => {
    if (event.button !== 0 || !viewportRef.current) return;
    const viewport = viewportRef.current;
    dragRef.current = {
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      scrollLeft: viewport.scrollLeft,
      scrollTop: viewport.scrollTop
    };
    viewport.setPointerCapture(event.pointerId);
    viewport.dataset.dragging = "true";
  };
  const continueDrag = event => {
    const drag = dragRef.current;
    const viewport = viewportRef.current;
    if (!drag || !viewport || drag.pointerId !== event.pointerId) return;
    viewport.scrollLeft = drag.scrollLeft - (event.clientX - drag.x);
    viewport.scrollTop = drag.scrollTop - (event.clientY - drag.y);
  };
  const stopDrag = event => {
    const viewport = viewportRef.current;
    if (viewport?.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
    if (viewport) delete viewport.dataset.dragging;
    dragRef.current = null;
  };
  const activeContentBox = frameMode === "content" ? contentBox : null;
  const activeWidth = activeContentBox?.width ?? width;
  const activeHeight = activeContentBox?.height ?? height;
  const activeRatio = activeWidth / activeHeight;
  const inlineContentBox = measurementStatus === "ready" ? contentBox : null;
  const inlineWidth = inlineContentBox?.width ?? width;
  const inlineHeight = inlineContentBox?.height ?? height;
  const inlineGeometry = {
    aspectRatio: `${inlineWidth} / ${inlineHeight}`,
    maxWidth: `${30 * inlineWidth / inlineHeight}rem`
  };
  const imageStyle = viewMode === "fit" ? {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: "100%",
    maxWidth: `${Math.max(16, activeRatio * 78)}dvh`
  } : {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: `${zoom * 100}%`,
    maxWidth: "none"
  };
  const zoomLabel = viewMode === "fit" ? frameMode === "content" ? "Fit content" : "Full page" : `${Math.round(zoom * 100)}%`;
  return <figure className="latex-preview">
      <button type="button" className="latex-preview__trigger" onClick={openViewer} aria-haspopup="dialog" aria-label={`Open zoomable preview: ${alt}`}>
        <span className="latex-preview__page" style={inlineGeometry}>
          {measurementStatus === "loading" ? <span className="latex-preview__loading" role="status">Preparing compiled output…</span> : renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: inlineContentBox,
    loading: "lazy"
  })}
        </span>
        <span className="latex-preview__trigger-label" aria-hidden="true">
          <span className="latex-preview__trigger-icon">⌕</span>
          Open viewer
        </span>
      </button>
      <figcaption className="latex-preview__caption">
        <span>
          {caption}
          {measurementStatus === "error" && <span className="latex-preview__status" role="status"> Content fit is unavailable; the complete vector page is shown.</span>}
        </span>
        <a href={src} target="_blank" rel="noreferrer" className="latex-preview__source-link">Open SVG</a>
      </figcaption>

      {isOpen && <div className="latex-preview__backdrop" onMouseDown={event => {
    if (event.target === event.currentTarget) closeViewer();
  }}>
          <section ref={dialogRef} className="latex-preview__dialog" role="dialog" aria-modal="true" aria-label={`Rendered LaTeX viewer: ${alt}`}>
            <header className="latex-preview__toolbar">
              <div className="latex-preview__identity">
                <span className="latex-preview__eyebrow">Compiled LaTeX</span>
                <span className="latex-preview__filename">{alt}</span>
              </div>
              <div className="latex-preview__controls" aria-label="Preview controls">
                <button type="button" className={frameMode === "content" && viewMode === "fit" ? "is-active" : undefined} disabled={!contentBox} onClick={() => {
    setFrameMode("content");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Fit content
                </button>
                <button type="button" className={frameMode === "page" && viewMode === "fit" ? "is-active" : undefined} onClick={() => {
    setFrameMode("page");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Full page
                </button>
                <span className="latex-preview__zoom-group">
                  <button type="button" onClick={zoomOut} disabled={viewMode === "fit" || zoom <= minZoom} aria-label="Zoom out">−</button>
                  <output aria-live="polite" aria-label="Current zoom">{zoomLabel}</output>
                  <button type="button" onClick={zoomIn} disabled={viewMode !== "fit" && zoom >= maxZoom} aria-label="Zoom in">+</button>
                </span>
                <a href={src} target="_blank" rel="noreferrer">Open SVG</a>
                <button ref={closeButtonRef} type="button" className="latex-preview__close" onClick={closeViewer} aria-label="Close rendered LaTeX viewer">
                  Close
                </button>
              </div>
            </header>
            <div ref={viewportRef} className="latex-preview__viewport" data-view-mode={viewMode} onPointerDown={startDrag} onPointerMove={continueDrag} onPointerUp={stopDrag} onPointerCancel={stopDrag}>
              <span className="latex-preview__dialog-page" style={imageStyle}>
                {renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: activeContentBox
  })}
              </span>
            </div>
            <footer className="latex-preview__viewer-note">
              Compiler-generated vector output · Use +/− to zoom · Drag to pan · Esc to close
            </footer>
          </section>
        </div>}
    </figure>;
};

This guide covers the broader computer-science notation stack in LaTeX: algorithms, graph notation, asymptotic complexity, and related mathematical symbols.

<Info>
  **Looking for pseudocode?** Use the focused [LaTeX pseudocode guide](/learn/latex/specialized-notation/pseudocode) for `algorithm`, `algorithmicx`, and `algpseudocode` examples.
</Info>

## Essential Algorithm Packages

<LatexSource filename="example.tex" source={"\\usepackage{algorithm}      % Algorithm environment\n\\usepackage{algorithmicx}   % Extended algorithmic commands\n\\usepackage{algpseudocode}  % Pseudocode style\n\\usepackage{listings}       % Code listings\n\\usepackage{clrscode3e}     % CLRS book style\n\\usepackage{complexity}     % Complexity classes\n\\usepackage{amsmath}        % Mathematical notation"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
  </Info>
</RenderedOutput>

## Basic Pseudocode

### Simple Algorithm Structure

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Binary Search}\n\\begin{algorithmic}[1]\n\\Procedure{BinarySearch}{$A, n, x$}\n    \\State $\\textit{left} \\gets 1$\n    \\State $\\textit{right} \\gets n$\n    \\While{$\\textit{left} \\leq \\textit{right}$}\n        \\State $\\textit{mid} \\gets \\lfloor (\\textit{left} + \\textit{right})/2 \\rfloor$\n        \\If{$A[\\textit{mid}] = x$}\n            \\State \\textbf{return} $\\textit{mid}$\n        \\ElsIf{$A[\\textit{mid}] < x$}\n            \\State $\\textit{left} \\gets \\textit{mid} + 1$\n        \\Else\n            \\State $\\textit{right} \\gets \\textit{mid} - 1$\n        \\EndIf\n    \\EndWhile\n    \\State \\textbf{return} $\\textit{null}$\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Rendered output" ctaHref="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=rendered_output&utm_campaign=docs_open_app&utm_content=learn_latex_specialized_notation_algorithms">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-02/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

### Control Structures

<LatexSource filename="example.tex" source={"\\begin{algorithmic}[1]\n\\State $x \\gets 0$\n\n\\If{condition}\n    \\State statement\n\\ElsIf{other condition}\n    \\State other statement\n\\Else\n    \\State default statement\n\\EndIf\n\n\\While{condition}\n    \\State loop body\n\\EndWhile\n\n\\For{$i = 1$ \\textbf{to} $n$}\n    \\State loop body\n\\EndFor\n\n\\For{\\textbf{each} $item$ \\textbf{in} $collection$}\n    \\State process item\n\\EndFor\n\n\\Repeat\n    \\State loop body\n\\Until{condition}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<Card title="Expected output" icon="eye">
  The algorithmicx package produces formatted pseudocode with proper indentation:

  **`\State`** produces a simple statement line

  **`\If{condition}`** produces: **if** *condition* **then**

  **`\For{$i = 1$ \textbf{to} $n$}`** produces: **for** $i = 1$ **to** $n$ **do**
</Card>

## Sorting Algorithms

### Merge Sort

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Merge Sort}\n\\begin{algorithmic}[1]\n\\Procedure{MergeSort}{$A, p, r$}\n    \\If{$p < r$}\n        \\State $q \\gets \\lfloor (p + r)/2 \\rfloor$\n        \\State \\Call{MergeSort}{$A, p, q$}\n        \\State \\Call{MergeSort}{$A, q+1, r$}\n        \\State \\Call{Merge}{$A, p, q, r$}\n    \\EndIf\n\\EndProcedure\n\n\\Procedure{Merge}{$A, p, q, r$}\n    \\State $n_1 \\gets q - p + 1$\n    \\State $n_2 \\gets r - q$\n    \\State Create arrays $L[1..n_1+1]$ and $R[1..n_2+1]$\n    \\For{$i = 1$ \\textbf{to} $n_1$}\n        \\State $L[i] \\gets A[p + i - 1]$\n    \\EndFor\n    \\For{$j = 1$ \\textbf{to} $n_2$}\n        \\State $R[j] \\gets A[q + j]$\n    \\EndFor\n    \\State $L[n_1 + 1] \\gets \\infty$\n    \\State $R[n_2 + 1] \\gets \\infty$\n    \\State $i \\gets 1$, $j \\gets 1$\n    \\For{$k = p$ \\textbf{to} $r$}\n        \\If{$L[i] \\leq R[j]$}\n            \\State $A[k] \\gets L[i]$\n            \\State $i \\gets i + 1$\n        \\Else\n            \\State $A[k] \\gets R[j]$\n            \\State $j \\gets j + 1$\n        \\EndIf\n    \\EndFor\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-04/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Graph Algorithms

### Depth-First Search

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Depth-First Search}\n\\begin{algorithmic}[1]\n\\Procedure{DFS}{$G$}\n    \\For{\\textbf{each} vertex $u \\in V[G]$}\n        \\State $color[u] \\gets \\text{WHITE}$\n        \\State $\\pi[u] \\gets \\text{NIL}$\n    \\EndFor\n    \\State $time \\gets 0$\n    \\For{\\textbf{each} vertex $u \\in V[G]$}\n        \\If{$color[u] = \\text{WHITE}$}\n            \\State \\Call{DFS-Visit}{$u$}\n        \\EndIf\n    \\EndFor\n\\EndProcedure\n\n\\Procedure{DFS-Visit}{$u$}\n    \\State $color[u] \\gets \\text{GRAY}$\n    \\State $time \\gets time + 1$\n    \\State $d[u] \\gets time$\n    \\For{\\textbf{each} $v \\in Adj[u]$}\n        \\If{$color[v] = \\text{WHITE}$}\n            \\State $\\pi[v] \\gets u$\n            \\State \\Call{DFS-Visit}{$v$}\n        \\EndIf\n    \\EndFor\n    \\State $color[u] \\gets \\text{BLACK}$\n    \\State $time \\gets time + 1$\n    \\State $f[u] \\gets time$\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-05/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

### Dijkstra's Algorithm

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Dijkstra's Shortest Path}\n\\begin{algorithmic}[1]\n\\Procedure{Dijkstra}{$G, w, s$}\n    \\State \\Call{Initialize-Single-Source}{$G, s$}\n    \\State $S \\gets \\emptyset$\n    \\State $Q \\gets V[G]$\n    \\While{$Q \\neq \\emptyset$}\n        \\State $u \\gets \\Call{Extract-Min}{Q}$\n        \\State $S \\gets S \\cup \\{u\\}$\n        \\For{\\textbf{each} vertex $v \\in Adj[u]$}\n            \\State \\Call{Relax}{$u, v, w$}\n        \\EndFor\n    \\EndWhile\n\\EndProcedure\n\n\\Procedure{Relax}{$u, v, w$}\n    \\If{$d[v] > d[u] + w(u,v)$}\n        \\State $d[v] \\gets d[u] + w(u,v)$\n        \\State $\\pi[v] \\gets u$\n    \\EndIf\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-06/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Complexity Analysis

### Big O Notation

<LatexSource filename="example.tex" source={"% Time complexities\n$O(1)$ \\quad\\text{constant time}\n$O(\\log n)$ \\quad\\text{logarithmic time}\n$O(n)$ \\quad\\text{linear time}\n$O(n \\log n)$ \\quad\\text{linearithmic time}\n$O(n^2)$ \\quad\\text{quadratic time}\n$O(n^3)$ \\quad\\text{cubic time}\n$O(2^n)$ \\quad\\text{exponential time}\n$O(n!)$ \\quad\\text{factorial time}\n\n% Space complexities\n$O(1)$ \\quad\\text{constant space}\n$O(n)$ \\quad\\text{linear space}\n$O(n^2)$ \\quad\\text{quadratic space}\n\n% Asymptotic notation\n$f(n) = O(g(n))$ \\quad\\text{upper bound}\n$f(n) = \\Omega(g(n))$ \\quad\\text{lower bound}\n$f(n) = \\Theta(g(n))$ \\quad\\text{tight bound}\n$f(n) = o(g(n))$ \\quad\\text{strict upper bound}\n$f(n) = \\omega(g(n))$ \\quad\\text{strict lower bound}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-07/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

### Complexity Classes

<LatexSource filename="example.tex" source={"% Using complexity package\n\\P \\quad\\text{Polynomial time}\n\\NP \\quad\\text{Nondeterministic polynomial time}\n\\coNP \\quad\\text{Co-NP}\n\\PSPACE \\quad\\text{Polynomial space}\n\\EXPTIME \\quad\\text{Exponential time}\n\\NEXPTIME \\quad\\text{Nondeterministic exponential time}\n\n% Reductions\n$A \\leq_p B$ \\quad\\text{polynomial-time reduction}\n$A \\leq_m B$ \\quad\\text{many-one reduction}\n\n% Completeness\n$L$ is $\\NP$-complete if:\n\\begin{enumerate}\n    \\item $L \\in \\NP$\n    \\item For every $L' \\in \\NP$, $L' \\leq_p L$\n\\end{enumerate}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Data Structures

### Binary Search Tree Operations

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Binary Search Tree Insert}\n\\begin{algorithmic}[1]\n\\Procedure{Tree-Insert}{$T, z$}\n    \\State $y \\gets \\text{NIL}$\n    \\State $x \\gets root[T]$\n    \\While{$x \\neq \\text{NIL}$}\n        \\State $y \\gets x$\n        \\If{$key[z] < key[x]$}\n            \\State $x \\gets left[x]$\n        \\Else\n            \\State $x \\gets right[x]$\n        \\EndIf\n    \\EndWhile\n    \\State $p[z] \\gets y$\n    \\If{$y = \\text{NIL}$}\n        \\State $root[T] \\gets z$\n    \\ElsIf{$key[z] < key[y]$}\n        \\State $left[y] \\gets z$\n    \\Else\n        \\State $right[y] \\gets z$\n    \\EndIf\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-09/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

### Hash Table Operations

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Hash Table with Chaining}\n\\begin{algorithmic}[1]\n\\Procedure{Chained-Hash-Insert}{$T, x$}\n    \\State Insert $x$ at head of list $T[h(key[x])]$\n\\EndProcedure\n\n\\Procedure{Chained-Hash-Search}{$T, k$}\n    \\State Search for element with key $k$ in list $T[h(k)]$\n\\EndProcedure\n\n\\Procedure{Chained-Hash-Delete}{$T, x$}\n    \\State Delete $x$ from list $T[h(key[x])]$\n\\EndProcedure\n\n\\Function{Hash-Function}{$k, m$}\n    \\State \\textbf{return} $k \\bmod m$\n\\EndFunction"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Dynamic Programming

### Longest Common Subsequence

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Longest Common Subsequence}\n\\begin{algorithmic}[1]\n\\Procedure{LCS-Length}{$X, Y$}\n    \\State $m \\gets length[X]$\n    \\State $n \\gets length[Y]$\n    \\For{$i = 1$ \\textbf{to} $m$}\n        \\State $c[i,0] \\gets 0$\n    \\EndFor\n    \\For{$j = 0$ \\textbf{to} $n$}\n        \\State $c[0,j] \\gets 0$\n    \\EndFor\n    \\For{$i = 1$ \\textbf{to} $m$}\n        \\For{$j = 1$ \\textbf{to} $n$}\n            \\If{$x_i = y_j$}\n                \\State $c[i,j] \\gets c[i-1,j-1] + 1$\n                \\State $b[i,j] \\gets$ \"↖\"\n            \\ElsIf{$c[i-1,j] \\geq c[i,j-1]$}\n                \\State $c[i,j] \\gets c[i-1,j]$\n                \\State $b[i,j] \\gets$ \"↑\"\n            \\Else\n                \\State $c[i,j] \\gets c[i,j-1]$\n                \\State $b[i,j] \\gets$ \"←\"\n            \\EndIf\n        \\EndFor\n    \\EndFor\n    \\State \\textbf{return} $c$ and $b$\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Mathematical Algorithms

### Euclidean Algorithm

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Euclidean Algorithm}\n\\begin{algorithmic}[1]\n\\Function{GCD}{$a, b$}\n    \\While{$b \\neq 0$}\n        \\State $temp \\gets b$\n        \\State $b \\gets a \\bmod b$\n        \\State $a \\gets temp$\n    \\EndWhile\n    \\State \\textbf{return} $a$\n\\EndFunction\n\n\\Function{Extended-GCD}{$a, b$}\n    \\If{$b = 0$}\n        \\State \\textbf{return} $(a, 1, 0)$\n    \\Else\n        \\State $(d, x', y') \\gets \\Call{Extended-GCD}{b, a \\bmod b}$\n        \\State $x \\gets y'$\n        \\State $y \\gets x' - \\lfloor a/b \\rfloor \\cdot y'$\n        \\State \\textbf{return} $(d, x, y)$\n    \\EndIf\n\\EndFunction\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-12/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Machine Learning Algorithms

### Gradient Descent

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Gradient Descent}\n\\begin{algorithmic}[1]\n\\Procedure{Gradient-Descent}{$f, \\nabla f, \\alpha, \\epsilon$}\n    \\State Initialize $\\mathbf{x}_0$\n    \\State $k \\gets 0$\n    \\Repeat\n        \\State $\\mathbf{g}_k \\gets \\nabla f(\\mathbf{x}_k)$\n        \\State $\\mathbf{x}_{k+1} \\gets \\mathbf{x}_k - \\alpha \\mathbf{g}_k$\n        \\State $k \\gets k + 1$\n    \\Until{$\\|\\mathbf{g}_k\\| < \\epsilon$}\n    \\State \\textbf{return} $\\mathbf{x}_k$\n\\EndProcedure\n\n\\Function{Learning-Rate-Schedule}{$k$}\n    \\State \\textbf{return} $\\frac{\\alpha_0}{1 + \\beta k}$\n\\EndFunction\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-13/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Parallel Algorithms

### Parallel Merge Sort

<LatexSource filename="example.tex" source={"\\begin{algorithm}\n\\caption{Parallel Merge Sort}\n\\begin{algorithmic}[1]\n\\Procedure{P-Merge-Sort}{$A, p, r$}\n    \\If{$p < r$}\n        \\State $q \\gets \\lfloor (p + r)/2 \\rfloor$\n        \\State \\textbf{spawn} \\Call{P-Merge-Sort}{$A, p, q$}\n        \\State \\Call{P-Merge-Sort}{$A, q+1, r$}\n        \\State \\textbf{sync}\n        \\State \\Call{P-Merge}{$A, p, q, r$}\n    \\EndIf\n\\EndProcedure\n\n\\Procedure{P-Merge}{$A, p, q, r$}\n    \\State $n_1 \\gets q - p + 1$\n    \\State $n_2 \\gets r - q$\n    \\If{$n_1 < n_2$}\n        \\State Exchange $p \\leftrightarrow q+1$ and $n_1 \\leftrightarrow n_2$\n    \\EndIf\n    \\If{$n_1 = 0$}\n        \\State \\textbf{return}\n    \\Else\n        \\State $q' \\gets \\lfloor (p + q)/2 \\rfloor$\n        \\State $r' \\gets \\Call{Binary-Search}{A[q'], A, q+1, r}$\n        \\State $s \\gets p + (q' - p) + (r' - (q+1))$\n        \\State $A'[s] \\gets A[q']$\n        \\State \\textbf{spawn} \\Call{P-Merge}{A, p, q'-1, r'-1}\n        \\State \\Call{P-Merge}{A, q'+1, q, r'+1}\n        \\State \\textbf{sync}\n    \\EndIf\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-14/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Recurrence Relations

### Solving Recurrences

<LatexSource filename="example.tex" source={"% Master Theorem\n\\textbf{Master Theorem:} Let $T(n) = aT(n/b) + f(n)$ where $a \\geq 1$ and $b > 1$.\n\n\\textbf{Case 1:} If $f(n) = O(n^{\\log_b a - \\epsilon})$ for some $\\epsilon > 0$,\nthen $T(n) = \\Theta(n^{\\log_b a})$.\n\n\\textbf{Case 2:} If $f(n) = \\Theta(n^{\\log_b a})$,\nthen $T(n) = \\Theta(n^{\\log_b a} \\log n)$.\n\n\\textbf{Case 3:} If $f(n) = \\Omega(n^{\\log_b a + \\epsilon})$ for some $\\epsilon > 0$,\nand $af(n/b) \\leq cf(n)$ for some $c < 1$ and sufficiently large $n$,\nthen $T(n) = \\Theta(f(n))$.\n\n% Examples\n$T(n) = 2T(n/2) + n$ \\quad $\\Rightarrow$ \\quad $T(n) = \\Theta(n \\log n)$\n$T(n) = 3T(n/4) + n^2$ \\quad $\\Rightarrow$ \\quad $T(n) = \\Theta(n^2)$\n$T(n) = T(n-1) + 1$ \\quad $\\Rightarrow$ \\quad $T(n) = \\Theta(n)$"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-15/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Algorithm Analysis Proofs

### Correctness Proofs

<LatexSource filename="example.tex" source={"% Loop invariant\n\\textbf{Loop Invariant for Insertion Sort:}\n\nAt the start of each iteration of the \\textbf{for} loop of lines 1-8,\nthe subarray $A[1..j-1]$ consists of the elements originally in\n$A[1..j-1]$, but in sorted order.\n\n\\textbf{Initialization:} Prior to the first iteration, when $j = 2$,\nthe subarray $A[1..j-1] = A[1..1] = \\{A[1]\\}$ is trivially sorted.\n\n\\textbf{Maintenance:} Assume the invariant holds at the beginning of an\niteration. The loop body moves $A[j-1], A[j-2], \\ldots$ one position\nto the right until it finds the proper position for $A[j]$.\n\n\\textbf{Termination:} When the loop terminates, $j = n + 1$. The\nsubarray $A[1..n]$ consists of the original elements in sorted order.\n\n% Asymptotic proof\n\\textbf{Theorem:} For any function $f(n)$ and $g(n)$,\n$f(n) = O(g(n))$ if and only if there exist positive constants\n$c$ and $n_0$ such that $0 \\leq f(n) \\leq c \\cdot g(n)$\nfor all $n \\geq n_0$."} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-specialized-notation-algorithms-16/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Best Practices

<CardGroup cols={2}>
  <Card title="Clear Variable Names" icon="tag" color="#FF6037">
    Use descriptive variable names and consistent notation
  </Card>

  <Card title="Proper Indentation" icon="indent" color="#FF6037">
    Use consistent indentation to show algorithm structure
  </Card>

  <Card title="Complexity Analysis" icon="chart-line" color="#FF6037">
    Always include time and space complexity analysis
  </Card>

  <Card title="Invariants and Proofs" icon="shield-check" color="#FF6037">
    Document loop invariants and correctness proofs
  </Card>
</CardGroup>

## Common Algorithm Notation

| Notation | Meaning           |
| :------- | :---------------- |
| **←**    | Assignment        |
| **⊕**    | XOR operation     |
| **⊕**    | Addition in GF(2) |
| **∀**    | For all           |
| **∃**    | There exists      |
| **∈**    | Element of        |
| **⊆**    | Subset of         |
| **∪**    | Union             |
| **∩**    | Intersection      |
| **∅**    | Empty set         |

## Troubleshooting

<Warning>
  **Common issues**:

  * Missing algorithm package: Install `algorithm` and `algorithmicx`
  * Line numbering: Use `[1]` option in algorithmic environment
  * Indentation problems: Check matching `\If`/`\EndIf` pairs
  * Symbol conflicts: Some symbols may conflict with math mode
</Warning>

## Further Reading

<CardGroup cols={2}>
  <Card title="Mathematics Notation" icon="square-root-variable" href="/learn/latex/mathematics/mathematical-expressions" color="#FF6037">
    Mathematical expressions and notation
  </Card>

  <Card title="Creating Tables" icon="table" href="/learn/latex/tables/creating-tables" color="#FF6037">
    Complexity comparison tables
  </Card>

  <Card title="Code Listings" icon="code" href="/learn/latex/formatting/code-listings-minted" color="#FF6037">
    Including actual code implementations
  </Card>

  <Card title="Physics Notation" icon="atom" href="/learn/latex/specialized-notation/physics" color="#FF6037">
    Scientific computing applications
  </Card>
</CardGroup>
