Given an alphanumeric string str, the task is to sort the string in such a way that if a position is occupied by an alphabet it must be occupied by an alphabet after sorting and if occupied by a number it must be occupied by a number after sorting.
Input: str = “geeks12for32geeks”
Input: str = “d4c3b2a1”
Approach: We will convert the string to a character array and then sort the character array c. After sorting the character array the numeric characters will occupy starting indices of the array and the alphabets will occupy the remaining part of the array.
The numeric half will be sorted and the alphabet part will also be sorted. We will keep two indices one at the starting index of the alphabet part al_c and one at the starting index of numeric part nu_c, now we will check the original string and if a position was occupied by an alphabet then we will replace it with c[al_c] and increment al_c else we will replace it with c[nu_c] and increment nu_c.
Below is the implementation of the above approach:
Time complexity: O(N * log(N)) where N is the length of the string.
- Sort ugly numbers in an array at their relative positions
- Find numbers of balancing positions in string
- Alphanumeric Abbreviations of a String
- Check if count of Alphabets and count of Numbers are equal in the given String
- How to check string is alphanumeric or not using Regular Expression
- Sort all special primes in their relative positions
- Sort groups of numbers and characters separately in a String
- Remove all characters other than alphabets from string
- Sub-string that contains all lowercase alphabets after performing the given operation
- Generate a string with maximum possible alphabets with odd frequencies
- Check if a string contains only alphabets in Java using ASCII values
- Check if a string contains only alphabets in Java using Lambda expression
- Reverse a string preserving space positions
- Bucket Sort To Sort an Array with Negative Numbers
- Number of positions where a letter can be inserted such that a string becomes palindrome