Count Pairs of Equal Substrings With Minimum Difference - Problem

You are given two strings firstString and secondString that are 0-indexed and consist only of lowercase English letters.

Count the number of index quadruples (i,j,a,b) that satisfy the following conditions:

  • 0 <= i <= j < firstString.length
  • 0 <= a <= b < secondString.length
  • The substring of firstString that starts at the ith character and ends at the jth character (inclusive) is equal to the substring of secondString that starts at the ath character and ends at the bth character (inclusive)
  • j - a is the minimum possible value among all quadruples that satisfy the previous conditions

Return the number of such quadruples.

Input & Output

Example 1 — Basic Case
$ Input: firstString = "abc", secondString = "bc"
Output: 2
💡 Note: Matching substrings: "b" at (1,1) and (0,0) with j-a=1, "c" at (2,2) and (1,1) with j-a=1. Both achieve minimum j-a=1, so count is 2.
Example 2 — Single Character
$ Input: firstString = "a", secondString = "a"
Output: 1
💡 Note: Only one match: "a" at (0,0) and (0,0) with j-a=0. This is the minimum, so count is 1.
Example 3 — No Matches
$ Input: firstString = "abc", secondString = "def"
Output: 0
💡 Note: No common substrings between the two strings, so no valid quadruples exist.

Constraints

  • 1 ≤ firstString.length, secondString.length ≤ 100
  • firstString and secondString consist only of lowercase English letters

Visualization

Tap to expand
Count Equal Substring Pairs With Minimum DifferencefirstString = "abc"secondString = "bc"abc012bc01Match!Match!Matching Quadruples"b": (i=1,j=1,a=0,b=0) → j-a = 1-0 = 1"c": (i=2,j=2,a=1,b=1) → j-a = 2-1 = 1"bc": (i=1,j=2,a=0,b=1) → j-a = 2-0 = 2Minimum j-a = 1Count of pairs with j-a = 1: 2Output: 2
Understanding the Visualization
1
Input Strings
firstString = 'abc', secondString = 'bc'
2
Find Matches
Compare all substring pairs and calculate j-a differences
3
Count Minimum
Count pairs with minimum j-a value
Key Takeaway
🎯 Key Insight: Group equal substrings and find the minimum j-a difference among all matching pairs
Asked in
Google 12 Amazon 8 Microsoft 6
8.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen