Skip to main content

Count The Repetitions - Solution & Explanation

HardStringDynamic Programming19 min readAsked at: Google
Practice this problem

Problem Statement

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 from s2 = "abdbec" 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 <= 100
  • s1 and s2 consist of lowercase English letters.
  • 1 <= n1, n2 <= 106

Approach Overview

Problem Overview: You are given two strings s1 and s2 with repeat counts n1 and n2. The task is to determine how many times the sequence [s2, n2] can be obtained as a subsequence from the repeated string [s1, n1]. Characters must appear in order, but you can skip characters while matching.

Approach 1: Simulation using Pointers (Time: O(n1 * |s1|), Space: O(1))

This approach directly simulates building the repeated string [s1, n1] and tries to match characters from s2. Use two pointers: one iterating through characters of s1 and another tracking the current position in s2. Every time characters match, advance the s2 pointer. When the pointer reaches the end of s2, increment a counter and reset it to zero. After scanning s1 exactly n1 times, divide the total number of completed s2 matches by n2. This method relies purely on sequential scanning and subsequence matching logic, making it straightforward to implement. However, when n1 is very large, repeated scanning becomes inefficient because the same matching patterns repeat.

Approach 2: Cycle Detection Optimization (Time: ~O(|s1| * |s2|), Space: O(|s2|))

Repeated subsequence matching often forms cycles. After processing some repetitions of s1, the pointer inside s2 returns to a previously seen position. Once this happens, the same sequence of matches will repeat for the remaining blocks of s1. Store states using a map where the key is the current index in s2, and the value records how many s1 blocks and s2 matches have been processed. When the same s2 index appears again, a cycle is detected. You can compute how many full cycles fit into the remaining s1 repetitions and jump ahead instead of simulating each one. This drastically reduces runtime for large inputs. The idea resembles pattern repetition analysis often seen in string processing and dynamic programming style state reuse.

Recommended for interviews: Start with the pointer simulation to demonstrate the subsequence matching logic clearly. Then discuss the repeating pattern observation and optimize it with cycle detection. Interviewers typically expect the optimized solution because it shows you recognize repeated states and avoid redundant work, a common optimization pattern in advanced string problems.

Approach 1: Approach 1: Simulation using pointers

This approach attempts to simulate the process of generating strings str1 and counting how many times str2 can be obtained. It uses two pointers to track the current positions in s1 and s2, moving them accordingly to find subsequence matches.

This C solution employs two loops: the outer loop repeats s1 n1 times and the inner loop checks for matches between characters in s1 and s2. The logic counts complete occurrences of s2 and divides by n2 at completion.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n1 * len1 * len2) where len1 and len2 are lengths of s1 and s2 respectively. Space Complexity: O(1).

Try this approach in the editor →

Approach 2: Approach 2: Cycle detection optimization

This approach optimizes the simulation by detecting and leveraging cycles. Once a cycle is detected in the repetition process, it calculates the outcomes in cycles to quickly compute the result, reducing the number of direct iterations required.

This C implementation detects cycle patterns in the process of iterating through s1 and s2. It optimizes by skipping over full cycle repetitions, leveraging recorded indices within the memoization table.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n1 * len1) in worst-case but optimized by cycle detection. Space Complexity: O(len1 * len2) for memoization table.

Try this approach in the editor →

Approach 3: Preprocessing + Iteration

We preprocess the string s_2 such that for each starting position i, we calculate the next position j and the count of s_2 after matching a complete s_1, i.e., d[i] = (cnt, j), where cnt represents the count of s_2, and j represents the next position in the string s_2.

Next, we initialize j=0, and then loop n1 times. Each time, we add d[j][0] to the answer, and then update j=d[j][1].

The final answer is the count of s_2 that can be matched by n1 s_1, divided by n2.

The time complexity is O(m times n + n_1), and the space complexity is O(n). Where m and n are the lengths of s_1 and s_2 respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Simulation using pointers

Time Complexity: O(n1 * len1 * len2) where len1 and len2 are lengths of s1 and s2 respectively. Space Complexity: O(1).

Approach 2: Cycle detection optimization

Time Complexity: O(n1 * len1) in worst-case but optimized by cycle detection. Space Complexity: O(len1 * len2) for memoization table.

Preprocessing + Iteration—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Simulation using PointersO(n1 * |s1|)O(1)Good baseline solution when n1 is small or when demonstrating subsequence matching logic in interviews
Cycle Detection Optimization~O(|s1| * |s2|)O(|s2|)Best for large n1 where repeated patterns appear and skipping cycles avoids redundant simulation

Video Solution

LeetCode 466. Count The Repetitions (Hard) | Dynamic Programming | C++ • Ascorbichelix • 3,427 views views

Watch 7 more video solutions →

Frequently Asked Questions

Is Count The Repetitions easy or hard?
Count The Repetitions is classified as a Hard problem because the straightforward simulation can be slow for large inputs. The key difficulty is recognizing that the matching process eventually repeats and using cycle detection to skip redundant work.
Count The Repetitions Python/Java solution
Both Python and Java implementations follow the same logic: simulate subsequence matching between repeated s1 and s2 while tracking the current index in s2. The optimized version stores previously seen states in a map to detect cycles and jump ahead when patterns repeat.
How to solve Count The Repetitions in O(n)?
Strict O(n) time is not guaranteed because matching depends on both |s1| and |s2|. However, cycle detection significantly reduces redundant scans by identifying repeating states of the s2 pointer. Once a cycle is found, you can jump across many repetitions of s1 in constant time.
What is the best approach for Count The Repetitions?
The most efficient approach uses cycle detection during the simulation of repeated strings. By storing the current index in s2 after each pass of s1, you can detect repeating states and skip entire cycles. This reduces redundant work and improves performance to roughly O(|s1| * |s2|) time with O(|s2|) space.
Is Count The Repetitions asked at Google/Amazon/Meta?
Count The Repetitions is a classic hard string problem commonly used to test pattern detection and optimization techniques. Variants of subsequence repetition and cycle detection problems have appeared in interviews at large tech companies including Google, Amazon, and Meta.
What data structure is used in Count The Repetitions?
The optimized solution uses a hash map to record previously seen states of the s2 pointer along with counts of processed s1 blocks and matched s2 strings. This allows fast cycle detection and skipping repeated patterns.
What is the time complexity of Count The Repetitions?
The basic simulation approach runs in O(n1 * |s1|) time because it scans s1 repeatedly while matching characters from s2. The optimized cycle detection approach reduces repeated work and runs in approximately O(|s1| * |s2|) time with O(|s2|) additional space.

Ready to solve this problem?

Practice Count The Repetitions with our built-in code editor and test cases.

Practice on FleetCode