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.
C++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
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 = "GEekS";
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 = "GEekS";
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 = "GEekS"
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 = "GEekS";
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 = "GEekS";
console.log(caseSort(s));
[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.
C++
// C++ Code for Case-Specific Sorting
// of Strings using Two Hash Arrays
#include <string>
#include<iostream>
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 = "GEekS";
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 = "GEekS";
System.out.println(caseSort(s));
}
}
Python
# 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 = "GEekS"
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 = "GEekS";
Console.WriteLine(caseSort(s));
}
}
JavaScript
// 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 = "GEekS";
console.log(caseSort(s));
Similar Reads
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
8 min read
Sort string of characters Given a string of lowercase characters from 'a' - 'z'. We need to write a program to print the characters of this string in sorted order.Examples: Input : "dcab" Output : "abcd"Input : "geeksforgeeks"Output : "eeeefggkkorss"Naive Approach - O(n Log n) TimeA simple approach is to use sorting algorith
5 min read
Sort given words as Array of Strings Given an array of strings Arr[]. The task is to sort them in lexicographic order. Examples: Input: Arr[] = {"sort", "this", "list"}Output: [list, sort, this] Input: Arr[] = {"sun", "earth", "mars", "mercury"}Output: [earth, mars, mercury, sun] Selection Sort Approach: The same problem can also be so
15+ min read
Permute a string by changing case Print all permutations of a string keeping the sequence but changing cases. Examples: Input : abOutput : AB Ab ab aBInput : ABCOutput : abc Abc aBc ABc abC AbC aBC ABCMethod 1 (Naive) : Naive approach would be to traverse the whole string and for every character, consider two cases, (1) change case
7 min read
Sorting collection of String and StringBuffer in Java Sorting a collection of objects can be done in two ways:Â By implementing Comparable (Natural Order) e.g. Strings are sorted ASCIIbetically. meaning B comes before A and 10 is before 2.By implementing Comparator (Custom order) and it can be in any order.Using Collections.sort() method of Collections
2 min read