Count The Repetitions Problem
Description
LeetCode Problem 466.
We define str = [s, n] as the string str which consists of the string s concatenated n times.
- For example,
str == ["abc", 3] =="abcabcabc".
We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1.
- For example,
s1 = "abc"can be obtained froms2 = "ab**dbe**c"based on our definition by removing the bolded underlined characters.
You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2].
Return the maximum integer m such that str = [str2, m] can be obtained from str1.
Example 1:
Input: s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
Output: 2
Example 2:
Input: s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
Output: 1
Constraints:
1 <= s1.length, s2.length <= 100s1ands2consist of lowercase English letters.1 <= n1, n2 <= 10^6
Solution
Approach: One Step per Copy of s1
[str2, m] is just s2 repeated m · n2 times. So the question is how many copies of s2 we can match, one after another, as a subsequence of n1 copies of s1. Call that number total. The answer is total / n2, rounded down.
Matching greedily is optimal: walk through str1 and, whenever its character equals the next needed character of s2, take it. Taking a match as early as possible never hurts later matches.
Simulating all n1 · len(s1) characters (up to 108) is too slow, but notice what one copy of s1 does. It only depends on where we are in s2 when the copy starts, which is one of len(s2) positions. So precompute, for each starting position j in s2:
done[j]: how many copies ofs2get finished while reading ones1from positionj;after[j]: the position ins2we are at when thats1ends.
Each table entry costs one pass over s1. Then process the n1 copies of s1 in O(1) each: start at j = 0, and n1 times do total += done[j]; j = after[j].
In Example 1, s1 = "acb" and s2 = "ab". From position 0, one "acb" finishes one "ab" and returns to position 0. Four copies give total = 4 copies of "ab", and 4 / 2 = 2. If s2 contains a letter that s1 lacks, every done[j] is 0 and the answer is 0.
Complexity: O(len(s1) · len(s2) + n1) time and O(len(s2)) extra space. (The walk is a sequence of positions that must eventually repeat, so it could be cut short by finding the cycle, but with n1 ≤ 106 the plain loop is fast enough.)
class Solution:
def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
n = len(s2)
# For each position j in s2: reading one copy of s1 from there finishes done[j] copies of s2
# and leaves us at position after[j].
done, after = [0] * n, [0] * n
for start in range(n):
j, count = start, 0
for c in s1:
if c == s2[j]:
j += 1
if j == n:
count += 1
j = 0
done[start], after[start] = count, j
total, j = 0, 0 # copies of s2 matched so far, and where we are in s2
for _ in range(n1):
total += done[j]
j = after[j]
return total // n2