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

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.