Program to find number of squareful arrays in Python


Suppose we want to make a target string of lowercase letters. At first, we have the sequence as n '?' marks (n is the length of target string). We also have a stamp of lowercase letters. On each turn, we can place the stamp over the sequence, and replace every letter in the with the corresponding letter from that stamp. You can make up to 10 * n turns.

As an example consider the initial sequence is "?????", and the stamp is "abc", then we may make strings like "abc??", "?abc?", "??abc" in the first turn. If the sequence is possible to stamp, then return an array of the index with the left-most letter being stamped at each turn. If that is not possible then return an empty array. So when the sequence is "ababc", and the stamp is "abc", then the answer can be like [0, 2], Because we can form like "?????" -> "abc??" - > "ababc".

So, if the input is like s = "abcd" t = "abcdbcd", then the output will be [3,0]

To solve this, we will follow these steps −

  • if size of s is same as 1, then

    • return a list from 0 to t when all characters in t are same and they are s[0], otherwise a new blank list

  • ans := a new list

  • while t is not same as size of t number of "?" marks, do

    • tmp := t

    • for i in range 0 to size of s, do

      • for j in size of s down to i+1:

        • search := i number of "?" concatenate substring of s[from index i to j-1] concatenate (size of s - j)number of "?"

        • while search is in t, do

          • insert where search is present in t at the end of ans

          • t := replace search with size of s number of "?" only once

        • if t is same as size of t number of "?", then

          • come out from loop

        • if t is same as size of t number of "?", then

          • come out from loop

      • if tmp is same as t, then

        • come out from loop

  • return reverse of ans.

Example

Let us see the following implementation to get better understanding

def solve(s, t):
   if len(s) == 1:
      return [i for i in range(len(t))] if all(t==s[0] for t in t)else []

   ans = []
   while t != "?" * len(t):
      tmp = t
      for i in range(len(s)):
         for j in reversed(range(i+1, len(s)+1)):
            search = "?" * i + s[i:j] + "?" * (len(s)-j)
            while t.find(search) != -1:
               ans.append(t.find(search))
               t = t.replace(search, "?"*len(s), 1)
            if t == "?" * len(t): break
         if t == "?" * len(t): break
      if tmp == t: return []
   return ans[::-1]

s = "abcd"
t = "abcdbcd"
print(solve(s, t))

Input

"abcd", "abcdbcd"

Output

[3,0]

Updated on: 07-Oct-2021

57 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements