← MathWorks Interview Insights
This one took me a minute to even parse correctly.
First, clarify that the operation is a cyclic rotation of a prefix: deleting a character and appending it to the end is equivalent to moving that character to the end, so the final string is a rotation of the original. Then, determine the minimum number of moves by finding the longest suffix of s that is a subsequence of t; the answer is n minus the length of that suffix. Finally, prove correctness, analyze O(n) complexity, and provide clean code.
Pro tip: Emphasize that the operation preserves the relative order of the remaining characters, so the problem reduces to finding the longest suffix of s that appears as a subsequence in t. This insight simplifies the solution and demonstrates strong algorithmic thinking.
Recognize that deleting a character and appending it to the end is equivalent to moving that character to the end, which is a cyclic rotation of a prefix. The final string must be a rotation of the original string.
The characters that are never moved must appear in the same relative order in both s and t. Therefore, the unmoved characters form a common subsequence, and to minimize moves, we want to maximize the number of unmoved characters.
Scan s from right to left and t from right to left to find the longest suffix of s that can be matched as a subsequence in t. The length of this suffix gives the maximum number of characters that can remain unmoved.
The minimum number of moves is n minus the length of the longest matching suffix. Prove that this is optimal by showing that any valid sequence of moves leaves a suffix of s unmoved, and that suffix must be a subsequence of t.
The algorithm runs in O(n) time and O(1) extra space. Write clean code that implements the two-pointer scan from the end.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.