Program to find out the number of pairs of equal substrings in Python


Suppose we are given two strings, both made of lowercase alphabets. We have to find out the number of quadruples (p, q, r, s) satisfying the given conditions −

  • 0 <= p <= q <= length of the first string.

  • 0 <= r <= s <= length of the second string.

  • The substring starting at index p of the first string and ending at index q of the first string, has to be equal to the substring starting at index q of the second string and ending at index r of the second string.

  • q - r has to be the minimum possible value within all the quadruples satisfying the above.

We have to find out the number of such quadruples.

So, if the input is like firstString = 'hgfn', secondString = 'gfrt', then the output will be 2.

There are two quadruples (1, 1, 0, 0) and (2, 2, 1, 1) that satisfy the conditions and have the minimum value for q - r.

To solve this, we will follow these steps −

  • Define a function ord() . This will take ch
    • return unicode value of ch
  • From the main method do the following −
  • left := a new list of size 26 containing value infinity
  • right := a new list of size 26 containing value -1
  • res := 0
  • mi := infinity
  • for each index i, and character ch in firstString, do
    • left[ord(ch) - ord('a') ] := minimum of (left[ord(ch) - ord('a') ], i)
  • for each index i, and character ch in secondString, do
    • right[ord(ch) - ord('a') ] := maximum of right[ord(ch) - ord('a') ], i
  • for i in range 0 to 25, do
    • if left[i] is not same as -1, then
      • mi := minimum of (mi, left[i] - right[i])
  • for i in range 0 to 25, do
    • if left[i] is not same as infinity and right[i] is not same as -1, then
      • if left[i] - right[i] is same as mi, then
        • res := res + 1
  • return res

Example

Let us see the following implementation to get better understanding −

def solve(firstString, secondString):
   left = [float('inf')] * 26
   right = [-1] * 26
   res = 0
   mi = float('inf')
   for i, ch in enumerate(firstString):
      left[ord(ch) - ord('a')] = min(left[ord(ch) - ord('a')], i)
   for i, ch in enumerate(secondString):
      right[ord(ch) - ord('a')] = max(right[ord(ch) - ord('a')], i)
   for i in range(26):
      if left[i] != -1:
         mi = min(mi, left[i] - right[i])
   for i in range(26):
      if left[i] != float('inf') and right[i] != -1:
         if left[i] - right[i] == mi:
            res += 1
   return res

print(solve('hgfn', 'gfrt'))

Input

'hgfn', 'gfrt'

Output

2

Updated on: 07-Oct-2021

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements