惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
有赞技术团队
有赞技术团队
博客园 - 叶小钗
博客园 - Franky
博客园_首页
S
SegmentFault 最新的问题
阮一峰的网络日志
阮一峰的网络日志
博客园 - 司徒正美
罗磊的独立博客
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recent Announcements
Recent Announcements
V
Visual Studio Blog
J
Java Code Geeks
D
Docker
Martin Fowler
Martin Fowler
Blog — PlanetScale
Blog — PlanetScale
腾讯CDC
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
T
Tailwind CSS Blog
The GitHub Blog
The GitHub Blog
Microsoft Azure Blog
Microsoft Azure Blog
美团技术团队
博客园 - 【当耐特】
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Commits to openclaw:main
Recent Commits to openclaw:main
G
Google Developers Blog
S
Schneier on Security
Apple Machine Learning Research
Apple Machine Learning Research
AWS News Blog
AWS News Blog
N
Netflix TechBlog - Medium
量子位
爱范儿
爱范儿
D
Darknet – Hacking Tools, Hacker News & Cyber Security
MyScale Blog
MyScale Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Spread Privacy
Spread Privacy
V
Vulnerabilities – Threatpost
A
Arctic Wolf
C
Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Cloudflare Blog
C
CERT Recently Published Vulnerability Notes
L
LINUX DO - 最新话题
W
WeLiveSecurity
Hacker News: Ask HN
Hacker News: Ask HN

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
DSA Application in Real Life: How Git Diff Works: LCS Intuition, Myers Algorithm, and Real Code Changes
Naimur Rahma · 2026-05-23 · via DEV Community

The Algorithm Hiding Behind git diff

You've run git diff hundreds of times.

Red lines. Green lines. Done.

But have you ever stopped and asked — what algorithm is actually doing that?

It turns out, it's one of the most classic problems in computer science: Longest Common Subsequence. And it's been hiding inside your terminal every single day.

In this article, we'll explore how Git-style diffing works, why LCS is the right mental model, how the actual algorithm Git uses (Myers diff) connects to it, and what tradeoffs real tools make when choosing a diff algorithm.

This is the first article in my series "DSA Application in Real Life" — where I explore how common data structures and algorithms power the tools developers use every day.


The Problem Git Is Solving

Imagine we have an old version of a file:

function add(a, b) {
  return a + b;
}

Enter fullscreen mode Exit fullscreen mode

Then we update it:

function addNumbers(a, b) {
  return a + b;
}

Enter fullscreen mode Exit fullscreen mode

When we run git diff, Git shows:

