Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Longest Common Substring Implementation in Rust

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Longest Common Substring runs in O(n*m) time and O(n*m) space, in Rust as in every other language.
  • ✓std has no LCSubstring. What it gives you is the machinery to do it safely on UTF-8: str::as_bytes for a &[u8] view, str::is_char_boundary(usize), str::get(range) -> Option<&str> for a non-panicking slice, and char_indices() when you need scalar values paired with their byte offsets.
  • ✓Take &str, never &String, and return &'a str borrowed from the first argument so the caller pays no allocation - the lifetime is the API.
  • ✓The Rust trap: Run the DP over as_bytes() - which is the fast, obvious choice - and the match boundaries are byte offsets that need not sit on a character boundary.
  • ✓Two Vec<u32> rows with indexed access keep a bounds check per read; writing the inner loop over bb.iter().enumerate() and zipping the previous row lets LLVM drop most of them.

What Longest Common Substring actually is

The longest run of CONSECUTIVE elements that appears in both sequences - not to be confused with longest common subsequence, which may skip elements. The textbook solution is a table where dp[i][j] holds the length of the match ending exactly at a[i-1] and b[j-1]: equal elements extend the diagonal, unequal elements reset to zero, and you track the running maximum. Engineers reach for it in diff tools looking for anchor blocks, plagiarism and duplicate-content checks, read overlap in bioinformatics, log deduplication, and fuzzy matching of product titles. Suffix automata or suffix arrays get you to O(n+m) when the inputs are large enough to care.

Longest Common Substring in Rust: what you actually reach for

std has no LCSubstring. What it gives you is the machinery to do it safely on UTF-8: str::as_bytes for a &[u8] view, str::is_char_boundary(usize), str::get(range) -> Option<&str> for a non-panicking slice, and char_indices() when you need scalar values paired with their byte offsets. Vec<u32> is the right table row. If the inputs get large enough that O(n*m) hurts, the ecosystem answer is a suffix automaton or a suffix array crate rather than anything in std - rust-bio ships suffix array structures under bio::data_structures::suffix_array.

Rust implementation

Take &str, never &String, and return &'a str borrowed from the first argument so the caller pays no allocation - the lifetime is the API. Reviewers reject a String return that copies the match, reject unsafe get_unchecked without a benchmark in the PR, and prefer iterator forms (iter().enumerate(), zip) over manual indexing because they read better and vectorise at least as well. u32 counters rather than usize for the table, and #[must_use] on a pure function that returns a slice.
rust
/// Returns a longest common substring of `a` and `b`, borrowed from `a`.
pub fn longest_common_substring<'a>(a: &'a str, b: &str) -> &'a str {
    let (ab, bb) = (a.as_bytes(), b.as_bytes());
    let mut prev = vec![0u32; bb.len() + 1];
    let mut cur = vec![0u32; bb.len() + 1];
    let (mut best, mut end) = (0usize, 0usize);

    for i in 1..=ab.len() {
        cur[0] = 0;
        for j in 1..=bb.len() {
            cur[j] = if ab[i - 1] == bb[j - 1] { prev[j - 1] + 1 } else { 0 };
            if cur[j] as usize > best {
                best = cur[j] as usize;
                end = i;
            }
        }
        std::mem::swap(&mut prev, &mut cur);
    }

    // The byte-level match may land mid-scalar; pull both ends onto boundaries.
    let mut start = end - best;
    let mut stop = end;
    while start < stop && !a.is_char_boundary(start) {
        start += 1;
    }
    while stop > start && !a.is_char_boundary(stop) {
        stop -= 1;
    }
    &a[start..stop]
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Rust-specific trap

Run the DP over as_bytes() - which is the fast, obvious choice - and the match boundaries are byte offsets that need not sit on a character boundary. UTF-8 continuation bytes in the range 0x80..=0xBF are shared across completely different scalars, so two unrelated characters can agree on a trailing byte and the winning run straddles a boundary. Then &a[start..end] panics at runtime with 'byte index is not a char boundary' - not a compile error, and not a wrong answer like Go gives you, but a hard panic in production. Shrink both ends with is_char_boundary, or use str::get and handle None.

Performance in Rust, beyond the O(n*m)

Two Vec<u32> rows with indexed access keep a bounds check per read; writing the inner loop over bb.iter().enumerate() and zipping the previous row lets LLVM drop most of them. u32 instead of usize halves the working set - 400 KB rather than 800 KB for a 100k-column row - which is the difference between two live rows fitting in a 1-2 MB L2 and spilling to L3 on every sweep. Vec<Vec<u32>> adds a pointer chase per row and scatters the table across the allocator. The largest single factor is the profile: debug builds keep every overflow and bounds check and commonly run 10-30x slower here, so never quote a timing from cargo run without --release. The asymptotic cost is the same in every language, O(n*m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Longest Common Substring between languages.

Real-World Applications

Longest Common Substring applies wherever its problem shape appears in your own code. In Rust, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Longest Common Substring helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Longest Common Substring appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Longest Common Substring over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Longest Common Substring to build pattern recognition. In Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

Frequently Asked Questions

Which Rust type or library should I use for Longest Common Substring?

std has no LCSubstring. What it gives you is the machinery to do it safely on UTF-8: str::as_bytes for a &[u8] view, str::is_char_boundary(usize), str::get(range) -> Option<&str> for a non-panicking slice, and char_indices() when you need scalar values paired with their byte offsets. Vec<u32> is the right table row. If the inputs get large enough that O(n*m) hurts, the ecosystem answer is a suffix automaton or a suffix array crate rather than anything in std - rust-bio ships suffix array structures under bio::data_structures::suffix_array.

What is the most common Rust mistake when implementing Longest Common Substring?

Run the DP over as_bytes() - which is the fast, obvious choice - and the match boundaries are byte offsets that need not sit on a character boundary. UTF-8 continuation bytes in the range 0x80..=0xBF are shared across completely different scalars, so two unrelated characters can agree on a trailing byte and the winning run straddles a boundary. Then &a[start..end] panics at runtime with 'byte index is not a char boundary' - not a compile error, and not a wrong answer like Go gives you, but a hard panic in production. Shrink both ends with is_char_boundary, or use str::get and handle None.

How does Longest Common Substring actually perform in Rust?

Two Vec<u32> rows with indexed access keep a bounds check per read; writing the inner loop over bb.iter().enumerate() and zipping the previous row lets LLVM drop most of them. u32 instead of usize halves the working set - 400 KB rather than 800 KB for a 100k-column row - which is the difference between two live rows fitting in a 1-2 MB L2 and spilling to L3 on every sweep. Vec<Vec<u32>> adds a pointer chase per row and scatters the table across the allocator. The largest single factor is the profile: debug builds keep every overflow and bounds check and commonly run 10-30x slower here, so never quote a timing from cargo run without --release. Time complexity is O(n*m) and space is O(n*m).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.