Minimum number of times to repeat a string so another string becomes a substring
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Given two lowercase strings a and b, find the smallest number of times a must be repeated so that b appears inside the result as a substring, or return -1 when no count works. It tests reasoning about string periodicity, bounding the search, and the cost of substring matching.
Constraints
- 1 <= len(a), len(b) <= 10^4
- a and b consist of lowercase English letters.
Examples
Input: ('a', 'a')
Expected Output: 1
Explanation: Minimum valid input: one copy of a already equals b.
Input: ('a', 'b')
Expected Output: -1
Explanation: Minimum valid input with no match: b holds a letter that a lacks.
Hints
- Before b can fit inside the repeated string, the repeated string must be at least as long as b. What is the fewest copies that reaches that length?
- The repeated string looks the same after shifting by one whole copy of a. Where inside the first copy could an occurrence of b start, and how many copies would it need from there?
- Check whether adding copies past a certain point can ever create a new place for b to start.
Community answers
Answer by nitkumthot
Answer by devinliao046
Answer by akkida746
Answer by nicolasjack1994
Answer by hvp4