> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/ecs122a-algorithm-design-lecture-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/ecs122a-algorithm-design-lecture-notes/string-algorithms/suffix-trees/applications/longest-common-substring.md).

# Longest Common Substring

**Problem**: Given two strings ‘X’ and ‘Y’, return the longest common substring.

```
Input : X = "abcdxyz", y = "xyzabcd"
Output : "abcd"

Input : X = "zxabcdezy", y = "yzabcdezx"
Output : "abcdez"
```

**Solution**

Assume strings s1 = "abab" and s2 = "baba"

```
S1 + S2 = a b a b $ b a b a #
Index   = 1 2 3 4 5 6 7 8 9 0
```

First build a generalized suffix tree that includes both strings. For this, you should add a unique delimiter to each string before making the generalized tree.

![](/files/-LoJI4wj_Bvjjbhhn_qE)

Then search for the deepest *internal* node in the tree that contains both delimiters within its subtree. The path label along this tree will be LCS. In our case, our tree returned two valid solutions: 'aba' or 'bab'.

![](/files/-LoJI4wlmYCJs3OTKr3g)

**Why this works**

A internal node in a suffix tree carries that property that it shares a common suffix from its parent. Therefore the deeper we move down the tree, the longer the path label gets are is shared by at least on other suffix. Searching for both delimiters in the tree is a way of confirm that both strings have visited the internal node, and are therefore both guaranteed to share a common substring.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://maksimdan.gitbook.io/ecs122a-algorithm-design-lecture-notes/string-algorithms/suffix-trees/applications/longest-common-substring.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
