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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python3 Program for Minimum rotations required to get the same string
Next article icon

Python3 Program to Minimize characters to be changed to make the left and right rotation of a string same

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 2
Explanation:
String after the left shift: “bcda”
String after the right shift: “dabc”
Changing the character at position 3 to 'a' and character at position 4 to 'b', the string is modified to “abab”.
Therefore, both the left and right rotations becomes “baba”.

Input: S = “gfg”
Output: 1
Explanation:
After updating the character at position 1 to 'g', the string becomes “ggg”.
Therefore, the left and right rotation are equal.

Approach: The key observation to solve the problem is that when the length of the string is even, then all the characters at even index and characters at odd index must be the same for the left and right rotations to be the same. For strings of odd length, all the characters must be equal. Follow the steps below to solve the problem:

  • Check if the length of the string is even, then the minimum number of characters to be changed is the length of the string excluding the frequency of the most occurring element at the even indices and odd indices.
  • Otherwise, if the length of the string is odd, then the minimum number of characters to be changed is the length of the string excluding the frequency of the most occurring character in the string.
  • Print the final count obtained.

Below is the implementation of the above approach:

Python
# Python3 Program of the # above approach  # Function to find the minimum # characters to be removed from # the string def getMinimumRemoval(str):        n = len(str)      # Initialize answer by N     ans = n      # If length is even     if(n % 2 == 0):          # Frequency array for odd         # and even indices         freqEven = {}         freqOdd = {}         for ch in range(ord('a'),                          ord('z') + 1):             freqEven[chr(ch)] = 0             freqOdd[chr(ch)] = 0          # Store the frequency of the         # characters at even and odd         # indices         for i in range(n):             if(i % 2 == 0):                 if str[i] in freqEven:                     freqEven[str[i]] += 1             else:                 if str[i] in freqOdd:                     freqOdd[str[i]] += 1          # Stores the most occurring          # frequency for even and          # odd indices         evenMax = 0         oddMax = 0          for ch in range(ord('a'),                          ord('z') + 1):             evenMax = max(evenMax,                        freqEven[chr(ch)])             oddMax = max(oddMax,                       freqOdd[chr(ch)])          # Update the answer         ans = ans - evenMax - oddMax      # If length is odd     else:          # Stores the frequency of the         # characters of the string         freq = {}                  for ch in range('a','z'):             freq[chr(ch)] = 0         for i in range(n):             if str[i] in freq:                 freq[str[i]] += 1          # Stores the most occurring          # characterin the string         strMax = 0                  for ch in range('a','z'):             strMax = max(strMax,                       freq[chr(ch)])          # Update the answer         ans = ans - strMax      return ans  # Driver Code str = "geeksgeeks" print(getMinimumRemoval(str))  # This code is contributed by avanitrachhadiya2155 

 
 


Output
6


 


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 Minimize characters to be changed to make the left and right rotation of a string same for more details!
 


Next Article
Python3 Program for Minimum rotations required to get the same string
author
kartik
Improve
Article Tags :
  • Strings
  • Greedy
  • Searching
  • Hash
  • Python
  • Python Programs
  • DSA
  • rotation
  • frequency-counting
Practice Tags :
  • Greedy
  • Hash
  • python
  • Searching
  • Strings

Similar Reads

  • Python3 Program for Longest subsequence of a number having same left and right rotation
    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"
    4 min read
  • Python3 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 : 5Input : s = "aaaa"Output : 1Method 1: The idea is based on below post.A Program to check if strings are rotations of each other or notStep 1 : Initialize result = 0
    2 min read
  • Python3 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 = 2Output : L
    3 min read
  • Python3 Program for Queries for rotation and Kth character of the given string in constant time
    Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string.Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab"
    2 min read
  • Python3 Program to Find Mth element after K Right Rotations of an Array
    [GFGTABS] Python3 # Python3 program to implement # the above approach # Function to return Mth element of # array after k right rotations def getFirstElement(a, N, K, M): # The array comes to original state # after N rotations K %= N # If K is greater or equal to M if (K >= M): # Mth element afte
    1 min read
  • Python3 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
  • Python3 Program to Find Lexicographically minimum string rotation | Set 1
    Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestMore Examples: Input: GEEKSQUIZOutput: EEKSQUIZGInput: GFGOutput: FGGInput: GEEKSFORGEEKSOutput: EEKSFORGEEKSGFollowing is a simple solution.
    2 min read
  • Python Program to find minimum number of rotations to obtain actual string
    Given two strings s1 and s2. The task is to find out the minimum number of string rotations for the given string s1 to obtain the actual string s2. Examples: Input : eeksg, geeks Output: 1 Explanation: g is rotated left to obtain geeks. Input : eksge, geeks Output: 2 Explanation : e and g are left r
    2 min read
  • Python3 Program to Check if strings are rotations of each other or not | Set 2
    Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABAOutput : TrueInput : GEEKS, EKSGEOutput : TrueWe have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (longest
    2 min read
  • Python3 Program to Check if a string can be obtained by rotating another string 2 places
    Given two strings, the task is to find if a string can be obtained by rotating another string two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Inter
    2 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