Check if one string is Rotation of another string

Objective: Write an algorithm to check if one string is Rotation of another string. This question has been asked in the Amazon interview.

Example:

Input Strings : 'sumitjain' and 'tjainsumi'
Output : true

Input String : 'Jaain' and 'ainJ'
Output: false

Input: Two Strings

Output: True or false based on whether strings are rotation of each other.

Approach:

  • Make a new String by appending the appending the first string with itself
  • Check if second string is sub string of new String
Check if one string is Rotation of another string
Check if one string is Rotation of another string

Complete Code:

public class RotatedArray {
public boolean isRotated(String s1, String s2){
if(s1.length()!=s2.length()){
return false;
}
String sAdd = s1 + s1;
if(sAdd.contains(s2)){
return true;
}else{
return false;
}
}
public static void main(String arg[]){
String s1 = "sumitjain";
String s2 = "tjainsumi";
RotatedArray r = new RotatedArray();
System.out.println("Is '" + s1 + "' and '" + s2 + "' are rotated?? : " + r.isRotated(s1, s2));
}
}

view raw
RotatedArray.java
hosted with ❤ by GitHub

Output:

Is 'sumitjain' and 'tjainsumi' are rotated?? : true