Given two strings, s1 and s2, write code to check if s2 is a rotation of s1

Tailwind

This is very simple coding interview question to check your knowledge on linear search algorithm implementation.

You have given two strings.

For example:

Input1: ‘erbottlewat’,

Input2: ‘waterbottle’

You have to write function which will check if “waterbottle” input string is a rotation of “erbottlewat” string or not. So we can see if we start reading from w in string erbottlewat we can recreate waterbottle that means “waterbottle” is a rotation of “erbottlewat”.

So if we write erbottlewat two times we can easily see that waterbottle is the rotation of erbottlewat.

Repeated String: erbottlewaterbottlewat

After we have repeated string we can easily check if input string 2 does exist within repeated string or not.

Now Let’s put that logic in actual code:

const stringRotation = (inputStr1, inputStr2) => {
  if (inputStr1.length === inputStr2.length) {
    let repeatedStr = inputStr1 + inputStr1;
    if (repeatedStr.indexOf(inputStr2) > -1) {
      return true;
    }
  }
  return false; 
}

console.log(stringRotation('erbottlewat', 'waterbottle'));