AlgoInsight

DSA problem

Repeated String Match

MediumString MatchingPattern: String Matchingtop300AmazonGoogleMicrosoftBloombergApple

Given two strings a and b, return the minimum number of times you must repeat a so that b becomes a substring of the repeated string. If no such number of repetitions makes b a substring of repeated a, return -1.

The key observation is a tight upper bound on how many repetitions are ever needed. If b is a substring of a repeated some number of times, then b aligns somewhere inside the repetition. Building enough copies so that the total length is at least |a| + |b| is always sufficient: any further repetition would only add another full copy of a, which cannot create a new substring placement of b that did not already exist.

This leads to a clean strategy. Repeat a until its length is at least |b| — call this count k. Check whether b is a substring of the resulting string; if yes, return k. Otherwise, append one more copy of a and check again; if it now matches, return k + 1. If neither attempt succeeds, no number of repetitions can ever work, so return -1.

This bound holds because any successful match must start within the first copy of a (every later start is just a shifted version of an earlier one), and from any start position within the first copy, the match cannot extend beyond |a| + |b| characters. Total work is therefore O((|a| + |b|) * |b|) using built-in substring search, or O(|a| + |b|) if KMP is used internally.

Examples

Example 1
Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: Repeating "abcd" three times gives "abcdabcdabcd", and "cdabcdab" is a substring starting at index 2. Two repetitions ("abcdabcd") do not contain "cdabcdab", so 3 is the minimum.
Example 2
Input: a = "a", b = "aa"
Output: 2
Explanation: Repeating "a" twice gives "aa", which contains "aa" as a substring.
Example 3
Input: a = "abc", b = "wxyz"
Output: -1
Explanation: No number of repetitions of "abc" will ever contain "wxyz" since the alphabets do not overlap, so the answer is -1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringstring-matching

Browse all DSA problems