Repeated String

Repeated String

Geeks for Geeks - 30 Days of Code - Day 10

·

4 min read

This article describes the question from Day 10 of the 30 Days of Code competition hosted by Geeks for Geeks.

Question

Given two strings A and B, find the minimum number of times A has to be repeated such that B becomes a substring of the repeated A. If B cannot be a substring of A no matter how many times it is repeated, return -1.

Example 1:

Input: A = "abcd", B = "cdabcdab" Output: 3 Explanation: After repeating A three times, we get "abcdabcdabcd".

Example 2:

Input: A = "aa", B = "a" Output: 1 Explanation: B is already a substring of A.

Your Task:
You don't need to read input or print anything. Complete the function repeatedStringMatch() which takes strings A and B as input parameters and returns the minimum number of operations to complete the task. If it is not possible then return -1.

Expected Time Complexity: O(|A| * |B|) Expected Auxiliary Space: O(1)

Constraints: 1 ≤ |A|, |B| ≤ 103

Solution

class Solution:
    def repeatedStringMatch(self, A, B):
        l = len(A) + len(B)
        r = 0
        a,b = '',''
        if A.find(B) != -1:
            return 1
        while a.find(B) == -1 and len(a) < l:
            a += A
            r += 1
        if a.find(B) == -1:
            return -1
        return r

A is a string. B another string which may contain a sequence of repeated A. In the first condition, we check to see if B is a substring of A, (i.e, A='aa', b='a'). In this case, only one repetition is needed since B is part of A already.

We recreate a sequence of A of length l. This is the length of A plus the length of B. This is because B is not guaranteed to contain only complete sequences (i.e., A="abcd", B="cdabcd"). Creating a sequence of this extra length, allows us to ensure these scenarios are covered. Each iteration of the loop we add another A to the sequence, and increase r, our repetitions counter. This loop stops if B is found as a substring of A, or if we exceed the length l.

The last condition checks if B is a substring of the sequence we have recreated. If this check fails, then we know that regardless of the number of repetitions, B will never be a sequence of repeated A. Otherwise, we return r, the number of repetitions.