
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if Strings are Rotations of Each Other in JavaScript
To check if strings are rotations of each other or not, it means that two strings can be rotated to either the right or left direction to obtain the other string. In the right rotation characters of the string shift to their following index and for the zeroth index, it takes the character of the last index assuming the string is in a circle. Left rotation is similar to right rotation but in the opposite direction.
In this article We are having two strings and we have to write a JavaScript program to check whether by rotating the characters of the string we can get another or not.
Examples
Input: string1: "abcdef" string2: "cdefab" Output: Yes
Explanation: We can rotate the first string two times toward the left side and get the second string. String1 after the first rotation will be "bcdefa" and in the next rotation, it will be the same as the second string.
Input: String1: "abcdef" String2: "bcadef" Output: No
Explanation: The maximum number of rotations that we can rotate a string or array without getting the original string is equal to the length of the given string or the array. Here, after six rotations we cannot get the string2 from the string1, proving it's impossible to make both strings equal after the maximum number of rotations.
Checking if strings are rotations of each other or not
Following are the different approaches to check if strings are rotations of each other or not
Naive Approach
In the naive method, the first string is rotated one character at a time by moving its first character to the end. After each rotation, the modified string is compared with the second string. This process is repeated for all possible rotations of the first string.
If the rotated version matches the second string at any step, the two strings are rotations of each other. If no match is found after all rotations, they are not rotations.
Example
The example is in JavaScript to check if strings are rotations of each other or not
// function to rotate the string in the left direction function left_rotate(str){ // splitting the string and then again joining back str = str.substr(1) + str.substr(0,1); return str; } // function to check if one string is equal to another after certain rotations function check(str1, str2){ // checking the size of both strings if(str1.length != str2.length){ return false; } var k = str1.length while(k--){ if(str1 == str2){ return true; } str1 = left_rotate(str1); } return false; } // defining the strings var str1 = "abcdef" var str2 = "cdefab" console.log("The given strings are " + str1 + " and " + str2); // calling the function if(check(str1,str2)){ console.log("Yes, we can obtain the second string from the given string by rotating it."); } else{ console.log("No, we cannot obtain the second string from the given string by rotating it."); } // defining the strings str1 = "abcdef" str2 = "bacdef" console.log("The given strings are " + str1 + " and " + str2); // calling the function if(check(str1,str2)){ console.log("Yes, we can obtain the second string from the given string by rotating it."); } else{ console.log("No, we cannot obtain the second string from the given string by rotating it."); }
Output
The given strings are abcdef and cdefab Yes, we can obtain the second string from the given string by rotating it. The given strings are abcdef and bacdef No, we cannot obtain the second string from the given string by rotating it.
Time and Space Complexity:
The time complexity of the above code is O(N*N), where N is the size of the given string.
The space complexity of the above code is O(1), as we are not using any space.
Queue-Based Comparison
In the queue-based comparison approach, each string is treated as a queue of characters. Starting with the first string, its characters are rotated by removing the first character and appending it to the end. After each rotation, the modified string is compared to the second string.
This process continues until the two strings match, indicating they are rotations of each other or all possible rotations are exhausted without a match. If no match is found, the strings are not rotated around each other.
Example
function areRotationsUsingQueue(str1, str2) { if (str1.length !== str2.length) { return false; } const queue1 = str1.split(''); const queue2 = str2.split(''); for (let i = 0; i < str1.length; i++) { // Rotate the first queue queue1.push(queue1.shift()); // Check if the rotated version matches the second queue if (queue1.join('') === queue2.join('')) { return true; } } return false; } // Example usage console.log(areRotationsUsingQueue("ABCD", "CDAB")); console.log(areRotationsUsingQueue("ABCD", "ACBD"));
Output
areRotationsUsingQueue("ABCD", "CDAB") => true
areRotationsUsingQueue("ABCD", "ACBD") => false
Time and Space complexity:
O(n^2), where n is the length of the string because rotation and comparison take O(n) for each rotation and O(n), for the queue.KMP Algorithm
Using the Knuth-Morris-Pratt (KMP) substring search algorithm, the first string is concatenated with itself to account for all possible rotations. The second string is then checked as a potential substring within this doubled version of the first string using the KMP algorithm.
If the second string is found as a substring, it confirms that the two strings are rotations of each other. The KMP algorithm ensures efficient searching by avoiding redundant comparisons during the substring check. If the second string is not found, the strings are not rotations.
Example
In this program we will use the KMP algorithm to find the rotations, let us move to the code.
// function to check if one string is equal to another using KMP function check(str1, str2){ // checking the size of both strings if(str1.length != str2.length){ return false; } var len = str1.length; // create lps that will hold the longest prefix var lps = Array.from({length: len}, (_, i) => 0); // length of the previous longest prefix suffix var len_p = 0; var i = 1; lps[0] = 0; // the loop calculates lps[i] for i = 1 to n-1 while (i < len) { if (str1.charAt(i) == str2.charAt(len_p)) { lps[i] = ++len_p; i++; } else { if (len_p == 0) { lps[i] = 0; i++; } else { len_p = lps[len_p - 1]; } } } i = 0; // match from that rotating point for(var k = lps[len - 1]; k < len; k++) { if (str2.charAt(k) != str1.charAt(i++)){ return false; } } return true; } // defining the strings var str1 = "abcdef" var str2 = "cdefab" console.log("The given strings are " + str1 + " and " + str2); // calling the function if(check(str1,str2)){ console.log("Yes, we can obtain the second string from the given string by rotating it."); } else{ console.log("No, we cannot obtain the second string from the given string by rotating it."); } // defining the strings str1 = "abcdef" str2 = "bacdef" console.log("The given strings are " + str1 + " and " + str2); // calling the function if(check(str1,str2)){ console.log("Yes, we can obtain the second string from the given string by rotating it."); } else{ console.log("No, we cannot obtain the second string from the given string by rotating it."); }
Output
The given strings are abcdef and cdefab Yes, we can obtain the second string from the given string by rotating it. The given strings are abcdef and bacdef No, we cannot obtain the second string from the given string by rotating it.
Time and Space Complexity:
For the above program, both the time and space complexity are O(N). We have used the extra space to store the values in lps array.
Comparison of Methods
Method | Time Complexity | Space Complexity | Comment |
---|---|---|---|
Naive Method | O(n^2) | O(n) | Simple to implement but inefficient for large strings. |
Queue-Based Comparison | O(n^2) | O(n) | Efficient for large strings each string is treated as a queue of characters. |
KMP Algorithm | O(n) | O(m) | Efficient for large strings; uses substring matching. |
Conclusion
In this tutorial, we examined three methods for checking if one string can be obtained by rotating another. The naive method is simple but inefficient for large strings with O(n^2) time complexity. The queue-based comparison improves efficiency but still has quadratic time complexity. The most efficient approach is the KMP algorithm, which offers O(n) time complexity and O(m) space complexity, making it ideal for large strings. For small strings, the naive method is sufficient, but for large datasets, KMP is the best choice. Thus, the KMP algorithm stands out as the optimal solution for performance.
Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.