BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Tokenization and NLP37 of 38 in topic

835. Find the longest common substring of two texts

MediumTokenization and NLP Pro

To spot copied passages between a training document and a benchmark item, you look for the longest stretch of characters they share exactly.

Write longest_common_substring(a, b) that returns the longest string that appears as a contiguous substring of both a and b. If several have the same maximum length, return the one that ends earliest in a. If none exist, return "".

Functiondef longest_common_substring(a, b)

Example 1

Input: longest_common_substring("abcdef", "zcdemf")

Output: "cde"

Example 2

Input: longest_common_substring("abc", "xyz")

Output: ""

Constraints

  • len(a), len(b) <= 2,000
Hint 1

Match extends the diagonal by 1.

Hint 2

Mismatch resets to 0.

Hint 3

Remember the end index, not just the length.

Common mistakes
  • Using the subsequence recurrence and returning non-contiguous text.
  • Slicing with off by one indices when rebuilding the answer.
  • Allocating a full 2D table for very long strings.
Understand the idea

Longest common substring and longest common subsequence look alike but differ in one rule. For the subsequence, a mismatch takes the max of the left and upper cells; for the substring, a mismatch drops to 0 because the shared run is broken. With "abcdef" and "zcdemf" the run c, d, e builds L values 1, 2, 3, then f after m restarts at 1.

Topics
Tokenization and NLP
Similar questions
  • Do one merge step of a BPE tokenizerMedium
  • Compute Levenshtein edit distanceMedium
  • Tokenize words with WordPiece greedy longest matchMedium
  • Build a vocabulary with special tokens, a minimum frequency and UNKMedium
All Tokenization and NLP problems
Report
835 / 903
Python 3solution.pyPython idle
1
2
3
4
def longest_common_substring(a, b):
# return the longest shared contiguous substring
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS