Count Pairs of Equal Substrings With Minimum Difference Problem
Description
LeetCode Problem 1794.
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.length0 <= a <= b < secondString.length- The substring of
firstStringthat starts at thei^thcharacter and ends at thej^thcharacter (inclusive) is equal to the substring ofsecondStringthat starts at thea^thcharacter and ends at theb^thcharacter (inclusive). j - ais the minimum possible value among all quadruples that satisfy the previous conditions.
Return the number of such quadruples.
Example 1:
Input: firstString = "abcd", secondString = "bccda"
Output: 1
Explanation: The quadruple (0,0,4,4) is the only one that satisfies all the conditions and minimizes j - a.
Example 2:
Input: firstString = "ab", secondString = "cd"
Output: 0
Explanation: There are no quadruples satisfying all the conditions.
Constraints:
1 <= firstString.length, secondString.length <= 2 * 10^5- Both strings consist only of lowercase English letters.
Solution
Approach: Greedy + Last Occurrence
Since a match of length one is always available when any character is shared, and extending it never lowers i - j, the problem reduces to single characters: find pairs (i, j) with firstString[i] == secondString[j] that minimize i - j. For a fixed i the best j is the last occurrence of that character in secondString.
Store those last occurrences first. Then scan firstString: compute i - last[c] for each character that occurs in secondString; a smaller value resets the answer to 1, an equal value adds 1.
Complexity: time O(m + n), space O(C), where m and n are the string lengths and C = 26.
from math import inf
class Solution:
def countQuadruples(self, firstString: str, secondString: str) -> int:
last = {c: i for i, c in enumerate(secondString)}
ans, mi = 0, inf
for i, c in enumerate(firstString):
if c in last:
t = i - last[c]
if mi > t:
mi = t
ans = 1
elif mi == t:
ans += 1
return ans