{x}
blog image

Count Pairs of Equal Substrings With Minimum Difference

Solution Explanation:

This problem requires finding the number of quadruples (i, j, a, b) such that substrings firstString[i:j+1] and secondString[a:b+1] are equal, and j - a is minimized. The solution leverages a greedy approach combined with a hash table for efficient lookup.

Algorithm:

  1. Preprocessing: Create a hash map (or array) last to store the last seen index of each character in secondString. This allows for O(1) lookup of the last occurrence of a character.

  2. Iteration: Iterate through firstString. For each character c in firstString:

    • Check if c exists in last. If not, it means the character is not present in secondString, so we skip it.
    • Calculate diff = i - last[c], where i is the current index in firstString. This diff represents j - a for a potential matching substring pair.
    • Greedy Comparison:
      • If diff is smaller than the current minimum difference minDiff, update minDiff to diff and reset the count of quadruples to 1 (because we've found a new minimum difference).
      • If diff is equal to minDiff, increment the count of quadruples because we've found another quadruple with the same minimum difference.
  3. Return: After iterating through firstString, return the final count of quadruples.

Time Complexity: O(m + n), where m is the length of firstString and n is the length of secondString. The preprocessing step takes O(n), and the iteration takes O(m).

Space Complexity: O(C), where C is the number of unique characters (26 in this case, for lowercase English letters). The space complexity is dominated by the last hash map (or array).

Code Implementation (Python):

class Solution:
    def countQuadruples(self, firstString: str, secondString: str) -> int:
        last = {}  # Hash map to store last seen index of each character in secondString
        for i, c in enumerate(secondString):
            last[c] = i
 
        min_diff = float('inf')  # Initialize minimum difference to infinity
        count = 0  # Initialize count of quadruples
 
        for i, c in enumerate(firstString):
            if c in last:
                diff = i - last[c]
                if diff < min_diff:
                    min_diff = diff
                    count = 1  # Reset count for new minimum difference
                elif diff == min_diff:
                    count += 1  # Increment count for same minimum difference
 
        return count
 

The code in other languages (Java, C++, Go, TypeScript) follows a very similar structure, adapting the syntax and data structures to the specific language. The core algorithmic approach remains the same.