708479. Minimum times A has to be repeated such that B is a substring of it

Medium

Minimum times A has to be repeated such that B is a substring of it

Summary

Given two strings A and B, find the minimum number of times A should be repeated such that B becomes a substring of the repeated string. This problem involves pattern searching, strings, and algorithms.

Detailed Explanation

The key to solving this problem is to recognize that when B is a substring of the repeated string, it means that we have found a way to concatenate multiple copies of A such that B appears at some position in the resulting string. Therefore, our goal is to find the minimum number of times A should be repeated to achieve this.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable count to 0.
  2. Iterate through the length of B. For each character in B, check if it exists in the current repetition of A.
  3. If the character is not found, increment count and repeat step 2 until the character is found or we have iterated through the entire string B.
  4. The value of count represents the minimum number of times A should be repeated such that B becomes a substring of it.

Here's an ASCII art diagram illustrating the process:

A : abcd
B : cd

Repeated A : abcdabcd

B is found in the second repetition!
Count = 2

Time complexity: O(|B| * |A|), where |B| and |A| are the lengths of strings B and A, respectively.

Space complexity: O(1), as we only need a few variables to store the count and indices.

Optimized Solutions

Java

View on GeeksforGeeks
public int minRepeatCount(String A, String B) {
    int count = 0;
    for (int i = 0; i < B.length(); i++) {
        boolean found = false;
        for (int j = 0; j <= count; j++) {
            if (A.indexOf(B.charAt(i)) >= 0 && A.substring(j * A.length(), (j + 1) * A.length()).indexOf(B.charAt(i)) >= 0) {
                found = true;
                break;
            }
        }
        if (!found) {
            count++;
        }
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.