All problems
1093HardMathStringDynamic ProgrammingString Matching

Turning a Word Onto Its Target

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2851String Transformation

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def number_of_ways(s: str, t: str, k: int) -> int:
Java
public int numberOfWays(String s, String t, long k)
September 7
Apply