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:

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.