Case-specific sorting of Strings in O(n) time and O(1) space

Given a string str consisting of uppercase and lowercase characters. The task is to sort uppercase and lowercase characters separately such that if the ith place in the original string had an uppercase character then it should not have a lowercase character after being sorted and vice versa.

Examples:

Input: str = “gEeksfOrgEEkS”
Output: eEfggkEkrEOsS



Input: str = “eDefSR”
Output: eDefRS

Approach: Take two arrays lower[] and upper[] to store the frequencies of all the lowercase and the uppercase characters in the given string then traverse the string once again and for every lowercase character encountered, replace it with the smallest lowercase character available using the lower[] array and replace the uppercase characters using the upper[] array.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
#define MAX 26
  
// Function to return the sorted string
string getSortedString(string s, int n)
{
  
    // To store the frequencies of the
    // lowercase and the uppercase
    // characters in the given string
    int lower[MAX] = { 0 };
    int upper[MAX] = { 0 };
  
    for (int i = 0; i < n; i++) {
  
        // If current character is lowercase then
        // increment its frequency in
        // the lower[] array
        if (islower(s[i]))
            lower[s[i] - 'a']++;
  
        // Else increment in the upper[] array
        else if (isupper(s[i]))
            upper[s[i] - 'A']++;
    }
  
    // Pointers that point to the smallest lowercase
    // and the smallest uppercase characters
    // respectively in the given string
    int i = 0, j = 0;
    while (i < MAX && lower[i] == 0)
        i++;
  
    while (j < MAX && upper[j] == 0)
        j++;
  
    // For every character in the given string
    for (int k = 0; k < n; k++) {
  
        // If the current character is lowercase
        // then replace it with the smallest
        // lowercase character available
        if (islower(s[k])) {
            while (lower[i] == 0)
                i++;
            s[k] = (char)(i + 'a');
  
            // Decrement the frequency
            // of the used character
            lower[i]--;
        }
  
        // Else replace it with the smallest
        // uppercase character available
        else if (isupper(s[k])) {
            while (upper[j] == 0)
                j++;
            s[k] = (char)(j + 'A');
  
            // Decrement the frequency
            // of the used character
            upper[j]--;
        }
    }
  
    // Return the sorted string
    return s;
}
  
// Driver code
int main()
{
    string s = "gEeksfOrgEEkS";
    int n = s.length();
  
    cout << getSortedString(s, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach 
import java.lang.Character;
  
class GFG
{
  
    static int MAX = 26;
  
    public static String getSortedString(StringBuilder s, int n) 
    {
  
        // To store the frequencies of the
        // lowercase and the uppercase
        // characters in the given string
        int[] lower = new int[MAX];
        int[] upper = new int[MAX];
  
        for (int i = 0; i < n; i++) 
        {
  
            // If current character is lowercase then
            // increment its frequency in
            // the lower[] array
            if (Character.isLowerCase(s.charAt(i)))
                lower[s.charAt(i) - 'a']++;
  
            // Else increment in the upper[] array
            else if (Character.isUpperCase(s.charAt(i)))
                upper[s.charAt(i) - 'A']++;
        }
  
        // Pointers that point to the smallest lowercase
        // and the smallest uppercase characters
        // respectively in the given string
        int i = 0, j = 0;
        while (i < MAX && lower[i] == 0)
            i++;
  
        while (j < MAX && upper[j] == 0)
            j++;
  
        // For every character in the given string
        for (int k = 0; k < n; k++) 
        {
  
            // If the current character is lowercase
            // then replace it with the smallest
            // lowercase character available
            if (Character.isLowerCase(s.charAt(k)))
            {
                while (lower[i] == 0)
                    i++;
                s.setCharAt(k, (char) (i + 'a'));
  
                // Decrement the frequency
                // of the used character
                lower[i]--;
            }
  
            // Else replace it with the smallest
            // uppercase character available
            else if (Character.isUpperCase(s.charAt(k))) 
            {
                while (upper[j] == 0)
                    j++;
                s.setCharAt(k, (char) (j + 'A'));
  
                // Decrement the frequency
                // of the used character
                upper[j]--;
            }
        }
  
        // Return the sorted string
        return s.toString();
    }
  
    // Driver code
    public static void main(String[] args)
    {
        StringBuilder s = new StringBuilder("gEeksfOrgEEkS");
        int n = s.length();
        System.out.println(getSortedString(s, n));
    }
}
  
// This code is contributed by
// sanjeev2552

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
  
MAX = 26
  
# Function to return the sorted string 
def getSortedString(s, n) : 
  
    # To store the frequencies of the 
    # lowercase and the uppercase 
    # characters in the given string 
    lower = [ 0 ] * MAX
    upper = [ 0 ] * MAX
  
    for i in range(n) : 
  
        # If current character is lowercase then 
        # increment its frequency in 
        # the lower[] array 
        if (s[i].islower()) :
            lower[ord(s[i]) - ord('a')] += 1
  
        # Else increment in the upper[] array 
        elif (s[i].isupper()) : 
            upper[ord(s[i]) - ord('A')] += 1
  
    # Pointers that point to the smallest lowercase 
    # and the smallest uppercase characters 
    # respectively in the given string 
    i = 0; j = 0
    while (i < MAX and lower[i] == 0) :
        i += 1
  
    while (j < MAX and upper[j] == 0) :
        j += 1
  
    # For every character in the given string 
    for k in range(n) : 
  
        # If the current character is lowercase 
        # then replace it with the smallest 
        # lowercase character available 
        if (s[k].islower()) :
            while (lower[i] == 0) :
                i += 1
            s[k] = chr(i + ord('a')); 
  
            # Decrement the frequency 
            # of the used character 
            lower[i] -= 1
          
        # Else replace it with the smallest 
        # uppercase character available 
        elif (s[k].isupper()) :
            while (upper[j] == 0) :
                j += 1
            s[k] = chr(j + ord('A')); 
  
            # Decrement the frequency 
            # of the used character 
            upper[j] -= 1
      
    # Return the sorted string 
    return "".join(s); 
  
# Driver code 
if __name__ == "__main__"
    s = "gEeksfOrgEEkS"
    n = len(s);
      
    print(getSortedString(list(s), n)); 
  
# This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
      
class GFG
{
    static int MAX = 26;
  
    // Function to return the sorted string
    static string getSortedString(char[] s, int n)
    {
      
        // To store the frequencies of the
        // lowercase and the uppercase
        // characters in the given string
        int[] lower = new int[MAX];
        int[] upper = new int[MAX];
        int i = 0, j = 0;
        for (i = 0; i < n; i++) 
        {
      
            // If current character is lowercase then
            // increment its frequency in
            // the lower[] array
            if (char.IsLower(s[i]))
                lower[s[i] - 'a']++;
      
            // Else increment in the upper[] array
            else if (char.IsUpper(s[i]))
                upper[s[i] - 'A']++;
        }
      
        // Pointers that point to the smallest lowercase
        // and the smallest uppercase characters
        // respectively in the given string
        i = 0;
        while (i < MAX && lower[i] == 0)
            i++;
      
        while (j < MAX && upper[j] == 0)
            j++;
      
        // For every character in the given string
        for (int k = 0; k < n; k++) 
        {
      
            // If the current character is lowercase
            // then replace it with the smallest
            // lowercase character available
            if (char.IsLower(s[k])) 
            {
                while (lower[i] == 0)
                    i++;
                s[k] = (char)(i + 'a');
      
                // Decrement the frequency
                // of the used character
                lower[i]--;
            }
      
            // Else replace it with the smallest
            // uppercase character available
            else if (char.IsUpper(s[k]))
            {
                while (upper[j] == 0)
                    j++;
                s[k] = (char)(j + 'A');
      
                // Decrement the frequency
                // of the used character
                upper[j]--;
            }
        }
      
        // Return the sorted string
        return String.Join("", s);
    }
      
    // Driver code
    public static void Main(String[] args)
    {
        String s = "gEeksfOrgEEkS";
        int n = s.Length;
        Console.WriteLine(getSortedString(s.ToCharArray(), n));
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

eEfggkEkrEOsS

Time Complexity: O(n)
Space Complexity: O(1)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.