Ctrl K

The Tightest Shared Piece

Medium
You are given two strings left and right of lowercase English letters, indexed from zero. Consider index quadruples (i, j, a, b) with 0 ≤ i ≤ j < len(left) and 0 ≤ a ≤ b < len(right) such that the piece left[i..j] equals the piece right[a..b] (both ends inclusive). Among all such quadruples, find the smallest value of j − a (where the piece ends in left minus where it starts in right) and return how many quadruples reach it. If no pieces match, return 0.
Example 1
left="race", right="care" → 1

The best choice is the letter r: position 0 in left, position 2 in right, so 0 − 2 = −2. Nothing gives less, and only one quadruple achieves it.

Example 2
left="ab", right="ab" → 2

The letter a gives 0 − 0 = 0 and b gives 1 − 1 = 0. The longer piece "ab" gives 1 − 0 = 1, which is worse. The minimum 0 is reached by two quadruples.

Example 3
left="dog", right="cat" → 0

No shared letters, so no matching pieces either.

Constraints
  • 1 ≤ len(left), len(right) ≤ 2·10⁵
  • Both strings consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPieces Without Shared Letters MediumNo Twin Letters Side by Side MediumSplit Letters Into Palindromes MediumDistinct Letter Counts MediumPalindrome From Two-Letter Cards Medium
loading Python…
Input
left="race", right="care"
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 85 tests on the server, hidden ones included.