Rotate String [Easy] — String Contains Trick

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem Statement

Given two strings s and goal, return true if s can become goal after some rotation (shifting left by k positions).

Input: s="abcde", goal="cdeab"true
Input: s="abcde", goal="abced"false

Intuition

Any rotation of s is a substring of s + s. Check len(s) == len(goal) and goal in (s+s).


Solutions

C++

bool rotateString(string s, string goal) {
    return s.size()==goal.size() && (s+s).find(goal)!=string::npos;
}

Java

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

JavaScript

var rotateString = function(s, goal) {
    return s.length===goal.length && (s+s).includes(goal);
};

Python

def rotateString(s: str, goal: str) -> bool:
    return len(s) == len(goal) and goal in s + s

Complexity

  • Time: O(n²) naïve; O(n) with KMP
  • Space: O(n) for concatenation

Note

Use KMP or str.find (Boyer-Moore Horspool internally in most implementations) for true O(n).

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro