String Transformation
Real-world version: Turning a Word Onto Its TargetThe statement here is our own: the same inputs, outputs and technique.
Two words s and t have the same length n, which is at least 2, and hold only lowercase letters.
One turn on s works like this: pick a cut length c with 1 <= c <= n - 1, take the last c letters off the end of s, and put them back on at the front keeping their order. So s becomes the last c letters followed by the first n - c letters.
Two sequences of turns are counted apart when they pick a different cut length on some turn, even if the words they pass through are the same.
Return how many sequences of exactly k turns carry s to t, taken modulo 10^9 + 7.
Examples
Example 1
- Input
- s = "ab", t = "ba", k = 1
- Output
- 1
With two letters the only allowed cut length is one, and taking the last letter to the front swaps the pair.
Example 2
- Input
- s = "abab", t = "abab", k = 2
- Output
- 5
Each turn picks one of three cut lengths, so there are nine sequences of two turns. The word reads the same after sliding it two places as it does untouched, so a sequence lands on the target when its two cut lengths add to two, four or six: that is 1 with 1, 1 with 3, 2 with 2, 3 with 1, and 3 with 3.
Example 3
- Input
- s = "xyz", t = "zyx", k = 4
- Output
- 0
Sliding letters round never reverses their order, so no slide turns the word into the target and no sequence of turns can either.
Constraints
- 2 <= s.length <= 5 * 10^5
- s.length == t.length
- 1 <= k <= 10^15
- s and t hold only lowercase English letters
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def number_of_ways(s: str, t: str, k: int) -> int:public int numberOfWays(String s, String t, long k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Maximum Repeating SubstringReal-world version: Longest Run of a Repeated TagEasy
- Different Ways to Add ParenthesesReal-world version: Every Value a Sum Can Be Grouped IntoMedium
- Numbers At Most N Given Digit SetReal-world version: Labels Printable With The Stamps On HandHard
- Climbing StairsReal-world version: Rung Ladder ClimbsEasy