#2851
String Transformation
HardMathStringDynamic ProgrammingString MatchingKMP algorithm for string matchingString rotation and manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use the KMP algorithm or Z algorithm to find all valid rotations of s that match t. This allows us to efficiently count the matches and determine how many can be achieved in k operations.
⚙️
Algorithm
3 steps- 1Step 1: Use the KMP algorithm to find all starting indices where s matches t.
- 2Step 2: Count how many of these indices can be reached in exactly k operations.
- 3Step 3: Return the count modulo 10^9 + 7.
solution.py33 lines
1def kmp_table(pattern):
2 m = len(pattern)
3 lps = [0] * m
4 length = 0
5 i = 1
6 while i < m:
7 if pattern[i] == pattern[length]:
8 length += 1
9 lps[i] = length
10 i += 1
11 else:
12 if length != 0:
13 length = lps[length - 1]
14 else:
15 lps[i] = 0
16 i += 1
17 return lps
18
19def countTransformations(s, t, k):
20 if len(s) != len(t): return 0
21 s = s + s
22 lps = kmp_table(t)
23 count = 0
24 j = 0
25 for i in range(len(s)):
26 while j > 0 and s[i] != t[j]:
27 j = lps[j - 1]
28 if s[i] == t[j]:
29 j += 1
30 if j == len(t):
31 count += 1
32 j = lps[j - 1]
33 return count if k % len(s) == 0 else 0ℹ
Complexity note: The time complexity is O(n) due to the KMP algorithm, which efficiently finds matches in linear time.
- 1The string t can only be formed from s if it is a rotation of s.
- 2The number of valid transformations is determined by the number of valid rotations that match t.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.