Interview Questions- Part-11

string rotation - Attempt 1

				
					// String Rotation
// Question --> Verify if the given string is any of the string rotation of original string
// For example --> 'lohel' is one of the string rotation of 'hello'
// But 'heoll' is not one of the string rotation of 'hello'

// take the last character ..make it first
// loop rest of characters to append.. make this string as new string
// o+ hell -->ohell
// l+ ohel -->lohel
// l+lohe  -->llohe
// e+lloh  -->elloh
// h+ello  -->hello .. the last one will be back to original string

const isStringRotation = (originalStr, inputStr) => {
  let length = inputStr.length - 1;
  let temp;
  for (let j = 0; j <= length - 1; j++) {
    let i = 0;
    temp = inputStr[length];
    while (i < length) {
      temp += inputStr[i];
      i++;
    }
    //console.log(temp);
    inputStr = temp;
    if (inputStr === originalStr) return true;
  }
  return false;
};

console.log(isStringRotation("hello", "elloh")); //true
console.log(isStringRotation("hello", "heoll")); //false
				
			

string rotation - Attempt 2

				
					//Find the index of the input string 
// for example if input string is "llohe"
//index of l in origical string will be 2 and 3
//Now loop on the indexes - 2 and 3
//construct new string from the originalStr.. based on the index ...
//so here for index 2 
//hello--> llo + he --> llohe (new string)
//compare new string === input string..which is equal,,so break it by returning true

const isStringRotation = (originalStr, inputStr) => {
  if (originalStr.length !== inputStr.length) return false;
  let output = false;
  let firstletter = inputStr[0];
  let indexes = originalStr
    .split("")
    .map((v, i) => {
      if (originalStr[i] === firstletter) {
        return i;
      }
    })
    .filter((y) => y >= 0);

  for (let i = 0; i < indexes.length; i++) {
    console.log(indexes[i]);
    const newString =
      originalStr.substring(indexes[i], originalStr.length) + originalStr.substring(0, indexes[i]);
    console.log(newString);
    if (newString === inputStr) {
      output = true;
      break;
    }
  }
  return output;
};

console.log(isStringRotation("hello", "ohell")); //true
console.log(isStringRotation("hello", "elloz")); //false
				
			

Leave a Comment