PHP Program for Minimum Rotations Required to get the Same String


In this problem, we need to achieve the same string by performing the rotations of the string and need to count rotations.

There can be different ways to solve the problem, but here we will learn some best approaches in PHP. The first approach uses the rotational substring, and another approach divides the string into two parts from the particular index.

Problem statement − We have a string str containing n characters. We have to find the minimum rotations of string we should perform to achieve the same string again.

Sample examples

Input

str = "bcbc";

Output

2

Explanation − In the first rotation string becomes ‘cbcb’, and in the second rotation string becomes ‘bcbc’. So, we require total 2 rotations to get the original string again.

Input

 str = "opqropqr"

Output

4

Explanation − When we perform 4 left rotations, we can achieve the original string.

Input

 str = ‘lnm’

Output

3

Explanation − The string doesn’t contain any repeated string. So, we need to perform the total rotations equal to the string length.

Approach 1

In this approach, we take the substring of length equal to the str string’s length from each index and check whether it is equal to the str string. If yes, the answer to the problem is p.

Algorithm

Step 1 − Use the ‘.’ Operator to combine str string to itself.

Step 2 − Make the total ‘len’ number of iterations starting from index 1.

Step 3 − Use the substr() method, and pass parameters. It takes a string as a first parameter, starting index as a second parameter, and the length of the substring as a third parameter.

Step 4 − Return the current index value if the str and resultant string are equal.

Step 5 − If we don’t find string rotation, return ‘len’ at last.

Example

<?php
function totalRotations($str){
    // Merge the string
    $tmp = ($str . $str);
    $len = strlen($str);
    // iterate the string
    for ($p = 1; $p <= $len; $p++) {
        // get a substring
        $substring = substr($tmp, $p, $len);
        // return $i, if the substring matches with the original string
        if ($str == $substring)
            return $p;
    }
    return $len;
}
$str = "bcbc";
echo "The total numbers of rotations required to get the original string are: ";
echo totalRotations($str), "\n";
?>

Output

The total numbers of rotations required to get the original string are: 2

Time complexity− O(N^2) to find the substring inside the loop.

Space complexity − O(N) to store the substring.

We learned to find the minimum rotations required to get the same string. Also, users can solve the problem in which we need to find the total number of right rotations required to get the original string for more practice.

Updated on: 14-Aug-2023

43 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements