Longest Common Substring Implementation in Swift
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 Swift as in every other language.
- ✓No LCSubstring in the standard library. String is a Collection of Character - extended grapheme clusters - with an opaque String.Index and no integer subscript, so the working shape is Array(s) for O(1) access, or an explicit view: s.unicodeScalars, s.utf8, s.utf16.
- ✓Reviewers reject any index arithmetic on String itself and insist you snapshot into an Array or a named view before the loop, then convert back once at the end.
- ✓The Swift trap: Character comparison uses Unicode canonical equivalence, so precomposed U+00E9 == e + U+0301 - which is usually what you want, and is why the match length in Characters cannot be converted to a byte or scalar offset by arithmetic: three matching Characters may span three UTF-8 bytes in one string and six in the other.
- ✓Array(s) is one O(n) allocation of Character values, far larger than the underlying UTF-8 bytes; comparing [UInt8] from s.utf8 is dramatically tighter but hands the boundary problem back to you.
What Longest Common Substring actually is
Longest Common Substring in Swift: what you actually reach for
Swift implementation
import Foundation
/// Returns a longest common substring of `a` and `b` as a Substring of `a`.
func longestCommonSubstring(_ a: String, _ b: String) -> Substring {
let ac = Array(a) // [Character]: String has no integer subscript
let bc = Array(b)
guard !ac.isEmpty, !bc.isEmpty else { return a[a.startIndex..<a.startIndex] }
var prev = [Int](repeating: 0, count: bc.count + 1)
var cur = prev
var best = 0
var end = 0
for i in 1...ac.count {
for j in 1...bc.count {
cur[j] = ac[i - 1] == bc[j - 1] ? prev[j - 1] + 1 : 0
if cur[j] > best {
best = cur[j]
end = i
}
}
swap(&prev, &cur)
}
// Character offsets are valid for `a` only, and only via index(_:offsetBy:).
let lo = a.index(a.startIndex, offsetBy: end - best)
let hi = a.index(lo, offsetBy: best)
return a[lo..<hi]
}
print(longestCommonSubstring("abcdxyz", "xyzabcd")) // abcd
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 Swift-specific trap
Performance in Swift, beyond the O(n*m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Longest Common Substring?
No LCSubstring in the standard library. String is a Collection of Character - extended grapheme clusters - with an opaque String.Index and no integer subscript, so the working shape is Array(s) for O(1) access, or an explicit view: s.unicodeScalars, s.utf8, s.utf16. Substring shares the parent's storage, which makes it the right return type. Foundation adds String.commonPrefix(with:options:), the longest-common-prefix primitive you can max over suffix pairs when you want a short, obviously correct reference implementation to test the DP against.
What is the most common Swift mistake when implementing Longest Common Substring?
Character comparison uses Unicode canonical equivalence, so precomposed U+00E9 == e + U+0301 - which is usually what you want, and is why the match length in Characters cannot be converted to a byte or scalar offset by arithmetic: three matching Characters may span three UTF-8 bytes in one string and six in the other. Never carry an index from one String into another. The performance trap is worse: calling a.index(a.startIndex, offsetBy: i) inside the loop is O(i), quietly turning the documented O(n*m) into O(n squared times m).
How does Longest Common Substring actually perform in Swift?
Array(s) is one O(n) allocation of Character values, far larger than the underlying UTF-8 bytes; comparing [UInt8] from s.utf8 is dramatically tighter but hands the boundary problem back to you. Element access on [Int] involves no ARC traffic, but a Character whose grapheme exceeds the small-form inline capacity is heap backed, so retain/release can appear in the inner loop for emoji-heavy text. withUnsafeBufferPointer removes the per-access bounds check; whole-module optimisation is what lets the comparison inline across files. 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 trialIf you are a student, see what GitHub Copilot offers students for free 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.