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));
}
}

Output:

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

3 thoughts on “Check if one string is Rotation of another string”

  1. hi….here rotation of the is ‘sumitjain’ not ‘tjainsumi’… u mean left Rotate–> ‘tjainimus’ right Rotate–>’niajtsumi’…neither of these is not the answer ………..please give valid explanantion of rotating the string..

    Reply
  2. Below is a better approach

    public class CheckingIfStringIsRotationOfOther {

    public static void main(String[] args) {

    String input = “sumitjain”, output = “tjainsumi”;

    if(function(input, output)){
    System.out.println(“True”);
    }
    else
    System.out.println(“false”);

    }

    public static boolean function(String input, String output) {
    if(input.length() != output.length()) return false;

    int upper = 0 ;
    for(int i = 0 ; i < input.length();i++){
    if(input.substring(i).equals(output.substring(0,output.length() – i))){
    upper = i ; break;
    }
    }

    if(upper == 0) return true;
    if(input.substring(0,upper).equals(output.substring(output.length() – upper,output.length())))
    return true;

    return false;
    }
    }

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.