Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Longest Common Substring

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Longest Common Substring. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Given two strings s1 and s2, return the longest common substring shared by both strings. A substring must be contiguous in each string. If multiple answers have the same maximum length, return the one that appears first in s1.

Formal Specification

Write a function that takes two strings and returns a string.

  • Input: s1, s2, two lowercase or mixed-case ASCII strings
  • Output: the longest common substring between s1 and s2
  • If no common substring exists, return an empty string

Constraints

  • 1 <= len(s1), len(s2) <= 2000
  • Strings may contain letters, digits, spaces, or punctuation
  • Return the earliest occurrence in s1 if multiple substrings share the maximum length

Function Signature

def longest_common_substring(s1, s2):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output