#686

Repeated String Match

Medium
StringString MatchingString MatchingTwo Pointers
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution leverages the properties of string matching. By calculating how many times we need to repeat 'a' based on the lengths of 'a' and 'b', we can minimize unnecessary concatenations and directly check for substring presence.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the minimum number of times 'a' needs to be repeated to ensure its length is at least the length of 'b'.
  2. 2Step 2: Create a repeated string by repeating 'a' the calculated number of times.
  3. 3Step 3: Check if 'b' is a substring of this repeated string. If not, repeat 'a' one more time and check again.
  4. 4Step 4: Return the count if 'b' is found; otherwise, return -1.
solution.py7 lines
1def repeatedStringMatch(a, b):
2    repeat_count = -(-len(b) // len(a))  # Ceiling division
3    repeated = a * repeat_count
4    if b in repeated:
5        return repeat_count
6    repeated += a
7    return repeat_count + 1 if b in repeated else -1

Complexity note: The time complexity is O(n) because we only concatenate 'a' a limited number of times based on the length of 'b'. The space complexity is O(n) due to the storage of the repeated string.

  • 1Understanding string lengths helps in determining how many times to repeat 'a'.
  • 2Checking for substrings efficiently can save unnecessary computations.

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