Print only sorted Permutation of a string

By | October 2, 2023

Given a string s, the task is to print all permutations of a string that are in ascending order, i.e., their characters are in ascending order.

Examples:

Input: Cplusplus
Output: Cllppssuu
Out of all the permutations of the string Cllppssuu is the only string which is sorted. 

Input: cba 
Output: abc

RECOMMENDED: Characteristics or features of an Algorithm

Approach:
There will always be only one string that will be in ascending order.
Below is the implementation of the above approach.

C++

// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;

void printString(string s)
{
    sort(s.begin(), s.end());
    cout << s << "\n";
}

int main()
{
    string s = "Cplusplus";
    printString(s);
    return 0;
}

Java

// Java implementation of the above approach
import java.util.Arrays;

public class Solution {
    public static void printString(String s) {
        char[] tempArray = s.toCharArray();
        
        // Sort tempArray
        Arrays.sort(tempArray);
        
        // Print the new sorted string
        System.out.println(tempArray);
    }

    public static void main(String[] args) {
        String s = "Cplusplus";
        printString(s);
    }
}

C#

// C# implementation of the above approach
using System;

class Solution {
    public static void printString(string s) {
        char[] arr = s.ToCharArray();
        Array.Sort(arr);
        Console.WriteLine(string.Join("", arr));
    }

    public static void Main() {
        string s = "Cplusplus";
        printString(s);
    }
}


Output:

Cllppssuu

Time Complexity: O(nlogn), due to sorting.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.