String Transformation - Problem

You are given two strings s and t of equal length n. You can perform the following operation on the string s:

Remove a suffix of s of length l where 0 < l < n and append it at the start of s.

For example, let s = 'abcd' then in one operation you can remove the suffix 'cd' and append it in front of s making s = 'cdab'.

You are also given an integer k. Return the number of ways in which s can be transformed into t in exactly k operations.

Since the answer can be large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Transformation
$ Input: s = "abcd", t = "cdab", k = 1
Output: 1
💡 Note: Remove suffix "cd" (length 2) and append to front: "abcd" → "cdab". There's exactly 1 way to transform s to t in 1 operation.
Example 2 — Multiple Operations
$ Input: s = "abc", t = "bca", k = 2
Output: 1
💡 Note: One possible path: "abc" → remove "c" → "cab" → remove "ab" → "bca". Need to count all paths with exactly 2 operations.
Example 3 — Impossible Target
$ Input: s = "abc", t = "xyz", k = 1
Output: 0
💡 Note: Target "xyz" is not a rotation of "abc", so it's impossible to reach regardless of operations.

Constraints

  • 2 ≤ s.length ≤ 1000
  • t.length = s.length
  • 1 ≤ k ≤ 1000
  • s and t consist of lowercase English letters

Visualization

Tap to expand
String Transformation Problem INPUT String s: a b c d String t: c d a b Parameters: s = "abcd" t = "cdab" k = 1 n = 4 (length) MOD = 10^9 + 7 ALGORITHM STEPS 1 Find valid rotations Count positions where rotation(s) equals t 2 Matrix exponentiation Build transition matrix for k operations 3 Compute paths Use formula with modular arithmetic 4 Apply result Multiply by match count, return mod Example Rotation (l=2): abcd --> cdab OK Remove "cd", prepend it Valid positions: 1 match FINAL RESULT Transformation in k=1 step: a b c d c d a b OUTPUT 1 Only 1 way to transform "abcd" to "cdab" in exactly k=1 operation Key Insight: All rotations of string s form a cyclic group. The problem reduces to counting paths of length k in a state transition graph where each state is a rotation. Using matrix exponentiation achieves O(log k) time complexity. For s="abcd", rotation by 2 positions gives "cdab" = t in one step. TutorialsPoint - String Transformation | Optimal Solution (Matrix Exponentiation)
Asked in
Google 45 Microsoft 32 Amazon 28
23.4K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen