- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum rotations required to get the same string in C++
Problem statement
Given a string, we need to find the minimum number of rotations required to get the same string
Example
If input string is “bbbbb” then minimum 1 rotation is required
Algorithm
1. Initialize result = 0 2. Make a temporary string equals to original string concatenated with itself. 3. Take the substring of temporary string of size same as original string starting from second character i.e. index 1 4. Increment the counter 5. Check whether the substring becomes equal to original string. If yes, then break the loop. Else go to step 2 and repeat it from the next index
Example
#include <bits/stdc++.h> using namespace std; int getRotationCount(string str) { string temp = str + str; int n = str.length(); for (int i = 1; i <= n; ++i) { string sub = temp.substr(i, str.size()); if (str == sub) { return i; } } return n; } int main() { string str = "bbbbb"; cout << "Rotation count = " << getRotationCount(str) << endl; return 0; }
When you compile and execute above program. It generates following output
Output
Rotation count = 1
- Related Articles
- Minimum swaps required to make a binary string alternating in C++
- Minimum Players required to win the game in C++
- Minimum number of operations required to sum to binary string S using C++.
- C++ code to find the number of dial rotations to print a string
- Minimum Initial Energy Required To Cross Street in C++
- Minimum operations required to remove an array in C++
- Program to find minimum changes required for alternating binary string in Python
- Minimum positive integer required to split the array equally in C++
- Minimum operations required to make all the array elements equal in C++
- Minimum edges required to add to make Euler Circuit in C++
- Minimum String in C++
- Program to find minimum number of bricks required to make k towers of same height in Python
- Find minimum steps required to reach the end of a matrix in C++
- Minimum Swaps required to group all 1’s together in C++
- Minimum number of swaps required to sort an array in C++

Advertisements