Taro Logo

Rotate String

#3 Most AskedEasy
0 views
Topics:
Strings

Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

A shift on s consists of moving the leftmost character of s to the rightmost position.

  • For example, if s = "abcde", then it will be "bcdea" after one shift.

Example 1:

Input: s = "abcde", goal = "cdeab"
Output: true

Example 2:

Input: s = "abcde", goal = "abced"
Output: false

Constraints:

  • 1 <= s.length, goal.length <= 100
  • s and goal consist of 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. What are the length constraints for the strings `s` and `goal`?
  2. Can `s` and `goal` be empty strings, and if so, what should the expected output be?
  3. Are the strings case-sensitive, or should we treat uppercase and lowercase letters as equivalent?
  4. What character set should we expect? Are we limited to standard ASCII, or do we need to support Unicode and multi-byte characters like emojis?
  5. Is there any restriction on using additional memory, or is $O(N)$ extra space acceptable?

Brute Force Solution

Approach

Imagine you have a word written on a strip of paper and you want to see if you can twist it into another specific word. The brute force strategy involves physically trying every single way to shift the letters around one by one and checking if it matches the target word.

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

  1. Take your starting word and shift the very first letter all the way to the end of the word.
  2. Check if this newly shifted word matches your target word completely.
  3. If it does not match, take the new word and shift its first letter to the end again.
  4. Repeat this process of shifting the first letter to the end and checking for a match.
  5. Keep doing this until you have tried every single possible shift for the word.
  6. If at any point the shifted word matches the target word, you have found your answer.
  7. If you finish trying all possible shifts and none of them match, then you know it is impossible to transform the first word into the second.

Code Implementation

def rotate_string(source_string, target_string):
    # Handle edge case where strings differ in length because shifts cannot change length
    if len(source_string) != len(target_string):
        return False

    # Handle empty strings which are technically valid rotations of each other
    if not source_string and not target_string:
        return True

    current_string = source_string

    # Iterate through every possible shift position up to the length of the string
    for shift_index in range(len(source_string)):
        # Check current rotation against target to avoid missing any valid shift state
        if current_string == target_string:
            return True

        current_string = current_string[1:] + current_string[0]

    # Exhausted all possible rotations without finding a match so return false
    return False

Big(O) Analysis

Time Complexity
O(n²) – For a string of length n, the brute force approach physically shifts the first letter to the end up to n times. During each of the n shift operations, the algorithm compares the newly formed string of length n against the target word character by character. This means we perform n comparisons for each of the n possible shifts. Consequently, the total operations approximate n multiplied by n, which simplifies to O(n²).
Space Complexity
O(N) – The simulation approach involves generating and storing shifted versions of the starting string during each iteration of the brute force process. Specifically, each shifted word requires allocating a new string of length N to compare against the target. As the algorithm tries all possible shifts up to N times, the temporary string representations consume extra memory proportional to the input size. Therefore, the auxiliary space complexity scales linearly with N, where N is the length of the string.

Optimal Solution

Approach

Instead of physically shifting letters around one by one, the optimal approach uses a clever text duplication trick to instantly reveal if the target word is a valid rotation. It checks a simple pattern matching condition that covers every possible shift combination in one go.

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

  1. Take the first word and write it down twice, right next to itself, to create a much longer double-word.
  2. Think of this double-word as containing every single possible rotation that can ever be formed from the original word.
  3. Take the target word you are trying to match.
  4. Look closely inside the double-word to see if the target word appears anywhere inside it as a continuous block.
  5. If the target word is found hidden inside the double-word, then the rotation is successful and possible.
  6. If the target word cannot be found anywhere inside the double-word, then no matter how many times you shift it, it will never match.
  7. Make sure that both the original word and the target word are the exact same length, because if they are different sizes, a rotation is never possible regardless of the content.

Code Implementation

def rotate_string(source_string, target_string):

    # Different lengths can never be valid rotations of one another.
    if len(source_string) != len(target_string):
        return False

    # Doubling the string contains every single possible rotation sequence.
    double_source = source_string + source_string

    # Checking containment reveals if the target matches any valid shift.
    return target_string in double_source

Big(O) Analysis

Time Complexity
O(n) – Letting n be the length of the string, the first step concatenates the original string with itself, which takes linear time proportional to n. The main operation then searches for the target string of length n inside this doubled string of length 2n. Standard substring search algorithms such as KMP or optimized library substring checks perform this matching in linear time proportional to n. Therefore, the total operations scale directly with n, simplifying the final time complexity to O(n).
Space Complexity
O(N) – The auxiliary space is driven by the text duplication step, which concatenates the first word with itself to form a new double-word of length 2N, where N is the length of the original string. This process explicitly allocates extra memory for the doubled string to cover all possible rotation combinations. Depending on the underlying programming language and substring search implementation, auxiliary data structures or temporary buffers proportional to size N may also be utilized during the pattern matching check. Consequently, as the input size N increases, the extra memory required scales linearly, resulting in a space complexity of O(N).

Edge Cases

Empty strings for both s and goal
How to Handle:
Both lengths are zero, and string concatenation or direct comparison successfully returns true.
Strings of unequal lengths
How to Handle:
A preliminary length check immediately returns false since rotation cannot alter string length.
Single-character strings that match or do not match
How to Handle:
Direct equality or single shift check handles this correctly without index out of bounds errors.
Strings with all identical characters like aaa and aaa
How to Handle:
The concatenation approach s plus s contains goal, correctly evaluating to true.
Maximum length strings up to constraint limits
How to Handle:
Using efficient substring search or KMP algorithm ensures optimal time complexity without exceeding limits.
Strings that are anagrams but not valid rotations
How to Handle:
The shift verification ensures character order is strictly preserved, returning false.
Null inputs for s or goal
How to Handle:
Standard null checks at the beginning of the function prevent null pointer exceptions and handle gracefully.
Unicode or special character strings
How to Handle:
Language native string concatenation and search functions correctly handle multi-byte Unicode code points.
0/5 completed