-function add(a, b) {
+function addNumbers(a, b) {
   return a + b;
 }

Enter fullscreen mode Exit fullscreen mode

This looks obvious to us as humans. Only the function name changed.

But Git does not "understand" JavaScript the way we do. At the diffing level, Git treats the file as a sequence of lines. Its job is to compare two sequences and decide:

  • Which lines stayed the same?
  • Which lines were deleted?
  • Which lines were added?

This is a sequence comparison problem — and that's exactly where LCS comes in.


Why Simple Line-by-Line Comparison Is Not Enough

A beginner might think Git just compares files line by line:

Old line 1 vs New line 1
Old line 2 vs New line 2
Old line 3 vs New line 3

Enter fullscreen mode Exit fullscreen mode

This works only when changes happen at the same position. But real code changes are rarely that simple.

Consider this old file:

login()
validate()
save()
logout()

Enter fullscreen mode Exit fullscreen mode

Now we insert one new line:

login()
checkPermission()
validate()
save()
logout()

Enter fullscreen mode Exit fullscreen mode

A naive line-by-line comparison would produce:

Old: login()      New: login()            same
Old: validate()   New: checkPermission()  different
Old: save()       New: validate()         different
Old: logout()     New: save()             different
Old: (nothing)    New: logout()           added

Enter fullscreen mode Exit fullscreen mode

That makes it look like almost the entire file changed — which is completely wrong. Only one line was added.

A smarter approach doesn't compare by position. It finds what's common between the two files first. That's the LCS idea.


LCS: The Mental Model Behind Diffing

LCS stands for Longest Common Subsequence.

A subsequence means you can pick elements from a sequence while keeping their relative order — but they don't need to be adjacent.

Example:

Old = [A, B, C, D]
New = [A, C, E, D]

Enter fullscreen mode Exit fullscreen mode

The longest common subsequence is [A, C, D] — because A, C, and D appear in both sequences in the same order.

Applied to file diffing, the lines of each file become the sequences:

Old = [login(), validate(), save(), logout()]
New = [login(), checkPermission(), validate(), save(), logout()]

Enter fullscreen mode Exit fullscreen mode

LCS = [login(), validate(), save(), logout()]

Now Git can reason:

  • These lines are common → unchanged
  • checkPermission() is only in the new file → added

Result:

 login()
+checkPermission()
 validate()
 save()
 logout()

Enter fullscreen mode Exit fullscreen mode

That's the core idea.


The Actual LCS Algorithm (with Code)

Here's the classic dynamic programming solution you've likely seen in competitive programming:

def lcs_length(A, B):
    m, n = len(A), len(B)
    # dp[i][j] = LCS length of A[:i] and B[:j]
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if A[i-1] == B[j-1]:
                dp[i][j] = dp[i-1][j-1] + 1
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])

    return dp[m][n]

Enter fullscreen mode Exit fullscreen mode

For sequences A = [A, B, C, D] and B = [A, C, E, D], the DP table looks like:

     ""  A   C   E   D
""  [ 0   0   0   0   0 ]
A   [ 0   1   1   1   1 ]
B   [ 0   1   1   1   1 ]
C   [ 0   1   2   2   2 ]
D   [ 0   1   2   2   3 ]

Enter fullscreen mode Exit fullscreen mode

The answer is dp[4][4] = 3 → LCS length is 3 → [A, C, D].

Time complexity: O(m × n)
Space complexity: O(m × n)

For large files, this gets expensive — which is why Git doesn't use this directly.


How LCS Builds the Diff

Once you know the LCS, building the diff is straightforward:

  • Lines in the LCS → unchanged
  • Lines in old but not in LCS → deleted (prefix with -)
  • Lines in new but not in LCS → added (prefix with +)

Example:

Old = [A, B, C, D]
New = [A, C, E, D]
LCS = [A, C, D]

B is only in Old  → deleted
E is only in New  → added

Enter fullscreen mode Exit fullscreen mode

Diff output:

 A
-B
 C
+E
 D

Enter fullscreen mode Exit fullscreen mode

This is the basic shape of what Git, GitHub pull requests, VS Code comparison, and merge tools show: unchanged lines, deleted lines, and added lines.


Does Git Actually Use Textbook LCS?

Not directly. Git's default algorithm is Myers diff — and it solves a slightly different (but deeply related) problem called the Shortest Edit Script.

What is the minimum number of insertions and deletions needed to transform the old file into the new file?

The connection to LCS is direct:

LCS finds what is common.
Shortest Edit Script finds what changed.

Enter fullscreen mode Exit fullscreen mode

If LCS is long → fewer edits needed.
If LCS is short → more edits needed.

They are two sides of the same coin.

So when we say "Git uses LCS-based diffing," the accurate meaning is:

Git's diffing is based on sequence comparison ideas rooted in LCS, but its default implementation uses Myers' shortest edit script algorithm — which is faster in practice.


How Myers Diff Actually Works (Simplified)

Myers models the diff problem as a graph search.

Imagine a grid where:

  • The X-axis represents lines of the old file
  • The Y-axis represents lines of the new file
  • Moving right = delete a line from the old file
  • Moving down = insert a line from the new file
  • Moving diagonally = lines match (no edit needed)

For Old = [A, B, C, D] and New = [A, C, E, D]:

     A    B    C    D
   ┌────┬────┬────┬────┐
