Fewest Front-Relocations to Rearrange a String
StringsAuto-graded · 26 test casesLast 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
sourcealready equalstarget, the answer is0. - Two empty strings need
0moves. - 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^5sourceandtargetcontain only lowercase lettersatoz.- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Feasibility. Moves only reorder characters, so the strings must have equal length and identical letter counts. Otherwise return
-1. - Invariant. Consider the characters that are never moved.
- They are never reordered among themselves, so they appear in
targetin the same relative order as insource, which makes them a subsequence ofsource. - Every moved character is placed at the front, so in the final string all moved characters come before all unmoved ones. The unmoved characters therefore form a suffix of
target.
- They are never reordered among themselves, so they appear in
- Answer. To minimize moves, maximize the number of unmoved characters. Let
Lbe the length of the longest suffix oftargetthat is a subsequence ofsource. The answer isn - L. - Computing
L. Walk throughtargetfrom right to left, and keep a pointer intosourcethat also moves right to left. For each target character, move the pointer left until it finds a match. If it runs off the start, stop. Each match increasesLby one.
Why it is correct
- Lower bound: In any valid sequence of moves, the unmoved characters form a suffix of
targetthat is a subsequence ofsource, so at mostLcharacters stay put and at leastn - Lmoves are needed. Moving a character more than once never helps, since only its last move affects its final position. - Achievability: Let
k = n - L. The characters ofsourceoutside the matched suffix have the same multiset astarget[0..k-1], because the full multisets are equal. Move one of them to the front in the ordertarget[k-1], target[k-2], ..., target[0]. Each insertion pushes earlier ones right, and the result istarget[0..k-1]followed by the untouched matched characters, which spelltarget[k..n-1]. That takes exactlykmoves. - Greedy matching is optimal: Matching from the right and always taking the rightmost available position in
sourceleaves the largest possible prefix for the remaining characters. By the usual exchange argument, any valid match can be shifted to the greedy one.
Complexity
- Time:
O(n). Counting is linear and the pointer intosourceonly moves left. - Space:
O(1)extra, since the counters hold at most 26 letters.
Reference solution
from collections import Counter
def min_front_moves(source: str, target: str) -> int:
if len(source) != len(target):
return -1
if Counter(source) != Counter(target):
return -1
i = len(source) - 1 # pointer into source, scanning right to left
kept = 0 # length of longest suffix of target that is a subsequence of source
for ch in reversed(target):
while i >= 0 and source[i] != ch:
i -= 1
if i < 0:
break
kept += 1
i -= 1
return len(source) - kept