1794. Count Pairs of Equal Substrings With Minimum Difference π
DifficultyMedium
Description
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 theithcharacter and ends at thejthcharacter (inclusive) is equal to the substring ofsecondStringthat starts at theathcharacter and ends at thebthcharacter (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 * 105- Both strings consist only of lowercase English letters.
Solutions
Solution 1: Greedy + Hash Table
Thinking
A valid quadruple needs equal substrings and minimal \(j-a\). Equality collapses to a single character: the leftmost occurrence in \(\textit{firstString}\) paired with the rightmost same character in \(\textit{secondString}\).
Map each character of \(\textit{secondString}\) to its last index. Walk \(\textit{firstString}\) and update the global minimum of \(i-\textit{last}[c]\) together with its multiplicity.
The problem actually asks us to find a smallest index \(i\) and a largest index \(j\) such that \(\textit{firstString}[i]\) equals \(\textit{secondString}[j]\), and the value of \(i - j\) is the smallest among all index pairs that meet the conditions.
Therefore, we first use a hash table \(\textit{last}\) to record the index of the last occurrence of each character in \(\textit{secondString}\). Then we traverse \(\textit{firstString}\). For each character \(c\), if \(c\) has appeared in \(\textit{secondString}\), we calculate \(i - \textit{last}[c]\). If the value of \(i - \textit{last}[c]\) is less than the current minimum value, we update the minimum value and set the answer to 1. If the value of \(i - \textit{last}[c]\) equals the current minimum value, we increment the answer by 1.
The time complexity is \(O(m + n)\), and the space complexity is \(O(C)\), where \(m\) and \(n\) are the lengths of \(\textit{firstString}\) and \(\textit{secondString}\) respectively, and \(C\) is the size of the character set. In this problem, \(C = 26\).
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |