Open In App

Case-specific Sorting of Strings

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given string s 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: s = “gEeksfOrgEEkS” 
Output: eEfggkEkrEOsS
Explanation: Sorted form of given string with the same case of character will result in output as eEfggkEkrEOsS.

Input: s = defRTSersUXI
Output: deeIRSfrsTUX
Explanation: Sorted form of given string with the same case of character as that in original string is deeIRSfrsTUX

Input: s = srbDKi
Output: birDKs
Explanation: Sorted form of given string with the same case of character will result in output as birDKs.

Using 2 Arrays + Sorting – O(nlog(n)) Time and O(n) Space

The idea is to sort lowercase and uppercase separately while maintaining their original positions. We store, sort, and then replace characters based on their original case. This ensures the case structure remains unchanged while sorting.

C++
// C++ Code for Case- Specific Sorting
// of Strings using 2 Arrays + Sorting
#include <bits/stdc++.h>
using namespace std;

// Function to sort uppercase and lowercase 
// characters separately
string caseSort(string s) {

    int n = s.length();
    
    vector<char> lower, upper;
    
    // Storing characters in respective vectors
    for (char ch : s) {
        if (islower(ch)) {
            lower.push_back(ch);
        } else {
            upper.push_back(ch);
        }
    }
    
    // Sorting both lowercase and uppercase characters
    sort(lower.begin(), lower.end());
    sort(upper.begin(), upper.end());

    string result = s;
    int lowerIndex = 0, upperIndex = 0;

    // Replacing characters while maintaining positions
    for (int i = 0; i < n; i++) {
        if (islower(s[i])) {
            result[i] = lower[lowerIndex++];
        } else {
            result[i] = upper[upperIndex++];
        }
    }

    return result;
}

// Driver Code
int main() {
    
    string s = "gEeksfOrgEEkS";
    
    cout << caseSort(s) << endl;

    return 0;
}
Java
// Java Code for Case-Specific Sorting
// of Strings using 2 Arrays + Sorting
import java.util.Arrays;

class GfG {

    // Function to sort uppercase and lowercase 
    // characters separately
    static String caseSort(String s) {

        int n = s.length();
        
        char[] lower = new char[n];
        char[] upper = new char[n];

        int lowerIndex = 0, upperIndex = 0;

        // Storing characters in respective arrays
        for (char ch : s.toCharArray()) {
            if (Character.isLowerCase(ch)) {
                lower[lowerIndex++] = ch;
            } else {
                upper[upperIndex++] = ch;
            }
        }

        // Sorting both lowercase and uppercase characters
        Arrays.sort(lower, 0, lowerIndex);
        Arrays.sort(upper, 0, upperIndex);

        StringBuilder result = new StringBuilder(s);
        lowerIndex = 0;
        upperIndex = 0;

        // Replacing characters while maintaining positions
        for (int i = 0; i < n; i++) {
            if (Character.isLowerCase(s.charAt(i))) {
                result.setCharAt(i, lower[lowerIndex++]);
            } else {
                result.setCharAt(i, upper[upperIndex++]);
            }
        }

        return result.toString();
    }

    // Driver Code
    public static void main(String[] args) {
        
        String s = "gEeksfOrgEEkS";

        System.out.println(caseSort(s));
    }
}
Python
# Python Code for Case-Specific Sorting
# of Strings using 2 Arrays + Sorting

def caseSort(s):
    
    n = len(s)
    
    lower = []
    upper = []

    # Storing characters in respective lists
    for ch in s:
        if ch.islower():
            lower.append(ch)
        else:
            upper.append(ch)

    # Sorting both lowercase and uppercase characters
    lower.sort()
    upper.sort()

    result = list(s)
    lowerIndex = 0
    upperIndex = 0

    # Replacing characters while maintaining positions
    for i in range(n):
        if s[i].islower():
            result[i] = lower[lowerIndex]
            lowerIndex += 1
        else:
            result[i] = upper[upperIndex]
            upperIndex += 1

    return ''.join(result)

# Driver Code
if __name__ == "__main__":
    
    s = "gEeksfOrgEEkS"

    print(caseSort(s))
C#
// C# Code for Case-Specific Sorting
// of Strings using 2 Arrays + Sorting
using System;

class GfG {

    // Function to sort uppercase and lowercase 
    // characters separately
    public static string caseSort(string s) {

        int n = s.Length;
        
        char[] lower = new char[n];
        char[] upper = new char[n];

        int lowerIndex = 0, upperIndex = 0;

        // Storing characters in respective arrays
        foreach (char ch in s) {
            if (char.IsLower(ch)) {
                lower[lowerIndex++] = ch;
            } else {
                upper[upperIndex++] = ch;
            }
        }

        // Sorting both lowercase and uppercase characters
        Array.Sort(lower, 0, lowerIndex);
        Array.Sort(upper, 0, upperIndex);

        char[] result = s.ToCharArray();
        lowerIndex = 0;
        upperIndex = 0;

        // Replacing characters while maintaining positions
        for (int i = 0; i < n; i++) {
            if (char.IsLower(s[i])) {
                result[i] = lower[lowerIndex++];
            } else {
                result[i] = upper[upperIndex++];
            }
        }

        return new string(result);
    }

    // Driver Code
    public static void Main() {
        
        string s = "gEeksfOrgEEkS";

        Console.WriteLine(caseSort(s));
    }
}
JavaScript
// JavaScript Code for Case-Specific Sorting
// of Strings using 2 Arrays + Sorting

function caseSort(s) {

    let n = s.length;

    let lower = [];
    let upper = [];

    // Storing characters in respective arrays
    for (let ch of s) {
        if (ch >= 'a' && ch <= 'z') {
            lower.push(ch);
        } else {
            upper.push(ch);
        }
    }

    // Sorting both lowercase and uppercase characters
    lower.sort();
    upper.sort();

    let result = s.split('');
    let lowerIndex = 0, upperIndex = 0;

    // Replacing characters while maintaining positions
    for (let i = 0; i < n; i++) {
        if (s[i] >= 'a' && s[i] <= 'z') {
            result[i] = lower[lowerIndex++];
        } else {
            result[i] = upper[upperIndex++];
        }
    }

    return result.join('');
}

// Driver Code
let s = "gEeksfOrgEEkS";

console.log(caseSort(s));

Output
eEfggkEkrEOsS

Using Two Count Arrays of 26 Size – O(n) Time and O(1) Space

The idea is to use two count arrays to count the frequency of each character, avoiding direct sorting. Then, we reconstruct the string by placing characters in their respective positions using the stored frequencies

Steps to implement the above idea:

  • Initialize two hash arrays of size 26 to store the frequency of lowercase and uppercase characters separately.
  • Traverse the given string and update the respective hash arrays based on whether the character is lowercase or uppercase.
  • Iterate through the original string and replace each lowercase character with the next available sorted one from the hash array. Repeat the process for uppercase characters as well.
  • Return the modified string after replacing all characters while maintaining their case-specific positions.
C++
// C++ Code for Case-Specific Sorting  
// of Strings using Two Hash Arrays  
#include <bits/stdc++.h>
using namespace std;

// Function to sort uppercase and lowercase  
// characters separately  
string caseSort(string s) {

    int n = s.length();
    
    int lower[26] = {0}, upper[26] = {0};
    
    // Storing frequency of characters  
    for (char ch : s) {
        if (islower(ch)) {
            lower[ch - 'a']++;
        } else {
            upper[ch - 'A']++;
        }
    }

    string result = s;
    int l = 0, u = 0;

    // Placing sorted characters in original positions  
    for (int i = 0; i < n; i++) {
        if (islower(s[i])) {
            while (lower[l] == 0) {
                l++;
            }
            result[i] = 'a' + l;
            lower[l]--;
        } else {
            while (upper[u] == 0) {
                u++;
            }
            result[i] = 'A' + u;
            upper[u]--;
        }
    }

    return result;
}

// Driver Code  
int main() {
    
    string s = "gEeksfOrgEEkS";
    
    cout << caseSort(s) << endl;

    return 0;
}
Java
// Java Code for Case-Specific Sorting  
// of Strings using Two Hash Arrays  
import java.util.*;

class GfG {

    // Function to sort uppercase and lowercase  
    // characters separately  
    static String caseSort(String s) {

        int n = s.length();

        int[] lower = new int[26], upper = new int[26];

        // Storing frequency of characters  
        for (char ch : s.toCharArray()) {
            if (Character.isLowerCase(ch)) {
                lower[ch - 'a']++;
            } else {
                upper[ch - 'A']++;
            }
        }

        StringBuilder result = new StringBuilder(s);
        int l = 0, u = 0;

        // Placing sorted characters in original positions  
        for (int i = 0; i < n; i++) {
            if (Character.isLowerCase(s.charAt(i))) {
                while (lower[l] == 0) {
                    l++;
                }
                result.setCharAt(i, (char) ('a' + l));
                lower[l]--;
            } else {
                while (upper[u] == 0) {
                    u++;
                }
                result.setCharAt(i, (char) ('A' + u));
                upper[u]--;
            }
        }

        return result.toString();
    }

    // Driver Code  
    public static void main(String[] args) {

        String s = "gEeksfOrgEEkS";

        System.out.println(caseSort(s));
    }
}
Python
# Python Code for Case-Specific Sorting  
# of Strings using Two Hash Arrays  

# Function to sort uppercase and lowercase  
# characters separately  
def caseSort(s):

    n = len(s)

    lower = [0] * 26
    upper = [0] * 26

    # Storing frequency of characters  
    for ch in s:
        if ch.islower():
            lower[ord(ch) - ord('a')] += 1
        else:
            upper[ord(ch) - ord('A')] += 1

    result = list(s)
    l, u = 0, 0

    # Placing sorted characters in original positions  
    for i in range(n):
        if s[i].islower():
            while lower[l] == 0:
                l += 1
            result[i] = chr(ord('a') + l)
            lower[l] -= 1
        else:
            while upper[u] == 0:
                u += 1
            result[i] = chr(ord('A') + u)
            upper[u] -= 1

    return ''.join(result)

# Driver Code  
if __name__ == "__main__":
    
    s = "gEeksfOrgEEkS"

    print(caseSort(s))
C#
// C# Code for Case-Specific Sorting  
// of Strings using Two Hash Arrays  
using System;

class GfG {

    // Function to sort uppercase and lowercase  
    // characters separately  
    public static string caseSort(string s) {

        int n = s.Length;

        int[] lower = new int[26], upper = new int[26];

        // Storing frequency of characters  
        foreach (char ch in s) {
            if (char.IsLower(ch)) {
                lower[ch - 'a']++;
            } else {
                upper[ch - 'A']++;
            }
        }

        char[] result = s.ToCharArray();
        int l = 0, u = 0;

        // Placing sorted characters in original positions  
        for (int i = 0; i < n; i++) {
            if (char.IsLower(s[i])) {
                while (lower[l] == 0) {
                    l++;
                }
                result[i] = (char)('a' + l);
                lower[l]--;
            } else {
                while (upper[u] == 0) {
                    u++;
                }
                result[i] = (char)('A' + u);
                upper[u]--;
            }
        }

        return new string(result);
    }

    // Driver Code  
    public static void Main() {

        string s = "gEeksfOrgEEkS";

        Console.WriteLine(caseSort(s));
    }
}
JavaScript
// JavaScript Code for Case-Specific Sorting  
// of Strings using Two Hash Arrays  

// Function to sort uppercase and lowercase  
// characters separately  
function caseSort(s) {

    let n = s.length;

    let lower = new Array(26).fill(0);
    let upper = new Array(26).fill(0);

    // Storing frequency of characters  
    for (let ch of s) {
        if (ch >= 'a' && ch <= 'z') {
            lower[ch.charCodeAt(0) - 'a'.charCodeAt(0)]++;
        } else {
            upper[ch.charCodeAt(0) - 'A'.charCodeAt(0)]++;
        }
    }

    let result = s.split('');
    let l = 0, u = 0;

    // Placing sorted characters in original positions  
    for (let i = 0; i < n; i++) {
        if (s[i] >= 'a' && s[i] <= 'z') {
            while (lower[l] === 0) {
                l++;
            }
            result[i] = String.fromCharCode('a'.charCodeAt(0) + l);
            lower[l]--;
        } else {
            while (upper[u] === 0) {
                u++;
            }
            result[i] = String.fromCharCode('A'.charCodeAt(0) + u);
            upper[u]--;
        }
    }

    return result.join('');
}

// Driver Code  
let s = "gEeksfOrgEEkS";

console.log(caseSort(s));

Output
eEfggkEkrEOsS



Next Article
Practice Tags :

Similar Reads