Taro Logo

Can Convert String in K Moves

#14 Most AskedMedium
0 views
Topics:
Strings

Given two strings s and t, your goal is to convert s into t in k moves or less.

During the ith (1 <= i <= k) move you can:

  • Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.
  • Do nothing.

Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.

Remember that any index j can be picked at most once.

Return true if it's possible to convert s into t in no more than k moves, otherwise return false.

Example 1:

Input: s = "input", t = "ouput", k = 9
Output: true
Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.

Example 2:

Input: s = "abc", t = "bcd", k = 10
Output: false
Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.

Example 3:

Input: s = "aab", t = "bbb", k = 27
Output: true
Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.

Constraints:

  • 1 <= s.length, t.length <= 10^5
  • 0 <= k <= 10^9
  • s, t contain only lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are the input strings `s` and `t` guaranteed to be of the exact same length?
  2. What character set are we working with? Should I assume only lowercase English letters (a-z), or could there be uppercase letters or other ASCII characters?
  3. Could you clarify the rule 'you can apply each shift distance at most once across all moves'? Does this mean if we shift a character by distance $d$, we cannot use distance $d$ for any other character in `s`, but we *can* shift multiple characters if their required shift distances are distinct?
  4. What happens if $k$ is very large (e.g., greater than 26)? Can shift distances wrap around past 'z' to 'a' (e.g., shifting 'z' forward by 1 gives 'a'), or are shift distances strictly cumulative/capped?
  5. What should be returned if `s` and `t` are already identical? Does that require 0 moves ($k e 0$), or is it considered trivially true?

Brute Force Solution

Approach

The problem asks whether we can transform one string into another by shifting each character at most once, using moves numbered from 1 to k. Each move allows shifting a chosen character by that move's index. We track how many times each shift value modulo 26 is needed and verify that the required move numbers do not exceed the given limit.

Here's how the algorithm would work step-by-step:

  1. Check if the lengths of the two strings are equal, returning false immediately if they differ.
  2. Initialize an array of size 26 to keep track of how many times each shift distance from 1 to 25 has been used.
  3. Iterate simultaneously through both strings to compute the positive circular shift needed for each character position.
  4. Calculate the specific move index required for the current shift based on how many times that shift distance has already occurred.
  5. Return false if the required move index exceeds the maximum allowed moves.
  6. Return true after processing all characters if every required shift can be completed within the move limit.

Code Implementation

def can_convert_string(source_str: str, target_str: str, max_moves: int) -> bool:
    # Return false immediately if the string lengths do not match
    if len(source_str) != len(target_str):
        return False

    shift_counts = [0] * 26
    # Calculate required shifts for each character and check if within max moves
    for source_char, target_char in zip(source_str, target_str):
        shift_needed = (ord(target_char) - ord(source_char)) % 26
        if shift_needed > 0:
            # Determine the actual move number required for this shift
            total_shift_move = shift_needed + shift_counts[shift_needed] * 26
            if total_shift_move > max_moves:
                return False
            shift_counts[shift_needed] += 1

    # If all needed shifts can be performed within the limit, return true
    return True

Big(O) Analysis

Time Complexity
O(n) – We iterate through the input strings of length n once, performing constant-time arithmetic operations for each pair of characters.
Space Complexity
O(1) – The algorithm only uses a fixed-size array of 26 integers to store shift frequencies, requiring constant additional space.

Optimal Solution

Approach

Instead of checking every single possible way to match the letters, we can use a tally sheet to count how many times each specific shift distance is needed. By looking at the distance between corresponding letters in both words, we determine if any shift distance is requested too many times within the allowed move limit.

Here's how the algorithm would work step-by-step:

  1. Compare the starting word and the target word letter by letter, noting how many steps forward in the alphabet are required to transform each letter into its partner.
  2. Keep a tally of how many times each specific shift distance appears.
  3. Watch out for wrap-arounds, meaning if you need a shift distance that has already been used a certain number of times, you will need to take an extra full cycle around the alphabet to use that same distance again.
  4. Calculate the maximum number of moves required for any single shift distance, factoring in those extra full cycles when a distance is repeated.
  5. Compare that maximum requirement against the total move limit to decide if the transformation is possible within the rules.

Code Implementation

def can_convert_string(source_string, target_string, move_limit):
    if len(source_string) != len(target_string):
        return False

    shift_frequency_tally = [0] * 26

    for source_char, target_char in zip(source_string, target_string):
        source_ascii = ord(source_char)
        target_ascii = ord(target_char)

        if source_ascii <= target_ascii:
            shift_distance = target_ascii - source_ascii
        else:
            shift_distance = (26 - source_ascii) + target_ascii

        if shift_distance > 0:
            # We track each shift distance to ensure no single shift is over-requested.
            shift_frequency_tally[shift_distance] += 1

    maximum_moves_required = 0

    for shift_distance in range(1, 26):
        frequency_count = shift_frequency_tally[shift_distance]

        if frequency_count > 0:
            # Wrap-arounds require full alphabet cycles when reusing the same shift distance.
            total_distance_for_shift = (frequency_count - 1) * 26 + shift_distance

            if total_distance_for_shift > maximum_moves_required:
                maximum_moves_required = total_distance_for_shift

    # Compare the max requirement against the move limit to decide if transformation works.
    return maximum_moves_required <= move_limit

Big(O) Analysis

Time Complexity
O(n) – To evaluate the transformation, we iterate through the characters of the starting and target words of length n side-by-side to calculate shift distances and update our tally sheet. For each character processed, we perform constant time arithmetic and frequency updates. Across all n characters, this requires a linear number of operations that approximate a direct pass of n steps, which simplifies to O(n).
Space Complexity
O(1) – To keep a tally of how many times each specific shift distance appears as described in step 2, we use a fixed-size frequency array or hash map of size 26 to cover all possible alphabet shift distances. Because the alphabet size is constant and does not grow with the input string length N, the auxiliary memory remains completely independent of N. Therefore, the total extra memory simplifies to constant space or O(1).

Edge Cases

Strings s and t are already identical
How to Handle:
The shift required for each character is zero, which requires zero moves and fits within any k >= 0.
Shift requirement exceeds 26 for multiple characters reusing the same shift value
How to Handle:
We use a frequency array to track the occurrences of each required shift distance modulo 26, ensuring that any duplicate shift values require additional cycles of 26 moves.
Strings have different lengths
How to Handle:
We immediately return false since a string cannot be transformed into another of a different length.
k is very small while total required shifts are large
How to Handle:
The maximum required moves for any shift value d is calculated as (count - 1) * 26 + d, and if this exceeds k, we return false.
All characters in s need the exact same forward shift
How to Handle:
The frequency map will register multiple requirements for the same shift value, correctly increasing the necessary move count by multiples of 26.
Maximum length strings with large k
How to Handle:
An O(N) single-pass algorithm using a fixed-size frequency array scales efficiently and runs well within time limits.
Zero available moves when strings differ
How to Handle:
If k is zero and any character in s does not match t, the algorithm immediately catches the mismatch and returns false.
Z to A wrapping shifts requiring careful arithmetic
How to Handle:
The forward shift distance is calculated using modulo 26 arithmetic as (target_char - source_char + 26) % 26.
0/257 completed