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

Longest Common Substring Implementation in Swift

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 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

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 Swift: what you actually reach for

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.

Swift implementation

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. Return Substring, not String, so the caller decides when to copy - and document which view you compared, because Character, UnicodeScalar and UTF8 give three different answers. guard for the empty cases rather than clamping ranges, for i in 1...n over stride(from: 1, through: n, by: 1) - and that guard is load-bearing, because 1...0 traps at runtime with 'Range requires lowerBound <= upperBound' rather than iterating zero times - and no force-unwrapped index conversions.
swift
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 Free

The Swift-specific 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. 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).

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

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. 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 Swift, 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 Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

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).

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

If you are a student, see what GitHub Copilot offers students for free 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.