Skip to content
Related Articles

Related Articles

Sort a string in increasing order of given priorities
  • Difficulty Level : Hard
  • Last Updated : 04 Jan, 2021

Given an alphanumeric string S of length N, the task is to sort the string in increasing order of their priority based on the following conditions:

  • Characters with even ASCII values have higher priority than characters with odd ASCII values.
  • Even digits have higher priority than odd digits.
  • Digits have higher priority than characters.
  • For characters or digits having the same parity, the priority is in increasing order of their ASCII values.

Examples:

Input: S = “abcd1234”
Output: 1324bdac
Explanation: 
The ASCII value of “a” is 97.
The ASCII value of “b” is 98.
The ASCII value of “c” is 99.
The ASCII value of “d” is 100.
Since characters with even ASCII value have higher priority, “b” and “d” are placed first followed by “a” and “c”.
Similarly, even digits have more priority than odd digits. Therefore, they are placed first.
Since the numbers have a higher priority than characters, the sorted string is “1324bdac”

Input: S = “adb123”
Output: bda132

 

Approach: The idea is to separate the characters with odd and even ASCII values and also the digits with odd and even parity. Then, join these substrings in the order of their priorities. Follow the steps below to solve the problem:



  1. Initialize two variables, say digits and characters, to store the characters and digits separately.
  2. Sort the strings digits and characters with respect to the ASCII table.
  3. Now, traverse all the characters in characters and append each character with an odd parity to a variable say oddChars and each character with an even parity to another variable say, evenChars.
  4. Similarly, for the string digits, separate the odd and even parity digits, say oddDigs and evenDigs.
  5. Finally, concatenate the string as oddChars + evenChars + oddDigs + evenDigs.

Below is the implementation of the above approach:

C++14




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the string s
// based on the given conditions
string sortString(string s)
{
    // Stores digits of given string
    string digits = "";
 
    // Stores characters of given string
    string character = "";
 
    // Iterate over characters of the string
    for (int i = 0; i < s.size(); ++i) {
        if (s[i] >= '0' && s[i] <= '9')
 {
     digits += s[i];
 }
 else
 {
     character += s[i];
 }
 }
 
 // Sort the string of digits
 sort(digits.begin(), digits.end());
 
 // Sort the string of characters
 sort(character.begin(), character.end());
 
 // Stores odd and even characters
 string OddChar = "", EvenChar = "";
 
 // Seperate odd and even digits
 for (int i = 0; i < digits.length(); ++i) {
     if ((digits[i] - '0') % 2 == 1) {
         OddChar += digits[i];
     }
     else {
         EvenChar += digits[i];
     }
 }
 
 // Concatenate strings in the order
 // odd characters followed by even
 OddChar += EvenChar;
 
 EvenChar = "";
 
 // Seperate the odd and even chars
 for (int i = 0; i < character.length();
      ++i) {
 
     if ((character[i] - 'a') % 2 == 1) {
         OddChar += character[i];
     }
     else {
         EvenChar += character[i];
     }
 }
 
 // Final string
 OddChar += EvenChar;
 
 // Return the final string
 return OddChar;
 }
 
 // Driver Code
 int main()
 {
     // Given string
     string s = "abcd1234";
 
     // Returns the sorted string
     cout << sortString(s);
 
     return 0;
 }

Java




// Java program for the above approach
import java.util.*;
class GFG
{
 
    // Function to sort the String s
    // based on the given conditions
    static String sortString(String s)
    {
       
        // Stores digits of given String
        String digits = "";
 
        // Stores characters of given String
        String character = "";
 
        // Iterate over characters of the String
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                digits += s.charAt(i);
            } else {
                character += s.charAt(i);
            }
        }
 
        // Sort the String of digits
        digits = sort(digits);
        // Sort the String of characters
        character = sort(character);
 
        // Stores odd and even characters
        String OddChar = "", EvenChar = "";
 
        // Seperate odd and even digits
        for (int i = 0; i < digits.length(); ++i) {
            if ((digits.charAt(i) - '0') % 2 == 1) {
                OddChar += digits.charAt(i);
            } else {
                EvenChar += digits.charAt(i);
            }
        }
 
        // Concatenate Strings in the order
        // odd characters followed by even
        OddChar += EvenChar;
        EvenChar = "";
 
        // Seperate the odd and even chars
        for (int i = 0; i < character.length(); ++i) {
 
            if ((character.charAt(i) - 'a') % 2 == 1) {
                OddChar += character.charAt(i);
            } else {
                EvenChar += character.charAt(i);
            }
        }
 
        // Final String
        OddChar += EvenChar;
 
        // Return the final String
        return OddChar;
    }
 
    static String sort(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);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given String
        String s = "abcd1234";
 
        // Returns the sorted String
        System.out.print(sortString(s));
 
    }
}
 