A  │╲   │    │    │    │
   ├────┼────┼────┼────┤
C  │    │    │╲   │    │
   ├────┼────┼────┼────┤
E  │    │    │    │    │
   ├────┼────┼────┼────┤
D  │    │    │    │╲   │
   └────┴────┴────┴────┘

Enter fullscreen mode Exit fullscreen mode

Myers finds the path from (0,0) to (N,M) that uses the most diagonal moves — because diagonals are free (matched lines). That path is the shortest edit script.

Time complexity: O(n × d) where d = number of differences
Space complexity: O(n)

This is much faster than O(m × n) LCS for files that are mostly similar — which is the common case in real codebases.


Diff as an Edit Script

Let's walk through a concrete edit script:

Old file → [A, B, C, D]
New file → [A, C, E, D]

Step 1: Delete B

A, C, D

Enter fullscreen mode Exit fullscreen mode

Step 2: Insert E after C

A, C, E, D

Enter fullscreen mode Exit fullscreen mode

Edit script: Delete B, Insert E — that's just 2 operations.

Git's diff output:

 A
-B
 C
+E
 D

Enter fullscreen mode Exit fullscreen mode

Clean, minimal, exactly right.


Why This Matters in Real Development

When we review code, we're not just looking at text changes — we're trying to understand intent.

A good diff makes that easy:

 function calculateTotal(items) {
-  return items.length;
+  return items.reduce((sum, item) => sum + item.price, 0);
 }

Enter fullscreen mode Exit fullscreen mode

Any reviewer immediately understands: the old code counted items, the new code sums their prices.

A bad diff creates noise and confusion. That's why diff algorithms matter — they're not just about correctness, they're about readability.


The Tradeoff: Shortest Diff vs Most Readable Diff

The "smallest" diff is not always the most readable one — especially in code with repeated patterns:

if (user) {
  return true;
}

if (admin) {
  return true;
}

if (owner) {
  return true;
}

Enter fullscreen mode Exit fullscreen mode

When many lines look similar, a diff algorithm can match the wrong lines. The result is technically correct but hard to read. That's why Git ships multiple algorithms.


Git's Four Diff Algorithms — With a Real Example


git diff --diff-algorithm=myers      # default
git diff --diff-algorithm=minimal
git diff --diff-algorithm=patience
git diff --diff-algorithm=histogram

Enter fullscreen mode Exit fullscreen mode

Here's what each one does and when to use it:

Myers (default)

Fast, generally good results. This is what runs when you just type git diff. Best for everyday use.

Minimal

Tries harder to find the absolute smallest diff. Slower, but useful when patch size matters (e.g., generating patches to send via email).

Patience

Prioritizes human readability. It only matches unique lines first, avoiding false alignments on repeated code. Best for reviewing refactors or moved code blocks.

Histogram

An evolution of Patience that also handles low-frequency lines well. Often produces the most readable output for real codebases. Many developers set this as their global default.

Side-by-side example — Myers vs Patience:

Given this change (a function was refactored):

# Old
def process(data):
    result = []
    for item in data:
        result.append(item * 2)
    return result

# New
def process(data):
    return [item * 2 for item in data]

Enter fullscreen mode Exit fullscreen mode

Myers output might show:

 def process(data):
-    result = []
-    for item in data:
-        result.append(item * 2)
-    return result
+    return [item * 2 for item in data]

Enter fullscreen mode Exit fullscreen mode

Patience output groups the change more cleanly around unique anchors, making it immediately obvious that the body was replaced with a list comprehension — less noise, same information.

To set histogram globally (recommended for most developers):

git config --global diff.algorithm histogram

Enter fullscreen mode Exit fullscreen mode


Algorithm Complexity Summary

Algorithm Rough Idea Best For
Textbook LCS DP O(m × n) time and space Learning the concept
Myers diff Efficient when files are mostly similar Default everyday diffs
Minimal Spends extra work to reduce diff size Smaller patches
Patience Uses unique lines as anchors Refactors / moved blocks
Histogram Extends patience using low-frequency lines Often readable code diffs

