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 INPUT s1 = "acb", n1 = 4 str1 = [s1, n1]: a c b a c b ... s2 = "ab", n2 = 2 str2 = [s2, n2]: a b a b s1 = "acb" n1 = 4 s2 = "ab" n2 = 2 Find max m for [str2, m] ALGORITHM STEPS 1 Track Position State Record s2 index after each complete s1 traversal 2 Detect Cycle Pattern Find repeating state in s2 position after s1 copies s1 s1 s1 s1 cycle 3 Calculate s2 Counts Count complete s2 matches per cycle + remainder s1 copies s2 matches 4 4 4 Compute Final m m = total_s2_count / n2 m = 4 / 2 = 2 FINAL RESULT str1 can form [str2, m]: str1 = "acbacbacbacb" a c b a c b a c b a c b Extracting "ab" matches: a . b a . b a . b a . b Found 4 complete "ab" in str1 str2 = "abab" (n2=2 copies) a b a b Maximum m 2 [str2, 2] can be obtained Key Insight: Pattern detection with cycle finding optimizes the brute-force approach. By tracking the position in s2 after each s1 traversal, we can detect repeating patterns. Once a cycle is found, we can calculate the total s2 matches without iterating through all n1 copies, reducing time complexity significantly. TutorialsPoint - Count The Repetitions | Pattern Detection with Cycle Finding
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