// This code is contributed by shikhasingrajput

Python3




# Python3 program for the above approach
 
# Function to sort the string s
# based on the given conditions
def sortString(s):
     
    # Stores digits of given string
    digits = ""
     
    # Stores characters of given string
    character = ""
     
    # Iterate over characters of the string
    for i in range(len(s)):
        if (s[i] >= '0' and s[i] <= '9'):
            digits += s[i]
        else:
            character += s[i]
             
    # Sort the string of digits
    Digits = list(digits)
    Digits.sort()
     
    # Sort the string of characters
    Character = list(character)
    Character.sort()
     
    # Stores odd and even characters
    OddChar, EvenChar = "", ""
     
    # Seperate odd and even digits
    for i in range(len(Digits)):
        if ((ord(digits[i]) - ord('0')) % 2 == 1):
            OddChar += Digits[i]
        else:
            EvenChar += Digits[i]
             
    # Concatenate strings in the order
    # odd characters followed by even
    OddChar += EvenChar
    EvenChar = ""
     
    # Seperate the odd and even chars
    for i in range(len(Character)):
        if ((ord(Character[i]) - ord('a')) % 2 == 1):
            OddChar += Character[i]
        else:
            EvenChar += Character[i]
             
    # Final string
    OddChar += EvenChar
     
    # Return the final string
    return OddChar
     
# Driver Code
 
# Given string
s = "abcd1234"
 
# Returns the sorted string
print(sortString(list(s)))
 
# This code is contributed by divyesh072019

C#




// C# program for the above approach
using System;
class GFG
{
 
  // Function to sort the string s
  // based on the given conditions
  static string sortString(char[] s)
  {
 
    // Stores digits of given string
    string digits = "";
 
    // Stores characters of given string
    string character = "";
 
    // Iterate over characters of the string
    for (int i = 0; i < s.Length; ++i)
    {
      if (s[i] >= '0' && s[i] <= '9')
      {
        digits += s[i];
      }
      else
      {
        character += s[i];
      }
    }
 
    // Sort the string of digits
    char[] Digits = digits.ToCharArray();
    Array.Sort(Digits);
 
    // Sort the string of characters
    char[] Character = character.ToCharArray();
    Array.Sort(Character);
 
    // Stores odd and even characters
    string OddChar = "", EvenChar = "";
 
    // Seperate odd and even digits
    for (int i = 0; i < Digits.Length; ++i)
    {
      if ((digits[i] - '0') % 2 == 1)
      {
        OddChar += Digits[i];
      }
      else
      {
        EvenChar += Digits[i];
      }
    }
 
    // Concatenate strings in the order
    // odd characters followed by even
    OddChar += EvenChar;
    EvenChar = "";
 
    // Seperate the odd and even chars
    for (int i = 0; i < Character.Length; ++i)
    {
 
      if ((Character[i] - 'a') % 2 == 1)
      {
        OddChar += Character[i];
      }
      else
      {
        EvenChar += Character[i];
      }
    }
 
    // Final string
    OddChar += EvenChar;
 
    // Return the final string
    return OddChar;
  }
 
  // Driver code
  static void Main()
  {
     
    // Given string
    string s = "abcd1234";
 
    // Returns the sorted string
    Console.WriteLine(sortString(s.ToCharArray()));
  }
}
 
// This code is contributed by divyehrabadiya07
Output: 
1324bdac

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :