|
| 1 | +class BoothsAlgorithm: |
| 2 | + """ |
| 3 | + Booth's Algorithm finds the lexicographically minimal rotation of a string. |
| 4 | +
|
| 5 | + Time Complexity: O(n) - Linear time where n is the length of input string |
| 6 | + Space Complexity: O(n) - Linear space for failure function array |
| 7 | +
|
| 8 | + For More Visit - https://en.wikipedia.org/wiki/Booth%27s_multiplication_algorithm |
| 9 | + """ |
| 10 | + |
| 11 | + def find_minimal_rotation(self, string: str) -> str: |
| 12 | + """ |
| 13 | + Find the lexicographically minimal rotation of the input string. |
| 14 | +
|
| 15 | + Args: |
| 16 | + string (str): Input string to find minimal rotation. |
| 17 | +
|
| 18 | + Returns: |
| 19 | + str: Lexicographically minimal rotation of the input string. |
| 20 | +
|
| 21 | + Raises: |
| 22 | + ValueError: If the input is not a string or is empty. |
| 23 | +
|
| 24 | + Examples: |
| 25 | + >>> ba = BoothsAlgorithm() |
| 26 | + >>> ba.find_minimal_rotation("baca") |
| 27 | + 'abac' |
| 28 | + >>> ba.find_minimal_rotation("aaab") |
| 29 | + 'aaab' |
| 30 | + >>> ba.find_minimal_rotation("abcd") |
| 31 | + 'abcd' |
| 32 | + >>> ba.find_minimal_rotation("dcba") |
| 33 | + 'adcb' |
| 34 | + >>> ba.find_minimal_rotation("aabaa") |
| 35 | + 'aaaab' |
| 36 | + """ |
| 37 | + if not isinstance(string, str) or not string: |
| 38 | + raise ValueError("Input must be a non-empty string") |
| 39 | + |
| 40 | + n = len(string) |
| 41 | + s = string + string # Double the string to handle all rotations |
| 42 | + f = [-1] * (2 * n) # Initialize failure function array with twice the length |
| 43 | + k = 0 # Starting position of minimal rotation |
| 44 | + |
| 45 | + for j in range(1, 2 * n): |
| 46 | + sj = s[j] |
| 47 | + i = f[j - k - 1] |
| 48 | + |
| 49 | + while i != -1 and sj != s[k + i + 1]: |
| 50 | + if sj < s[k + i + 1]: |
| 51 | + k = j - i - 1 |
| 52 | + i = f[i] |
| 53 | + |
| 54 | + if i == -1 and sj != s[k]: |
| 55 | + if sj < s[k]: |
| 56 | + k = j |
| 57 | + f[j - k] = -1 |
| 58 | + else: |
| 59 | + f[j - k] = i + 1 |
| 60 | + |
| 61 | + return s[k : k + n] |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + ba = BoothsAlgorithm() |
| 66 | + print(ba.find_minimal_rotation("bca")) # output is 'abc' |
0 commit comments