Open In App

Sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged

Last Updated : 22 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.
Examples: 

Input: str = “geeks12for32geeks” 
Output: eeeef12ggk23korss
Input: str = “d4c3b2a1” 
Output: a1b2c3d4 

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: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns the string s
// in sorted form such that the
// positions of alphabets and numeric
// digits remain unchanged
string sort(string s)
{
    char c[s.length() + 1];
 
    // String to character array
    strcpy(c, s.c_str());
 
    // Sort the array
    sort(c, c + s.length());
 
    // Count of alphabets and numbers
    int al_c = 0, nu_c = 0;
 
    // Get the index from where the
    // alphabets start
    while (c[al_c] < 97)
        al_c++;
 
    // Now replace the string with sorted string
    for (int i = 0; i < s.length(); i++) {
 
        // If the position was occupied by an
        // alphabet then replace it with alphabet
        if (s[i] < 97)
            s[i] = c[nu_c++];
 
        // Else replace it with a number
        else
            s[i] = c[al_c++];
    }
 
    // Return the sorted string
    return s;
}
 
// Driver code
int main()
{
    string s = "d4c3b2a1";
 
    cout << sort(s);
 
    return 0;
}


Java




// A Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function that returns the string s
// in sorted form such that the
// positions of alphabets and numeric
// digits remain unchanged
static String sort(String s)
{
    char []c = new char[s.length() + 1];
 
    // String to character array
    c = s.toCharArray();
 
    // Sort the array
    Arrays.sort(c);
 
    // Count of alphabets and numbers
    int al_c = 0, nu_c = 0;
 
    // Get the index from where the
    // alphabets start
    while (c[al_c] < 97)
        al_c++;
 
    // Now replace the string with sorted string
    for (int i = 0; i < s.length(); i++)
    {
 
        // If the position was occupied by an
        // alphabet then replace it with alphabet
        if (s.charAt(i) < 97)
            s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1);
 
        // Else replace it with a number
        else
            s = s.substring(0,i)+ c[al_c++]+s.substring(i+1);
    }
 
    // Return the sorted string
    return s;
}
 
// Driver code
public static void main(String[] args)
{
    String s = "d4c3b2a1";
 
    System.out.println(sort(s));
}
}
 
/* This code contributed by PrinciRaj1992 */


Python3




# Python3 implementation of the approach
 
# Function that returns the string s
# in sorted form such that the
# positions of alphabets and numeric
# digits remain unchanged
def sort(s):
 
    # String to character array
    c, s = list(s), list(s)
 
    # Sort the array
    c.sort()
 
    # Count of alphabets and numbers
    al_c = 0
    nu_c = 0
 
    # Get the index from where the
    # alphabets start
    while ord(c[al_c]) < 97:
        al_c += 1
 
    # Now replace the string with sorted string
    for i in range(len(s)):
 
        # If the position was occupied by an
        # alphabet then replace it with alphabet
        if s[i] < 'a':
            s[i] = c[nu_c]
            nu_c += 1
 
        # Else replace it with a number
        else:
            s[i] = c[al_c]
            al_c += 1
 
    # Return the sorted string
    return ''.join(s)
 
# Driver Code
if __name__ == "__main__":
    s = "d4c3b2a1"
    print(sort(s))
 
# This code is contributed by
# sanjeev2552


C#




// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function that returns the string s
    // in sorted form such that the
    // positions of alphabets and numeric
    // digits remain unchanged
    static string sort(string s)
    {
        char []c = new char[s.Length + 1];
     
        // String to character array
        c = s.ToCharArray();
     
        // Sort the array
        Array.Sort(c);
     
        // Count of alphabets and numbers
        int al_c = 0, nu_c = 0;
     
        // Get the index from where the
        // alphabets start
        while (c[al_c] < 97)
            al_c++;
     
        // Now replace the string with sorted string
        for (int i = 0; i < s.Length; i++)
        {
     
            // If the position was occupied by an
            // alphabet then replace it with alphabet
            if (s[i] < 97)
                s = s.Substring(0,i)+ c[nu_c++]+s.Substring(i+1);
     
            // Else replace it with a number
            else
                s = s.Substring(0,i)+ c[al_c++]+s.Substring(i+1);
        }
     
        // Return the sorted string
        return s;
    }
     
    // Driver code
    public static void Main()
    {
        string s = "d4c3b2a1";
     
        Console.WriteLine(sort(s));
    }
}
 
/* This code contributed by AnkitRai01 */


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function that returns the string s
// in sorted form such that the
// positions of alphabets and numeric
// digits remain unchanged
function sort(s)
{
    var c = s.split('');
 
    c.sort();
 
    // Count of alphabets and numbers
    var al_c = 0, nu_c = 0;
 
    // Get the index from where the
    // alphabets start
    while (c[al_c].charCodeAt(0) < 97)
        al_c++;
 
    // Now replace the string with sorted string
    for (var i = 0; i < s.length; i++) {
 
        // If the position was occupied by an
        // alphabet then replace it with alphabet
        if (s[i].charCodeAt(0) < 97)
            s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1);
 
        // Else replace it with a number
        else
        s = s.substring(0,i)+ c[al_c++]+s.substring(i+1);
    }
 
    // Return the sorted string
    return s;
}
 
// Driver code
var s = "d4c3b2a1";
document.write( sort(s));
 
// This code is contributed by rutvik_56.
</script>


Output

a1b2c3d4

Time complexity: O(N * log(N)) where N is the length of the string.
Auxiliary Space: O(N), where N is the length of the given string.



Similar Reads

Maximum number of elements that can be removed such that MEX of the given array remains unchanged
Given an array arr[] of size N, the task is to count the maximum number of elements that can be removed from the given array without changing the MEX of the original array. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {2, 3, 5, 1, 6} Output: 2 Explanation:The smallest positive integer which is
6 min read
Count ways to remove objects such that exactly M equidistant objects remain
Given an integer N, representing objects placed adjacent to each other, the task is to count the number of ways to remove objects such that after their removal, exactly M objects are left and the distance between each adjacent object is equal. Examples: Input: N = 5, M = 3Output: 4Explanation:Let the initial arrangement be A1 A2 A3 A4 A5.The follow
6 min read
Count of ways to rearrange N digits and M alphabets keeping all alphabets together
Given two positive integers N and M representing the count of distinct digits and alphabets respectively in a string, the task to count the number of ways to rearrange the characters of the string such that all the alphabets are adjacent. Examples: Input: N = 2, M = 2Output: 12Explanation: Possible ways to rearrange characters of a string such that
9 min read
Maximum increase in value of Matrix to keep maximum rows and columns unchanged
Given a matrix mat[][] of dimensionM*N, the task is to find the total maximum possible value must be increased to each cell(say mat[i][j]) such that maximum element of row i and column j remains unchanged. Examples: Input: N = 3, M = 3, mat[][] = { {4, 1, 3}, {3, 1, 1}, {2, 2, 0} } Output: 6 Explanation: The given matrix is: 4 1 3 3 1 1 2 2 0 Row-w
9 min read
Check if Matrix remains unchanged after row reversals
Given an NxN matrix. The task is to check if after reversing all the rows of the given Matrix, the matrix remains the same or not. Examples: Input : N = 3 1 2 1 2 2 2 3 4 3 Output : Yes If all the rows are reversed then matrix will become: 1 2 1 2 2 2 3 4 3 which is same. Input : N = 3 1 2 2 2 2 2 3 4 3 Output : No Approach: A most important observ
5 min read
Minimize K whose XOR with given array elements leaves array unchanged
Given an array of N elements, the task is to find the minimum value of K such that Bitwise XOR of K with all array elements produces the same set of elements. If it is impossible to find any value of K then print "-1". Examples: Input: arr[] = { 1, 0, 2, 3} Output: 1 Explanation: For K = 1, 1 xor 1 = 01 xor 0 = 11 xor 2 = 31 xor 3 = 2Thus, K = 1 is
7 min read
Probability of Knight to remain in the chessboard
Given an NxN chessboard and a Knight at position (x,y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. What is the probability that the Knight remains in the chessboard after taking K steps, with the condition that it can't enter the board again once it leaves it?Examples: Let's ta
12 min read
Sort a permutation of first N natural numbers by swapping elements at positions X and Y if N &le; 2|X - Y|
Given an array arr[] consisting of first N natural numbers (N is even), the task is to find a sequence of swaps that can sort the array by swapping elements at positions X and Y ifN ≤ 2|X - Y| Note: Consider 1-based indexing Examples: Input: N = 2, arr[] = { 2, 1 }Output: 1 2Explanation: Swapping elements at positions 1 and 2 sorts the array. Input
12 min read
How to remove all non-alphanumeric characters from a string in Java
Given string str, the task is to remove all non-alphanumeric characters from it and print the modified it. Examples: Input: @!Geeks-for'Geeks,123 Output: GeeksforGeeks123 Explanation: at symbol(@), exclamation point(!), dash(-), apostrophes('), and commas(, ) are removed.Input: Geeks_for$ Geeks?{}[] Output: GeeksforGeeks Explanation: underscore(_),
3 min read
How to check string is alphanumeric or not using Regular Expression
Given string str, the task is to check whether the string is alphanumeric or not by using Regular Expression. An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Examples: Input: str = "GeeksforGeeks123" Output: true Explanation: This string contains all the alphabets from a-z, A-Z, and the numbe
5 min read
Practice Tags :