Longest Common Substring Implementation in Rust
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
Longest Common Substring in Rust: what you actually reach for
Rust implementation
/// 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 FreeThe Rust-specific trap
Performance in Rust, beyond the O(n*m)
Real-World Applications
Interview Tips & Practice
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).
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 trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.