KatInterview

Fewest Front-Relocations to Rearrange a String

StringsAuto-graded · 26 test cases
MediumAuto-gradedStringsstringsgreedytwo-pointers

Last updated

Count the minimum moves to turn one string into another by moving characters to the front, using a multiset check and a right-to-left greedy subsequence match.

You are given two strings, source and target, made of lowercase English letters.

In one move, you pick any single character of the current string, remove it from its position, and re-insert it at the very front of the string. All other characters keep their relative order.

Return the minimum number of moves needed to turn source into target. If it is impossible, return -1.

Rules and edge cases

  • If the two strings have different lengths, return -1.
  • If the strings have the same length but contain different multisets of letters (some letter occurs a different number of times), return -1.
  • If source already equals target, the answer is 0.
  • Two empty strings need 0 moves.
  • The same character may be moved more than once, but only the minimum total count of moves is asked for.

Constraints

  • 0 <= len(source), len(target) <= 10^5
  • source and target contain only lowercase letters a to z.
  • The strings may have different lengths.

Examples

Example 1

Input: min_front_moves('abcde', 'cdeab')

Output: 3

Example 2

Input: min_front_moves('aabb', 'bbaa')

Output: 2

Example 3

Input: min_front_moves('abc', 'abd')

Output: -1

Example 4

Input: min_front_moves('a', 'a')

Output: 0

Hints

Hint 1

First decide when the answer is -1. Moves only rearrange characters, so what must the two strings have in common?

Hint 2

Think about the characters that are never moved. What do you know about their order in the source, and about where they sit in the target relative to the moved characters?

Hint 3

The unmoved characters form a suffix of the target that is also a subsequence of the source. Find the longest such suffix by scanning both strings from right to left with two pointers; the answer is the length minus that suffix length.