Count The Repetitions - Problem

We define a string 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 = "adbec" by removing the characters 'd' and 'e'.

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.

Input & Output

Example 1 — Basic Case
$ Input: s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
Output: 2
💡 Note: str1 = "acbacbacbacb". We can form str2 = "ab" twice by taking characters at positions [0,2] and [3,5], so we can get [str2, 2] from str1.
Example 2 — No Complete Match
$ Input: s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
Output: 1
💡 Note: str1 = "acb" and we need s2 = "acb" once. We can form exactly 1 copy of s2 from str1.
Example 3 — Impossible Match
$ Input: s1 = "abc", n1 = 2, s2 = "def", n2 = 1
Output: 0
💡 Note: str1 = "abcabc" contains no characters from s2 = "def", so we cannot form any copy of s2.

Constraints

  • 1 ≤ s1.length, s2.length ≤ 100
  • 1 ≤ n1, n2 ≤ 106
  • s1 and s2 consist of lowercase English letters

Visualization

Tap to expand
Count The Repetitions: Pattern MatchingInput:s1 = "acb", n1 = 4s2 = "ab", n2 = 2str1 = s1 × n1:a c b a c b a c b a c bFinding s2 = "ab" patterns:Match 1Match 2Match 3Match 4Found 4 matches, but limited by n2 = 2Result: 2
Understanding the Visualization
1
Input
s1="acb", n1=4, s2="ab", n2=2
2
Process
Find how many complete s2 patterns fit in str1
3
Output
Return min(found_matches, n2)
Key Takeaway
🎯 Key Insight: Use cycle detection to avoid simulating every character match for large repetitions
Asked in
Google 15 Microsoft 8
12.0K Views
Medium Frequency
~35 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen