Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
C/C++ Program for Longest Increasing Subsequence
Next article icon

C++ Program for Longest subsequence of a number having same left and right rotation

Last Updated : 27 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation.

Examples:

Input: S = "100210601" 
Output: 4 
Explanation: 
The subsequence "0000" satisfies the necessary condition. 
The subsequence "1010" generates the string "0101" on left rotation and string "0101" on right rotation. Since both the rotations are same. Therefore, "1010" satisfies the condition as well. 
Therefore, the maximum length of such subsequence is 4.
Input: S = "252525" 
Output: 6 
Explanation: 
The subsequence "252525" generates the string "525252" on left rotation and string "525252" on right rotation. Since both the rotations are same. Therefore, the "252525" satisfies the required condition.

Naive Approach: The simplest approach to solve the problem is to generate all possible subsequences of the given string, and for each subsequence, check if its left rotation is equal to its right rotation. 
Time Complexity: O(2N * N) 
Auxiliary Space: O(N)
 

Efficient Approach: To optimize the above approach, the main observation is that the subsequence should either consist of a single character or should be of even length consisting of two characters alternatively.

Illustration: 
str = "2424" 
Left rotation of the string = "4242" 
Right rotation of the string = "4242" 
As we can see, since the number is of even length having two characters appearing alternately, therefore, the left and right rotation of the given number is equal.
str = "24242" 
Left rotation of the string = "42422" 
Right rotation of the string = "22424" 
As we can see, since the number is of odd length having two characters appearing alternately, therefore, the left and right rotation of the given number is not equal.


Follow the steps below to solve the problem:

  • Generate all possible two-digit numbers.
  • For each two-digit number generated, check for the alternating occurrence of both the digits in the string. Keep incrementing count to store the length of alternating subsequence for the particular combination.
  • After the entire traversal of the string, check if both the digits are equal or not. If found to be true, update count to the required answer. If both the digits are equal, then update count or count - 1 to the answer if the count is even or odd respectively.
  • Repeat the above steps for all the possible combinations and print the maximum count obtained.

Below is the implementation of the above approach:

C++
// C++ Program to implement // the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the longest subsequence // having equal left and right rotation int findAltSubSeq(string s) {     // Length of the string     int n = s.size(), ans = INT_MIN;      // Iterate for all possible combinations     // of a two-digit numbers     for (int i = 0; i < 10; i++) {         for (int j = 0; j < 10; j++) {             int cur = 0, f = 0;              // Check for alternate occurrence             // of current combination             for (int k = 0; k < n; k++) {                  if (f == 0 and s[k] - '0' == i) {                     f = 1;                      // Increment the current value                     cur++;                 }                 else if (f == 1 and s[k] - '0' == j) {                     f = 0;                      // Increment the current value                     cur++;                 }             }              // If alternating sequence is             // obtained of odd length             if (i != j and cur % 2 == 1)                  // Reduce to even length                 cur--;              // Update answer to store             // the maximum             ans = max(cur, ans);         }     }      // Return the answer     return ans; }  // Driver Code int main() {     string s = "100210601";     cout << findAltSubSeq(s);      return 0; } 

Output: 
4

 

Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time 
Auxiliary Space: O(1), as we are not using any extra space.
 

Please refer complete article on Longest subsequence of a number having same left and right rotation for more details!


Next Article
C/C++ Program for Longest Increasing Subsequence
author
kartik
Improve
Article Tags :
  • Strings
  • Pattern Searching
  • Mathematical
  • Combinatorial
  • C++ Programs
  • C++
  • DSA
  • subsequence
  • rotation
  • large-numbers
Practice Tags :
  • CPP
  • Combinatorial
  • Mathematical
  • Pattern Searching
  • Strings

Similar Reads

  • C++ Program for Left Rotation and Right Rotation of a String
    Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d <= n)Right (Or clockwise) rotate the given string by d elements (where d <= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output :
    5 min read
  • C++ Program to Minimize characters to be changed to make the left and right rotation of a string same
    Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc
    3 min read
  • C++ Program for Longest Increasing Subsequence
    The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60,
    9 min read
  • C/C++ Program for Longest Increasing Subsequence
    Given an array arr[] of size N, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples: Input: arr[] = {3, 10, 2, 1, 20}Output: 3Explanation: The longest incre
    8 min read
  • C++ Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
    Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6
    2 min read
  • Find the longest subsequence of an array having LCM at most K
    Given an array arr[] of N elements and a positive integer K. The task is to find the longest sub-sequence in the array having LCM (Least Common Multiple) at most K. Print the LCM and the length of the sub-sequence, following the indexes (starting from 0) of the elements of the obtained sub-sequence.
    10 min read
  • C++ Program for Minimum rotations required to get the same string
    Given a string, we need to find the minimum number of rotations required to get the same string. Examples: Input : s = "geeks" Output : 5 Input : s = "aaaa" Output : 1 The idea is based on below post.A Program to check if strings are rotations of each other or not Step 1: Initialize result = 0 (Here
    2 min read
  • C++ Program to Count of rotations required to generate a sorted array
    Given an array arr[], the task is to find the number of rotations required to convert the given array to sorted form.Examples: Input: arr[] = {4, 5, 1, 2, 3} Output: 2 Explanation: Sorted array {1, 2, 3, 4, 5} after 2 anti-clockwise rotations. Input: arr[] = {2, 1, 2, 2, 2} Output: 1 Explanation: So
    4 min read
  • C++ Program to Rotate digits of a given number by K
    Given two integers N and K, the task is to rotate the digits of N by K. If K is a positive integer, left rotate its digits. Otherwise, right rotate its digits. Examples: Input: N = 12345, K = 2Output: 34512 Explanation: Left rotating N(= 12345) by K(= 2) modifies N to 34512. Therefore, the required
    2 min read
  • C++ Program to Maximize count of corresponding same elements in given Arrays by Rotation
    Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples:   Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences