Rotate String LeetCode Solution

Difficulty Level Easy
Frequently asked in Adobe Amazon Apple Bloomberg Cisco Goldman Sachs Google LinkedIn Microsoft Oracle Yahoo
String ZoomViews 6056

Problem Statement

Rotate String LeetCode Solution – Given two strings s and goal, return true if and only ifcan become goal after some number of shifts on s.

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

Approach

Idea:

We add s+s like in the first example abcde+abcde= abcdeabcde and clearly, we can see it contains all the left shift os s and simply we can return the contains method from it.

Code

Java Program of Rotate String:

class Solution {
public boolean rotateString(String s, String goal) 
{
    return (s.length()==goal.length() && (s+s).contains(goal));
}
}

Python Program of Rotate String:

class Solution :
    def  rotateString(self, s,  goal) :
        return (len(s) == len(goal) and  goal in (s + s) )

Complexity Analysis for Rotate String LeetCode Solution

Time Complexity

The time complexity of the above code is O(1) because we don’t do any traversing.

Space Complexity

The space complexity of the above code is O(1) because no matter how large our input is, the output always takes the same amount of space because of the way that it’s structured. Also, the output only needs to return true or false so the output itself isn’t derived by traversing anything.

Translate »