Given a string str with repeated characters, the task is to rearrange the characters in a string such that no two adjacent characters are same. If it is possible then print Yes else print No.
Input: str = “geeksforgeeks”
“egeksforegeks” is one such arrangement.
Input: str = “bbbbb”
Approach: The idea is to store the frequency of each character in an unordered_map and compare maximum frequency of character with the difference of string length and maximum frequency number. If the maximum frequency is less than the difference then it can be arranged otherwise not.
Below is the implementation of the above approach:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Rearrange characters in a string such that no two adjacent are same
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Rearrange a string so that all same characters become d distance away
- Rearrange a string so that all same characters become atleast d distance away
- String with k distinct characters and no same characters adjacent
- C program to swap adjacent characters of a String
- Check if a given string can be formed using characters of adjacent cells of a Matrix
- Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
- Minimum replacements to make adjacent characters unequal in a ternary string
- Rearrange array such that difference of adjacent elements is in descending order
- Rearrange characters to form palindrome if possible
- Minimum string such that every adjacent character of given string is still adjacent
- Longest subsequence with different adjacent characters
- Rearrange given string to maximize the occurrence of string t
- Rearrange numbers in an array such that no two adjacent numbers are same
- Remove first adjacent pairs of similar characters until possible
- Count of strings where adjacent characters are of difference one
- Count of ungrouped characters after dividing a string into K groups of distinct characters
- Check whether two strings can be made equal by copying their characters with the adjacent ones