LeetcodeApr 15, 2025

Repeated String Match

Hazrat Ali

Leetcode

Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1.

Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".

Example 1:

Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.

Example 2:

Input: a = "a", b = "aa"
Output: 2


Solution
/**
 * @param {string} A
 * @param {string} B
 * @return {number}
 */
const repeatedStringMatch = (A, B) => {
  const lenA = A.length;
  const lenB = B.length;

  for (let i = 0; i < lenA; i++) {
    let j = 0;

    while (j < lenB && B[j] === A[(i + j) % lenA]) {
      j++;
    }

    if (j === lenB) {
      return Math.ceil((i + j) / lenA);
    }
  }

  return -1;
};



Comments