Count The Repetitions — LeetCode 466 Python Solution

HardStringDynamic Programming
Problem
#466
Reading time
4 min

The problem

We define str = [s, n] as the string str which consists of the string s concatenated n times. For example, str == ["abc", 3] =="abcabcabc".

Example

Input
s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
Output
2

Python solution

Python
class Solution:
    def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
        n = len(s2)
        d = {}
        for i in range(n):
            cnt = 0
            j = i
            for c in s1:
                if c == s2[j]:
                    j += 1
                if j == n:
                    cnt += 1
                    j = 0
            d[i] = (cnt, j)

        ans = 0
        j = 0
        for _ in range(n1):
            cnt, j = d[j]
            ans += cnt
        return ans // n2

Complexity

MeasureComplexity
TimeO(m \times n + n_1)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 466. Count The Repetitions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 466. Count The Repetitions?
LeetCode 466. Count The Repetitions is rated Hard on LeetCode.
What is the time complexity of LeetCode 466. Count The Repetitions?
The Python solution on this page runs in O(m \times n + n_1).
What is the space complexity of LeetCode 466. Count The Repetitions?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 466. Count The Repetitions cover?
LeetCode 466. Count The Repetitions is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview