VOOZH about

URL: https://www.geeksforgeeks.org/dsa/case-specific-sorting-of-strings/

⇱ Case-specific Sorting of Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Case-specific Sorting of Strings

Last Updated : 17 Jun, 2025

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 = "GEekS" 
Output: "EGekS"
Explanation: Sorted form of given string with the same case of character will result in output as EGekS.

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.

[Naive Approach]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.


Output
EGekS

[Expected Approach] 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

Step-By-Step Approach:

  • 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.

Output
EGekS
Comment
Article Tags:
Article Tags: