AlgoMaster Logo

Repeated String Match

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The problem requires us to determine the minimum number of times string A has to be repeated such that B is a substring of it. A brute force solution involves repeatedly appending A to itself until B becomes a substring or we surpass a certain reasonable limit.

Steps:

  1. Start by observing that if the answer exists, the number of times we need to repeat A is at least |B|/|A| (integer division) and at most |B|/|A| + 2.
  2. The reasoning behind the upper bound is that B can start appearing mid-way within one of the copies of A which might require one or two more copies of A to cover whole of B.
  3. Create a repeated string starting from a single A, and keep appending A to this string.
  4. For each iteration, check if B is a substring of the current repeated string.
  5. If B is found, return the count of repetitions. If after |B|/|A| + 2 repetitions B is not found, return -1.

Code:

2. Optimal String Concatenation

Intuition:

The brute force solution already works fairly efficiently for most reasonable input sizes. However, we can optimize the repeated string construction and search process slightly using intuitive bounds.

Steps:

  1. Start by computing the minimum repetitions required using ceil(|B|/|A|), which can be done using (B.length() + A.length() - 1) / A.length().
  2. Instead of constructing the repeated string each time from scratch, directly compute this base repeated string.
  3. Append one more A to handle boundary conditions.
  4. Check if B is a substring after minRepeats and minRepeats + 1 repetitions and return the respective count if true.
  5. Return -1 if B is not a substring in both checks.

Code: