Count Pairs of Equal Substrings With Minimum Difference - Problem
Count Pairs of Equal Substrings With Minimum Difference
You're given two strings firstString and secondString containing only lowercase English letters. Your task is to find matching substrings between these two strings and count specific quadruples.
A quadruple (i, j, a, b) is valid if:
0 <= i <= j < firstString.length0 <= a <= b < secondString.length- The substring
firstString[i:j+1]equalssecondString[a:b+1] j - ais the minimum possible value among all valid quadruples
Goal: Return the count of quadruples that satisfy all conditions, especially having the minimum j - a value.
Example: If firstString = "abab" and secondString = "ab", we need to find all matching substrings and then count only those with minimum difference j - a.
Input & Output
example_1.py โ Basic Match
$
Input:
firstString = "abab", secondString = "ab"
โบ
Output:
1
๐ก Note:
The substring "ab" from firstString[1:2] matches secondString[0:1]. The quadruple (1,2,0,1) gives j-a = 2-0 = 2. This is the minimum possible difference, so we count 1 quadruple.
example_2.py โ Multiple Matches
$
Input:
firstString = "ab", secondString = "abab"
โบ
Output:
3
๐ก Note:
We have matches: "a"(0,0,0,0) with diff=0, "a"(0,0,2,2) with diff=-2, "b"(1,1,1,1) with diff=0, "b"(1,1,3,3) with diff=-2, "ab"(0,1,0,1) with diff=1, "ab"(0,1,2,3) with diff=-1. Minimum difference is -2, and there are 2 quadruples with this difference.
example_3.py โ No Matches
$
Input:
firstString = "abc", secondString = "def"
โบ
Output:
0
๐ก Note:
No common substrings exist between the two strings, so there are no valid quadruples.
Visualization
Tap to expand
Understanding the Visualization
1
Scan by Book Size
Process books (substrings) starting from single letters, then pairs, then larger groups
2
Create Quick Reference
Build a catalog of all books on the second shelf for current size
3
Find Matches
For each book on the first shelf, quickly look up matches in the catalog
4
Calculate Reading Order
Compute j-a difference (position relationship between matched books)
5
Track Best Arrangement
Keep only matches with the minimum reading order difference
Key Takeaway
๐ฏ Key Insight: By processing substrings length by length and tracking the minimum j-a difference dynamically, we avoid storing all possible matches and achieve optimal efficiency.
Time & Space Complexity
Time Complexity
O(n^3)
Three nested loops for length, starting positions, and string comparison
โ Quadratic Growth
Space Complexity
O(n^2)
Hash map stores substrings of current length only
โ Quadratic Space
Constraints
- 1 <= firstString.length, secondString.length <= 100
- firstString and secondString consist of only lowercase English letters
- The minimum difference j - a can be negative
- All quadruples must satisfy the substring equality condition
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code