Open In App

Sort an array of strings in ascending order with each string sorted in descending order

Last Updated : 01 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a array of strings S[] of size N (1 ? N ? 105), sort characters of each string in descending order and then print the array of strings in ascending order.

Examples: 
 

Input: s[] = {“apple”, “box”, “cat”} 
Output: pplea tca xob 
Explanation: 
Sorting each string in descending order, S[] modifies to {“pplea”, “xob”, “tca”}. 
Sorting the array in ascending order modifies S[] to {pplea, tca, xob}.

Input: s[] = {“pqr”, “moon”, “geeks”} 
Output: oonm rqp skgee

Approach: Follow the steps below to solve the problem:

Below is the implementation of the above approach.

C++
// C++ program of the above approach

#include <bits/stdc++.h>
using namespace std;

// Function to sort the strings in
// descending order and sort the
// array in ascending order
void sortStr(string s[], int N)
{

    // Traverse the array of strings
    for (int i = 0; i < N; i++) {

        // Sort each string in descending order
        sort(s[i].begin(), s[i].end(), greater<char>());
    }

    // Sort the array in ascending order
    sort(s, s + N);

    // Print the array of strings
    for (int i = 0; i < N; i++) {
        cout << s[i] << " ";
    }
}

// Driver Code
int main()
{
    string s[] = { "apple", "box", "cat" };
    int N = sizeof(s) / sizeof(s[0]);
    sortStr(s, N);

    return 0;
}
Java
// Java program of the above approach
import java.util.Arrays;
class GFG {

    // Function to sort the Strings in
    // descending order and sort the
    // array in ascending order
    static void sortStr(String s[], int N)
    {

        // Traverse the array of Strings
        for (int i = 0; i < N; i++) {

            // Sort each String in descending order
            s[i] = reverse(sortString(s[i]));
        }

        // Sort the array in ascending order
        Arrays.sort(s);

        // Print the array of Strings
        for (int i = 0; i < N; i++) {
            System.out.print(s[i] + " ");
        }
    }
    static String sortString(String inputString)
    {

        // convert input string to char array
        char tempArray[] = inputString.toCharArray();

        // sort tempArray
        Arrays.sort(tempArray);

        // return new sorted string
        return new String(tempArray);
    }
    static String reverse(String input)
    {
        char[] a = input.toCharArray();
        int l, r = a.length - 1;
        for (l = 0; l < r; l++, r--) {
            char temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
        return String.valueOf(a);
    }

    // Driver Code
    public static void main(String[] args)
    {
        String s[] = { "apple", "box", "cat" };
        int N = s.length;
        sortStr(s, N);
    }
}

// This code is contributed by shikhasingrajput
Python
# Python program of the above approach

# Function to sort the Strings in
# descending order and sort the
# array in ascending order


def sortStr(s, N):

    # Traverse the array of Strings
    for i in range(N):

        # Sort each String in descending order
        s[i] = "".join(reversed("".join(sorted(s[i]))))

    # Sort the array in ascending order
    s = " ".join(sorted(s))

    # Print the array of Strings
    print(s)


# Driver Code
if __name__ == '__main__':
    s = ["apple", "box", "cat"]
    N = len(s)
    sortStr(s, N)

    # This code is contributed by shikhasingrajput
C#
// C# program of the above approach
using System;
class GFG {

    static void reverse(char[] a)
    {
        int i, n = a.Length;
        char t;
        for (i = 0; i < n / 2; i++) {
            t = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = t;
        }
    }

    // Function to sort the strings in
    // descending order and sort the
    // array in ascending order
    static void sortStr(string[] s, int N)
    {

        // Traverse the array of strings
        for (int i = 0; i < N; i++) {
            char[] t = s[i].ToCharArray();

            // Sort each string
            Array.Sort(t);

            // Reverse the string
            reverse(t);
            s[i] = String.Join("", t);
        }

        // Sort the array in ascending order
        Array.Sort(s);

        // Print the array of strings
        for (int i = 0; i < N; i++) {
            Console.Write(s[i] + " ");
        }
    }

    // Driver Code
    public static void Main()
    {
        string[] s = { "apple", "box", "cat" };
        int N = s.Length;
        sortStr(s, N);
    }
}

// This code is contributed by subhammahato348
Javascript
<script>

// Javascript program of the above approach

// Function to sort the strings in
// descending order and sort the
// array in ascending order
function sortStr( s, N)
{

    // Traverse the array of strings
    for (var i = 0; i < N; i++) {

        // Sort each string in descending order
        s[i] = s[i].split('').sort((a,b)=>{return b>a?1:-1}).join('')
    }

    // Sort the array in ascending order
    s.sort();

    // Print the array of strings
    for (var i = 0; i < N; i++) {
        document.write( s[i] + " ");
    }
}

// Driver Code
var s = [ "apple", "box", "cat" ];
var N = s.length;
sortStr(s, N);

</script>

Output
pplea tca xob 

Time Complexity: O(N*MlogM) where N is the size of the array and M is the maximum size of any string present in the array.
Auxiliary Space: O(1) 

Approach Using Character Counting

In this approach, we’ll utilize character counting (a variant of counting sort) for sorting each string in descending order, which offers a linear time complexity relative to the string’s length. Then, we sort the array of these transformed strings. This method minimizes the complexity by ensuring the internal string sorting is efficient.

Follow the steps to solve the above approach:

  • Convert each string to its character counts, then generate a sorted version of the string in descending order using these counts.
  • Sort the array of strings based on their transformed descending character-sorted forms.
  • Print the transformed sorted array, which shows each string with its characters sorted in descending order.

Below is the implementation of above approach:

C++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

// Function to sort a string in descending order
std::string sort_descending(const std::string& s) {
    // Array to store the frequency of each character
    std::vector<int> char_count(26, 0);
    // Count each character in the string
    for (char c : s) {
        char_count[c - 'a']++;
    }

    // Build a string with characters sorted in descending order
    std::string sorted_str;
    for (int i = 25; i >= 0; --i) {
        if (char_count[i] > 0) {
            sorted_str.append(char_count[i], 'a' + i);
        }
    }
    return sorted_str;
}

// Function to sort an array of strings where each string is sorted in descending order internally
void sort_strings(std::vector<std::string>& arr) {
    // Create a vector of pairs to store the descending sorted version of each string along with the original string
    std::vector<std::pair<std::string, std::string>> transformed;
    for (const std::string& s : arr) {
        transformed.emplace_back(sort_descending(s), s);
    }

    // Sort the pairs based on the descending sorted string
    std::sort(transformed.begin(), transformed.end());

    // Output each original string sorted internally in descending order
    for (const auto& pair : transformed) {
        std::cout << sort_descending(pair.second) << " ";
    }
}

// Main function to demonstrate the sorting functionality
int main() {
    std::vector<std::string> arr = {"apple", "box", "cat"};
    sort_strings(arr);
    return 0;
}
Python
def sort_descending(s):
    # Character count for characters in the string
    char_count = [0] * 26
    for char in s:
        char_count[ord(char) - ord('a')] += 1
    
    # Building the descending order string from character counts
    sorted_str = []
    for i in range(25, -1, -1):
        if char_count[i] > 0:
            sorted_str.append(chr(i + ord('a')) * char_count[i])
    
    return ''.join(sorted_str)

def sort_strings(arr):
    # Transform each string to its sorted descending order
    transformed = [(sort_descending(s), s) for s in arr]
    # Sort the list of tuples based on the descending ordered string
    transformed.sort()
    # Print each original string sorted internally in descending order
    for _, orig_str in transformed:
        print(sort_descending(orig_str), end=" ")

# Example usage
arr = ["apple", "box", "cat"]
sort_strings(arr)

Output
pplea tca xob 

Time Complexity: O(N×(M+26)) N is the number of strings, M is the maximum length of the strings, and 26 represents the fixed time to build the sorted string from the character counts.

Auxilary Space: O(M)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads