Check if a String Is a Rotation of Another

Problem

Check whether string s2 is a rotation of string s1 (same length, same characters in rotated order).

Input:  s1 = "waterbottle", s2 = "erbottlewat"
Output: true

Python Solution

def is_rotation(s1, s2):
    if len(s1) != len(s2):
        return False
    return s2 in (s1 + s1)

C++ Solution

bool isRotation(string s1, string s2) {
    if (s1.size() != s2.size()) return false;
    string doubled = s1 + s1;
    return doubled.find(s2) != string::npos;
}

Java Solution

class Solution {
    public boolean isRotation(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
        return (s1 + s1).contains(s2);
    }
}

Complexity

Time: O(n) average with an efficient substring search (like KMP internally); a naive substring search makes it O(n²) worst case, where n is the string length. Space: O(n) for the doubled string.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.