Coding Challenge Day-5: Problem 2: Check if one string is a rotation of another

Hello! So I’m doing a 30 day coding challenge where I solve a few questions everyday and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 5: Problem 2! Be sure to post your answers, queries etc in the comments!!

Problem: Write a function isSubstring which checks if one word is a substring of another. Given two string s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring

Sample input: String s1= “waterbottle”;
String s2= “erbottlewat”;
Output: String erbottlewat is a rotation of waterbottle

Sample input: String s1= “lockdown”;
String s2= “downlock”;
Output: String downlock is a rotation of lockdown

Sample input: String s1= “waterbottle”;
String s2= “bottlew”;
Output: String bottlew is not a rotation of waterbottle


  • logic isSubstring
    • start by finding the length of strings s1 and s2
    • run a loop through length of string s1
    • if any character of s1 matches the first character of s2 then run a loop through entire length of s2 to check if the following character of s1 also match that of s2 if yes then return true else return false
  • logic of is_rotation
    • if length of string s1= length of string s2 then
    • then initialize substring s with s1s1 and send to isSubstring for comparison
package string;
// check rotation 
public class Program005_isrotation {
	public static boolean is_rotation(String s1, String s2){
			String s= s1+s1;
			if(isSubstring(s, s2))
				return true;
		return false;
	public static boolean isSubstring (String s1, String s2){
		int l1= s1.length();
		int l2= s2.length();
		int count=0;
		for(int i=0; i<l1; i++){
				for(int j=0; j<l2; j++){
					return true;
		return false;
	public static void main (String [] args){
		String s1= "waterbottle";
		String s2= "erbottlewat";
			System.out.printf("String %s is a rotation of %s", s2,s1);
			System.out.printf("String %s is not a rotation of %s", s2,s1);


Download Code

1. Cracking the Coding Interview (by Gayle Laakmann McDowell)

Happy Learning!!

Leave a Reply


Your email address will not be published.

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

%d bloggers like this: