Open In App

Rearrange a string in sorted order followed by the integer sum

Last Updated : 15 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string containing uppercase alphabets and integer digits (from 0 to 9), the task is to print the alphabets in the order followed by the sum of digits.

Examples:  

Input : AC2BEW3
Output : ABCEW5
Alphabets in the lexicographic order 
followed by the sum of integers(2 and 3).
Recommended Practice

1- Start traversing the given string.
a) If an alphabet comes increment its
occurrence count into a hash_table.
b) If an integer comes then store it
separately by summing up everytime.
2- Using hash_table append all the
characters first into a string and
then at the end, append the integers
sum.
3- Return the resultant string.

Implementation:

C++




// C++ program for above implementation
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// Function to return string in lexicographic
// order followed by integers sum
string arrangeString(string str)
{
    int char_count[MAX_CHAR] = {0};
    int sum = 0;
  
    // Traverse the string
    for (int i = 0; i < str.length(); i++)
    {
        // Count occurrence of uppercase alphabets
        if (str[i]>='A' && str[i] <='Z')
            char_count[str[i]-'A']++;
  
        //Store sum of integers
        else
            sum = sum + (str[i]-'0');
    }
  
    string res = "";
  
    // Traverse for all characters A to Z
    for (int i = 0; i < MAX_CHAR; i++)
    {
        char ch = (char)('A'+i);
  
        // Append the current character
        // in the string no. of times it
        //  occurs in the given string
        while (char_count[i]--)
            res = res + ch;
    }
  
    // Append the sum of integers
    if (sum > 0)
        res = res + to_string(sum);
  
    // return resultant string
    return res;
}
  
// Driver program
int main()
{
    string str = "ACCBA10D2EW30";
    cout << arrangeString(str);
    return 0;
}


Java




// Java program for above implementation
  
class Test
{
    static final int MAX_CHAR = 26;
      
    // Method to return string in lexicographic
    // order followed by integers sum
    static String arrangeString(String str)
    {
        int char_count[] = new int[MAX_CHAR];
        int sum = 0;
       
        // Traverse the string
        for (int i = 0; i < str.length(); i++)
        {
            // Count occurrence of uppercase alphabets
            if (Character.isUpperCase(str.charAt(i)))
                char_count[str.charAt(i)-'A']++;
       
            //Store sum of integers
            else
                sum = sum + (str.charAt(i)-'0');
              
        }
       
        String res = "";
       
        // Traverse for all characters A to Z
        for (int i = 0; i < MAX_CHAR; i++)
        {
            char ch = (char)('A'+i);
       
            // Append the current character
            // in the string no. of times it
            //  occurs in the given string
            while (char_count[i]-- != 0)
                res = res + ch;
        }
       
        // Append the sum of integers
        if (sum > 0)
            res = res + sum;
       
        // return resultant string
        return res;
    }
      
    // Driver method
    public static void main(String args[]) 
    {
        String str = "ACCBA10D2EW30";
        System.out.println(arrangeString(str));
    }
}


Python3




# Python3 program for above implementation
MAX_CHAR = 26
  
# Function to return string in lexicographic
# order followed by integers sum
def arrangeString(string):
    char_count = [0] * MAX_CHAR
    s = 0
  
    # Traverse the string
    for i in range(len(string)):
  
        # Count occurrence of uppercase alphabets
        if string[i] >= "A" and string[i] <= "Z":
            char_count[ord(string[i]) - ord("A")] += 1
  
        # Store sum of integers
        else:
            s += ord(string[i]) - ord("0")
  
    res = ""
  
    # Traverse for all characters A to Z
    for i in range(MAX_CHAR):
        ch = chr(ord("A") + i)
  
        # Append the current character
        # in the string no. of times it
        # occurs in the given string
        while char_count[i]:
            res += ch
            char_count[i] -= 1
  
    # Append the sum of integers
    if s > 0:
        res += str(s)
  
    # return resultant string
    return res
  
# Driver code
if __name__ == "__main__":
    string = "ACCBA10D2EW30"
    print(arrangeString(string))
  
# This code is contributed by
# sanjeev2552


C#




// C# program for above implementation
using System;
  
class GFG {
      
    static int MAX_CHAR = 26;
      
    // Method to return string in lexicographic
    // order followed by integers sum
    static String arrangeString(string str)
    {
        int []char_count = new int[MAX_CHAR];
        int sum = 0;
      
        // Traverse the string
        for (int i = 0; i < str.Length; i++)
        {
              
            // Count occurrence of uppercase 
            // alphabets
            if (char.IsUpper(str[i]))
                char_count[str[i]-'A']++;
      
            //Store sum of integers
            else
                sum = sum + (str[i]-'0');
              
        }
      
        string res = "";
      
        // Traverse for all characters A to Z
        for (int i = 0; i < MAX_CHAR; i++)
        {
            char ch = (char)('A' + i);
      
            // Append the current character
            // in the string no. of times it
            // occurs in the given string
            while (char_count[i]-- != 0)
                res = res + ch;
        }
      
        // Append the sum of integers
        if (sum > 0)
            res = res + sum;
      
        // return resultant string
        return res;
    }
      
    // Driver method
    public static void Main() 
    {
        string str = "ACCBA10D2EW30";
        Console.Write(arrangeString(str));
    }
}
  
// This code is contributed by nitin mittal.


PHP




<?php 
// PHP program for above implementation
  
$MAX_CHAR = 26;
  
// Function to return string in lexicographic
// order followed by integers sum
function arrangeString($str)
{
    global $MAX_CHAR;
    $char_count = array_fill(0, $MAX_CHAR, NULL);
    $sum = 0;
  
    // Traverse the string
    for ($i = 0; $i < strlen($str); $i++)
    {
        // Count occurrence of uppercase alphabets
        if ($str[$i] >= 'A' && $str[$i] <= 'Z')
            $char_count[ord($str[$i]) -     
                        ord('A')]++;
  
        // Store sum of integers
        else
            $sum = $sum + (ord($str[$i]) - 
                           ord('0'));
    }
  
    $res = "";
  
    // Traverse for all characters A to Z
    for ($i = 0; $i < $MAX_CHAR; $i++)
    {
        $ch = chr(ord('A') + $i);
  
        // Append the current character
        // in the string no. of times it
        // occurs in the given string
        while ($char_count[$i]--)
            $res = $res . $ch;
    }
  
    // Append the sum of integers
    if ($sum > 0)
        $res = $res . strval($sum);
  
    // return resultant string
    return $res;
}
  
// Driver Code
$str = "ACCBA10D2EW30";
echo arrangeString($str);
  
// This code is contributed by ita_c
?>


Javascript




<script>
  
// Javascript program for above implementation
      
    let MAX_CHAR = 26;
      
    // Method to return string in lexicographic
    // order followed by integers sum
    function arrangeString(str)
    {
        let char_count = new Array(MAX_CHAR);
        for(let i=0;i<MAX_CHAR;i++)
        {
            char_count[i]=0;
        }
        let sum = 0;
         
        // Traverse the string
        for (let i = 0; i < str.length; i++)
        {
            // Count occurrence of uppercase alphabets
            if (str[i] >= "A" && str[i] <= "Z")
                char_count[str[i].charCodeAt(0)-
                'A'.charCodeAt(0)]++;
         
            //Store sum of integers
            else
                sum = sum + (str[i].charCodeAt(0)-
                '0'.charCodeAt(0));
                
        }
         
        let res = "";
         
        // Traverse for all characters A to Z
        for (let i = 0; i < MAX_CHAR; i++)
        {
            let ch = 
            String.fromCharCode('A'.charCodeAt(0)+i);
         
            // Append the current character
            // in the string no. of times it
            //  occurs in the given string
            while (char_count[i]-- != 0)
                res = res + ch;
        }
         
        // Append the sum of integers
        if (sum > 0)
            res = res + sum;
         
        // return resultant string
        return res;
    }
      
     // Driver method
    let str = "ACCBA10D2EW30";
    document.write(arrangeString(str));
      
    // This code is contributed by avanitrachhadiya2155
      
</script>


Output

AABCCDEW6

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

 



Similar Reads

Rearrange a string in the form of integer sum followed by the minimized character
Given a string including lowercase alphabets and numeric digits. The task is to construct another string which consists of the sum of digits followed by the sum of all alphabets minimized to a single character. If no numeric digit is present add 0 to the string. Note: Alphabet summation is done in this manner: a+a = b, d+y = c. Examples: Input: str
5 min read
Sorting rows of matrix in ascending order followed by columns in descending order
Given a matrix, sort the rows of matrix in ascending order followed by sorting the columns in descending order. Examples : Input : a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output : 7 8 9 4 5 6 1 2 3 Input : a[3][3] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; Output : 7 8 9 4 5 6 1 2 3 Approach: Traverse all rows one by one and sort rows in ascending o
10 min read
Sorting rows of matrix in descending order followed by columns in ascending order
Given a matrix of distinct elements. The task is to sort the rows of matrix in descending order followed by sorting the columns in ascending order. Examples: Input: a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output: 3 2 1 6 5 4 9 8 7 Input: a[3][3] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; Output: 3 2 1 6 5 4 9 8 7 Approach: Traverse all rows one by o
9 min read
Print 2-D co-ordinate points in ascending order followed by their frequencies
Given two arrays x[] and y[] where x[i] represents the x coordinate and y[i] represent the corresponding y coordinate of a 2-D point, the task is to print the coordinate points in ascending order followed by their frequencies.Examples: Input: x[] = {1, 2, 1, 1, 1}, y[] = {1, 1, 3, 1, 3} Output: 1 1 2 1 3 2 2 1 1Input: x[] = {-1, 2, 1, -1, 2}, y[] =
5 min read
Sort an array of strings in ascending order with each string sorted in descending order
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 asce
9 min read
Rearrange characters in a sorted string such that no pair of adjacent characters are the same
Given a sorted string S consisting of N lowercase characters, the task is to rearrange characters in the given string such that no two adjacent characters are the same. If it is not possible to rearrange as per the given criteria, then print "-1". Examples: Input: S = "aaabc"Output: abaca Input: S = "aa"Output: -1 Approach: The given problem can be
20 min read
Maximize Array sum after incrementing at most K elements followed by dividing array by X
Given an array, arr[] and two integers, K and X, the task is to maximize the sum of the array elements after at most K increments of any elements, then dividing all of the elements by X Example: Input: arr = {16, 15, 17}, K = 8, X = 10Output: 5Explanation: At most 8 increments are allowed. So, increment element at index 0 by 4 and element at index
8 min read
Maximize sum possible by selecting K array elements followed by decrementing them by 1
Given an array arr[] consisting of N positive integers and an integer K. In one operation, select an array element, add it to the sum and then decrement it by 1. The task is to print the maximum sum that can be obtained by performing the operation K times. Examples: Input: arr[] = {2, 5}, K = 4Output: 14Explanation:Perform the following operations
11 min read
String formed with middle character of every right substring followed by left sequentially
Given a string str of length N, the task is to decrypt it using a given set of decryption rules and print the decrypted string. The decryption rules are as follows: Start with the middle character of the string str and print it.Repetitively traverse the right substring and print its middle character.Repeat the same procedure for the left substring
5 min read
Check if a string can be split into substrings starting with N followed by N characters
Given a string str, the task is to check if it can be split into substrings such that each substring starts with a numeric value followed by a number of characters represented by that numeric integer. Examples: Input: str = "4g12y6hunter" Output: Yes Explanation: Substrings "4g12y" and "6hunter" satisfy the given condition Input: str = "31ba2a" Out
5 min read
Article Tags :
Practice Tags :