![]() |
In this article, we are given a string str, our task is to find the minimum number of rotations required to get the same string using JavaScript. Example 1: Input: str = "geeks" Example 2: Input: str = "abc" Approach 1: Evaluating Substrings after Concatenating string with itself (with auxiliary space)
Example: This example shows the implementation of the above appraoch.
Output Minimum Number of Rotations Required are: 5 Minimum Number of Rotations Required are: 1 Time Complexity: O(n2) Auxiliary Space: O(n) Approach 2: Partitioning & Concatenating both Left and Right substring (without auxiliary space)In the previous approach, we were using an auxiliary variable ‘temp’ which was increasing our space complexity but we can also solve this problem without using any temporary variable as extra space. We will traverse the original string and at each position we partition it and concatenate both the left substring and the right substring and then check whether it is equal to original string. If yes, then return the value of res and break the loop but if res remains 0 then we have to return the size of original string. Example: This example shows the implementation of the above appraoch.
Output Minimum Number of Rotations Required are: 5 Minimum Number of Rotations Required are: 1 Time Complexity: O(n2) Auxiliary Space: O(1) Using Regular ExpressionsUsing regular expressions, the input string is concatenated with itself. A regex pattern is created to match the repeated string. The matched length of the repeated substring determines the minimum rotations needed to get the same string. Example: In this example the function minRotationsUsingRegExp calculates the minimum number of rotations needed to return to the original string using regex.
Output Minimum Number of Rotations Required are:5 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |