Repeated String Match

Find the fewest copies of one string, joined end to end, that contain another string.

Given two strings a and b, join copies of a end to end until b appears inside the result as a substring, a run of consecutive characters. Return the fewest copies that make this happen, or -1 if no number of copies does.

Example 1
Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: "abcdabcdabcd" contains "cdabcdab", but "abcdabcd" does not.
Example 2
Input: a = "a", b = "aa"
Output: 2
Solution

The Idea

Picture a strip of paper printed with abcd over and over: abcdabcdabcd.... You unroll it from the start, looking for the word cdabcdab printed in one piece. How many copies of abcd do you have to unroll?

The word has 8 letters and each copy has 4, so two copies give exactly 8 letters, abcdabcd. That is long enough, yet the word is not in it. The word begins with cd, and cd only appears two letters into a copy. Look at the picture below.

Three copies of abcd side by side, labelled copy 1, copy 2 and copy 3. b, cdabcdab, starts at offset 2 inside copy 1. Two copies are already 8 letters, as long as b, but the last 2 letters of b spill into copy 3.

The row labelled b starts under the c of copy 1, at offset 2: two letters in from the start of a copy. From there, 8 letters reach past the end of copy 2, marked by the dashed line. The last two letters, ab, come from copy 3, so the answer is 3.

That raises the real question: how far might we have to go? Could some b need five or ten copies more than its length suggests? And when b is not there at all, when do we stop looking?

Every copy is the same, so wherever b sits on the strip, it fits just as well starting inside copy 1, at the same offset. That offset is at most one less than the length of a. Starting at offset 0, b needs the fewest copies whose total length reaches its own length; call that number q. A later start pushes the end of b right by less than one copy, so it never needs more than q + 1.

So only two strings need checking: q copies and q + 1 copies. The q + 1 copies hold every possible start inside copy 1, so if b is not there, no number of copies contains it.

Solution Approach

The simple way keeps adding copies until b shows up. The two copy counts, q and q + 1, turn it into three decisions: where to start checking, when to stop, and how to search the joined string.

Adding copies until b appears

Why not just add a copy, search, and repeat? For Example 1 that works: one copy, two copies, then three, found. But for a = "abc" and b = "wxyz" the search never succeeds, and nothing tells the loop when to give up. It needs a limit.

The fewest copies worth checking

Which copy count should the first search use? Any string shorter than b cannot contain it, so searching there is wasted. Keep appending a while the joined string is shorter than b, and count the copies. The count is q, and the first search happens there.

The one extra copy as the limit

When should the search stop? q + 1 copies hold every possible start inside copy 1, so the limit is one more copy and one more search. A miss after that means the answer is -1. That gives exactly two searches, whatever the strings are.

Searching the joined string

How do we build and search the joined string? Java's String cannot change, so each + would copy all the letters so far. A StringBuilder grows in place instead, and its indexOf(b) returns the position where b starts, or -1 when it is not there.

Java Solution

The method repeatedStringMatch works in these steps:

  1. First, create an empty StringBuilder named sb and a counter times set to 0. A loop appends a to sb and adds 1 to times while sb is shorter than b. When it ends, times is q.
  2. Search sb with sb.indexOf(b). If b is found, return times.
  3. Otherwise append one more copy of a and search again. If b is found now, return times + 1.
  4. If neither search found b, return -1.

The main method runs both examples, a one-letter b, a short b that still needs the extra copy, a b made of the letters of a in the wrong order, and a b that shares no letters with a.

Java
public class RepeatString {

    public static int repeatedStringMatch(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int times = 0;
        while (sb.length() < b.length()) {    // the fewest copies that are at least as long as b
            sb.append(a);
            times++;
        }
        if (sb.indexOf(b) >= 0) {
            return times;
        }
        if (sb.append(a).indexOf(b) >= 0) {   // one more copy covers any starting offset
            return times + 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(repeatedStringMatch("abcd", "cdabcdab"));
        System.out.println(repeatedStringMatch("a", "aa"));
        System.out.println(repeatedStringMatch("abc", "b"));
        System.out.println(repeatedStringMatch("abcd", "cda"));
        System.out.println(repeatedStringMatch("abc", "acb"));
        System.out.println(repeatedStringMatch("abc", "wxyz"));
    }
}

Running it prints:

Output
3
2
1
2
-1
-1

The 3 and the 2 at the top match the two examples. Example 1 needed the extra copy, and Example 2 did not: two copies of "a" already make "aa".

The 1 on the third line is for b = "b". One copy of "abc" is already as long as b, so the first loop stops after one append, and the first search finds it. The 2 on the fourth line is for "cda". One copy of "abcd" is long enough, but "cda" starts at offset 2, and its a comes from the second copy.

The two -1 lines show the limit at work. "acb" uses only letters from "abc", but in "abcabc" an a is always followed by b, so it never appears. "wxyz" shares no letters with "abc". Both stop after the second search instead of adding copies forever.

The extra copy matters more than it looks. A version that checks only the first q copies returns -1 for both "cdabcdab" and "cda", instead of 3 and 2.

Complexity

The work is building at most q + 1 copies of a and running two searches over them. Call the length of a m and the length of b n.

  • Time: O(m × n), plus O(m + n) for the appends. The joined string holds fewer than n + 2m letters, so b can start at no more than 2m positions in it. indexOf tries the starts one by one and compares up to n letters at each. With KMP, a search that never steps back in the joined string, the time drops to O(m + n).
  • Space: O(m + n) for the joined string in sb, which never holds more than n + 2m letters.

A related trick, joining a string to itself to see all its rotations, solves Rotate String.