Skip to main content
Back to problems
#686
Medium Algorithms

Repeated string match

String String Matching
38.4% acceptance
Feb 20, 2026
2866
1007
Given two strings a and b, return the minimum number of times you should repeat a so that b is a substring of it. Return -1 if impossible.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn repeated_string_match(a: String, b: String) -> i32 {
    let mut repeated = a.clone();
    let mut count = 1;
    while repeated.len() < b.len() {
      repeated.push_str(&a);
      count += 1;
    }
    if repeated.contains(b.as_str()) {
      return count;
    }
    repeated.push_str(&a);
    count += 1;
    if repeated.contains(b.as_str()) {
      return count;
    }
    -1
  }
}