Where m = number of lines in the old file and n = number of lines in the new file.


Where the DSA Is Hiding

In competitive programming, LCS is a textbook DP problem. In the real world, the same idea powers:

Git diff
GitHub pull request review
VS Code file comparison
Merge conflict resolution
Google Docs version history
Code review platforms (Gerrit, Phabricator)
Patch generation

Enter fullscreen mode Exit fullscreen mode

The input changes — lines of code, words in a document, DOM nodes in a UI, events in a timeline — but the core question is always the same:

What stayed the same, and what changed?


A Real-World Developer Example

Old code:

function createUser(name, email) {
  const user = { name, email };
  saveUser(user);
  return user;
}

Enter fullscreen mode Exit fullscreen mode

New code:

function createUser(name, email, role) {
  const user = { name, email, role };
  validateUser(user);
  saveUser(user);
  return user;
}

Enter fullscreen mode Exit fullscreen mode

A well-tuned diff shows:

-function createUser(name, email) {
+function createUser(name, email, role) {
-  const user = { name, email };
+  const user = { name, email, role };
+  validateUser(user);
   saveUser(user);
   return user;
 }

Enter fullscreen mode Exit fullscreen mode

Any reviewer immediately understands: a role parameter was added, it's stored on the user object, and validation was introduced before saving. Three changes, instantly clear.

That's the value of a good diff algorithm — it's not just computing differences. It's helping humans understand change.


Why Git Works at the Line Level (Not Character Level)

Git diffs at the line level because source code is naturally line-based. A character-level diff would be more precise:

-const total = price * quantity;
+const total = price * quantity * tax;

Enter fullscreen mode Exit fullscreen mode

vs character diff: * tax was appended.

But character-level diffs get noisy fast for code review. Line-level is the right abstraction for most developer workflows. (You can get word-level diffs with git diff --word-diff when you need them.)

The best algorithm isn't always the most precise one. It's the one that gives the most useful output for the context.


LCS vs Myers: The Mental Model

LCS:    Find the longest part that stayed the same.
Myers:  Find the shortest set of changes to get from old to new.

Enter fullscreen mode Exit fullscreen mode

LCS gives you the intuition.
Myers gives Git an efficient practical algorithm.

If the LCS is long → few changes needed.
If the LCS is short → many changes needed.

They measure the same thing from different directions.


Why This Is a Great Example of DSA in Real Life

Many beginners ask: "Where do we actually use DSA in real projects?"

git diff is one of the best answers — because every developer runs it daily without thinking about it.

When you run git diff, you're using an algorithm.
When you review a pull request on GitHub, you're using an algorithm.
When you resolve merge conflicts, you're relying on algorithms that compare versions of files.

The algorithm is invisible behind a clean developer experience. That's what good engineering looks like — the user sees red and green lines, and behind it is a carefully designed algorithmic solution built on decades of computer science research.

That's the beauty of DSA. Not just for interviews. Inside the tools you use every day.


Practical Commands to Try

# Try different algorithms on any repo
git diff --diff-algorithm=myers
git diff --diff-algorithm=patience
git diff --diff-algorithm=histogram
git diff --diff-algorithm=minimal

# Word-level diff (great for prose or config files)
git diff --word-diff

# Set histogram as your permanent default
git config --global diff.algorithm histogram

Enter fullscreen mode Exit fullscreen mode


Final Thoughts

LCS may look like just another DP problem when you first learn it. But the idea is powerful:

Find what stayed the same so we can understand what changed.

Git uses it to show file changes. Code review tools use it to help developers understand pull requests. Merge tools use it to combine work from different branches. Document editors use it to show version history.

So the next time you run git diff, remember: you're not just seeing red and green lines. You're seeing dynamic programming, graph search, and decades of algorithmic research — all compressed into a two-word command.


References