Transform One String to Another using Minimum Number of Given Operation

Pattern: String building

medium

The only move picks a character of A and puts it at the front. Characters that never move stay at the back in their order, so match B from its end against A from its end; every character of A that cannot be matched must move once.

The problem

You are given two strings A and B of the same length. In one move you take any character of A and insert it at the front of A. Return the fewest moves that turn A into B, or -1 if that is impossible. For example, A = "EACBD" and B = "EABCD" need 3 moves, and "ABC" and "ABD" give -1.

The link above is a GeeksforGeeks article. The function name transform is this guide's own.

Think first

  • When can A never become B?
  • Characters that are never moved: where do they end up, and in what order?
  • Which characters of B can be made of unmoved characters?

Hints

    Brute force, and why it fails

    Breadth-first search over all strings reachable by moves: exponential. The greedy scan from the end is O(n), because keeping a character whenever it matches never makes the kept suffix shorter.

    The key insight

    Count the characters that can stay instead of the ones that move. The ones that stay are the longest suffix of B that appears in A in order, and matching from the back finds it greedily.

    Dry run

    E0 
    A1 
    C2 
    B3 
    D4i
    j4
    moves0

    A = EACBD and B = EABCD. Both use the same letters, so it is possible. Walk A from the end with i, and B from the end with j.

    Step 1 of 4

    The plan

    if A and B have different letter counts: return -1
    moves = 0, j = n - 1
    for i from n - 1 down to 0:
        if A[i] == B[j]: j = j - 1
        else: moves = moves + 1
    return moves
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One count check with a fixed-size array and one scan.

    Edge cases

    • Equal strings: 0.
    • Reversed, as in "ABC" and "CBA": 2. Only the last character can stay.
    • Different lengths or letters: -1.
    I've built my logic, show the code

    Java

    class Solution {
        public int transform(String a, String b) {
            if (a.length() != b.length()) return -1;
            int[] count = new int[256];
            for (int k = 0; k < a.length(); k++) { count[a.charAt(k)]++; count[b.charAt(k)]--; }
            for (int c : count) if (c != 0) return -1;      // different letters: impossible
            int moves = 0;
            for (int i = a.length() - 1, j = b.length() - 1; i >= 0; i--) {
                if (a.charAt(i) == b.charAt(j)) j--;          // this character can stay where it is
                else moves++;                                 // it must be picked up and put at the front
            }
            return moves;
        }
    }

    C++

    class Solution {
    public:
        int transform(string a, string b) {
            if (a.size() != b.size()) return -1;
            int count[256] = {0};
            for (size_t k = 0; k < a.size(); k++) { count[static_cast<unsigned char>(a[k])]++; count[static_cast<unsigned char>(b[k])]--; }
            for (int c : count) if (c != 0) return -1;      // different letters: impossible
            int moves = 0;
            for (int i = static_cast<int>(a.size()) - 1, j = static_cast<int>(b.size()) - 1; i >= 0; i--) {
                if (a[i] == b[j]) j--;                        // this character can stay where it is
                else moves++;                                 // it must be picked up and put at the front
            }
            return moves;
        }
    };

    Python

    class Solution:
        def transform(self, a: str, b: str) -> int:
            if sorted(a) != sorted(b):
                return -1                                     # different letters: impossible
            moves, j = 0, len(b) - 1
            for i in range(len(a) - 1, -1, -1):
                if a[i] == b[j]:
                    j -= 1                                    # this character can stay where it is
                else:
                    moves += 1                                # it must be picked up and put at the front
            return moves

    Common mistakes

    • Scanning from the front, which matches the wrong characters.
    • Forgetting the letter-count check and returning a number for an impossible pair.
    • Counting matched characters as moves.

    Similar problems