#466

Count The Repetitions

Hard
Two PointersStringDynamic ProgrammingTwo PointersDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of generating large strings, we can use a two-pointer technique to efficiently count how many times str2 can be formed from str1 without explicitly creating the full strings.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use two pointers to traverse s1 and s2. Count how many characters from s2 can be matched in str1.
  2. 2Step 2: Keep track of how many full iterations of str2 can be formed from the characters matched in str1.
  3. 3Step 3: Repeat the process for the number of times str1 is repeated (n1).
solution.py13 lines
1def count_repetitions(s1, n1, s2, n2):
2    count = 0
3    s1_len, s2_len = len(s1), len(s2)
4    total_s2 = 0
5    i = 0
6    while total_s2 < n2:
7        for j in range(s1_len):
8            if s1[i % s1_len] == s2[total_s2 % s2_len]:
9                total_s2 += 1
10                if total_s2 % s2_len == 0:
11                    count += 1
12        i += 1
13    return count

Complexity note: The time complexity is O(n) because we are effectively iterating through the characters of s1 and s2 without generating large strings, making it efficient.

  • 1Understanding the relationship between the strings and how they can be formed is crucial.
  • 2Using pointers to track positions in the strings can significantly reduce the time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.