 Open in App
Not now

# Minimize cost to convert all occurrences of each distinct character to lowercase or uppercase

• Last Updated : 08 Aug, 2022

Given a string S consisting of N alphabets and two positive integers L and U, representing the cost of converting any character to lowercase and uppercase respectively, the task is to modify the string S such that every occurrence of the alphabet in the string S is either lowercase or uppercase and the cost of converting the original string to the modified string must be minimum.

Examples:

Input: S = “aabbAA”, L = 1, U = 1
Output: AAbbAA
Explanation:
The cost of converting “aabbAA” to “AAbbAA” is 1*2 = 2, which is minimum among all the possible combinations of conversions.

Input: S = “aApbBp”, L = 1, U = 2
Output: aapbbp

Approach: The given problem can be solved by using the Greedy Approach, the idea is to check if the cost to convert all occurrences of a character to its lowercase is less than that of uppercase, then convert all its occurrences to lowercase. Otherwise, convert all its occurrences to uppercase. Follow the steps below to solve the problem:

• Store the frequency of all lowercase and uppercase characters in the arrays lowerFreq and upperFreq respectively.
• Initialize another array say, result as 0 where result[i] = 1 denotes that the ith character needs to be in lowercase, otherwise it needs to be in uppercase.
• Iterate over the range [0, 25] using the variable i and perform the following steps:
• Store the cost to convert every occurrence of character i to lowercase and uppercase in variables costLower and costUpper respectively.
• Find the value of costLower by multiplying the cost to convert 1 character to lowercase, i.e., L with its uppercase frequencies, i.e., upperFreq[i]. Similarly, find the value of costUpper by multiplying U with lowerFreq[i].
• If the value of costLower < costUpper, then update the value of result[i] to 1.
• Traverse the string S using the variable i and perform the following steps:
• After completing the above steps, print the string S as the modified string.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Function to find the minimum cost` `// to convert all distinct characters` `// to either uppercase or lowercase` `void` `minimumCost(string s, ``int` `L, ``int` `U)` `{` `    ``// Store the size of the string` `    ``int` `N = s.size();`   `    ``string ans = ``""``;`   `    ``// Stores the frequency of lowercase` `    ``// & uppercase characters respectively` `    ``int` `lowerFreq = { 0 };` `    ``int` `upperFreq = { 0 };`   `    ``// Traverse the string S` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// Update uppercase` `        ``// frequency of s[i]` `        ``if` `(``isupper``(s[i]))` `            ``upperFreq[s[i] - ``'A'``]++;`   `        ``// Otherwise, update lowercase` `        ``// frequency of s[i]` `        ``else` `            ``lowerFreq[s[i] - ``'a'``]++;` `    ``}`   `    ``// Stores if the i-th character` `    ``//should be lowercase or not` `    ``int` `result = { 0 };`   `    ``// Iterate over the range [0, 25]` `    ``for` `(``int` `i = 0; i < 26; i++) {`   `        ``// If the character is present` `        ``// in the string` `        ``if` `(lowerFreq[i] != 0` `            ``|| upperFreq[i] != 0) {`   `            ``// Store the cost to convert` `            ``// every occurrence of i to` `            ``// uppercase and lowercase` `            ``int` `costToUpper = U * lowerFreq[i];` `            ``int` `costToLower = L * upperFreq[i];`   `            ``// Update result[i] to 1 if` `            ``// lowercase cost is less` `            ``if` `(costToLower < costToUpper) {` `                ``result[i] = 1;` `            ``}` `        ``}` `    ``}`   `    ``// Traverse the string S` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// Store the index` `        ``// of the character` `        ``int` `index = 0;`   `        ``if` `(``islower``(s[i]))` `            ``index = s[i] - ``'a'``;` `        ``else` `            ``index = s[i] - ``'A'``;`   `        ``// Convert the current character` `        ``// to uppercase or lowercase` `        ``// according to the condition` `        ``if` `(result[index] == 1) {`   `            ``// Update s[i]` `            ``s[i] = ``tolower``(s[i]);` `        ``}` `        ``else` `{`   `            ``// Update s[i]` `            ``s[i] = ``toupper``(s[i]);` `        ``}` `    ``}`   `    ``// Print the modified string` `    ``cout << s;` `}`   `// Driver Code` `int` `main()` `{` `    ``string S = ``"aabbAA"``;` `    ``int` `L = 1, U = 1;` `    ``minimumCost(S, L, U);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.io.*;` `import` `java.lang.*;` `import` `java.util.*;`   `class` `GFG{`   `// Function to find the minimum cost` `// to convert all distinct characters` `// to either uppercase or lowercase` `static` `void` `minimumCost(String str, ``int` `L, ``int` `U)` `{` `    `  `    ``// Store the size of the string` `    ``int` `N = str.length();` `    ``char` `s[] = str.toCharArray();`   `    ``String ans = ``""``;`   `    ``// Stores the frequency of lowercase` `    ``// & uppercase characters respectively` `    ``int` `lowerFreq[] = ``new` `int``[``26``];` `    ``int` `upperFreq[] = ``new` `int``[``26``];`   `    ``// Traverse the string S` `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `        `  `        ``// Update uppercase` `        ``// frequency of s[i]` `        ``if` `(Character.isUpperCase(s[i]))` `            ``upperFreq[s[i] - ``'A'``]++;`   `        ``// Otherwise, update lowercase` `        ``// frequency of s[i]` `        ``else` `            ``lowerFreq[s[i] - ``'a'``]++;` `    ``}`   `    ``// Stores if the i-th character` `    ``// should be lowercase or not` `    ``int` `result[] = ``new` `int``[``26``];`   `    ``// Iterate over the range [0, 25]` `    ``for``(``int` `i = ``0``; i < ``26``; i++) ` `    ``{` `        `  `        ``// If the character is present` `        ``// in the string` `        ``if` `(lowerFreq[i] != ``0` `|| upperFreq[i] != ``0``) ` `        ``{` `            `  `            ``// Store the cost to convert` `            ``// every occurrence of i to` `            ``// uppercase and lowercase` `            ``int` `costToUpper = U * lowerFreq[i];` `            ``int` `costToLower = L * upperFreq[i];`   `            ``// Update result[i] to 1 if` `            ``// lowercase cost is less` `            ``if` `(costToLower < costToUpper)` `            ``{` `                ``result[i] = ``1``;` `            ``}` `        ``}` `    ``}`   `    ``// Traverse the string S` `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `        `  `        ``// Store the index` `        ``// of the character` `        ``int` `index = ``0``;`   `        ``if` `(Character.isLowerCase(s[i]))` `            ``index = s[i] - ``'a'``;` `        ``else` `            ``index = s[i] - ``'A'``;`   `        ``// Convert the current character` `        ``// to uppercase or lowercase` `        ``// according to the condition` `        ``if` `(result[index] == ``1``)` `        ``{` `            `  `            ``// Update s[i]` `            ``s[i] = Character.toLowerCase(s[i]);` `        ``}` `        ``else` `        ``{` `            `  `            ``// Update s[i]` `            ``s[i] = Character.toUpperCase(s[i]);` `        ``}` `    ``}`   `    ``// Print the modified string` `    ``System.out.println(``new` `String(s));` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `    ``String S = ``"aabbAA"``;` `    ``int` `L = ``1``, U = ``1``;` `    ``minimumCost(S, L, U);` `}` `}`   `// This code is contributed by Kingash`

## Python3

 `# Python3 program for above approach`   `# Function to find the minimum cost` `# to convert all distinct characters` `# to either uppercase or lowercase` `def` `minimumCost(s, L, U):` `    `  `    ``ans ``=` `[]`   `    ``# Stores the frequency of lowercase` `    ``# & uppercase characters respectively` `    ``lowerFreq ``=` `[``0``] ``*` `26` `    ``upperFreq ``=` `[``0``] ``*` `26`   `    ``# Traverse the string S` `    ``for` `c ``in` `s:` `        ``if` `c.isupper():`   `        ``# Update uppercase` `        ``# frequency of s[i]` `            ``upperFreq[``ord``(c) ``-` `ord``(``'A'``)] ``+``=` `1`   `        ``# Otherwise, update lowercase` `        ``# frequency of s[i]` `        ``else``:` `            ``lowerFreq[``ord``(c) ``-` `ord``(``'a'``)] ``+``=` `1`   `    ``# stores if the i-th character` `    ``# should be lowercase or not` `    ``result ``=` `[``0``] ``*` `26`   `    ``# Iterate over the range [0, 25]` `    ``for` `i ``in` `range``(``26``):`   `        ``# If the character is present` `        ``# in the string` `        ``if` `lowerFreq[i] !``=` `0` `or` `upperFreq[i] !``=` `0``:`   `            ``# Store the cost to convert` `            ``# every occurrence of i to` `            ``# uppercase and lowercase` `            ``costToUpper ``=` `U ``*` `lowerFreq[i];` `            ``costToLower ``=` `L ``*` `upperFreq[i];`   `            ``# Update result[i] to 1 if` `            ``# lowercase cost is less` `            ``if` `costToLower < costToUpper:` `                ``result[i] ``=` `1`   `    ``# Traverse the string S` `    ``for` `i ``in` `range``(``len``(s)):`   `        ``# Store the index` `        ``# of the character` `        ``index ``=` `0`   `        ``if` `s[i].islower():` `            ``index ``=` `ord``(s[i]) ``-` `ord``(``'a'``)` `        ``else``:` `            ``index ``=` `ord``(s[i]) ``-` `ord``(``'A'``)`   `        ``# Convert the current character` `        ``# to uppercase or lowercase` `        ``# according to the condition` `        ``if` `result[index] ``=``=` `1``:`   `            ``# Update the character at the` `            ``# ith index of s` `            ``ans.append(s[i].lower())` `        ``else``:`   `            ``# Update the character at the` `            ``# ith index of s` `            ``ans.append(s[i].upper())`   `    ``s ``=` `''.join(ans)` `    `  `    ``# Print the modified string` `    ``print``(s)`   `# Driver code` `S ``=` `"aabbAA"` `L ``=` `1` `U ``=` `1`   `minimumCost(S, L, U)`   `# This code is contributed by Md Zaid Alam`

## C#

 `// C# program for the above approach` `using` `System;`   `class` `GFG {`   `    ``// Function to find the minimum cost` `    ``// to convert all distinct characters` `    ``// to either uppercase or lowercase` `    ``static` `void` `minimumCost(``string` `str, ``int` `L, ``int` `U)` `    ``{`   `        ``// Store the size of the string` `        ``int` `N = str.Length;` `        ``char``[] s = str.ToCharArray();`   `        ``// string ans = "";`   `        ``// Stores the frequency of lowercase` `        ``// & uppercase characters respectively` `        ``int``[] lowerFreq = ``new` `int``;` `        ``int``[] upperFreq = ``new` `int``;`   `        ``// Traverse the string S` `        ``for` `(``int` `i = 0; i < N; i++) {`   `            ``// Update uppercase` `            ``// frequency of s[i]` `            ``if` `(``char``.IsUpper(s[i]))` `                ``upperFreq[s[i] - ``'A'``]++;`   `            ``// Otherwise, update lowercase` `            ``// frequency of s[i]` `            ``else` `                ``lowerFreq[s[i] - ``'a'``]++;` `        ``}`   `        ``// Stores if the i-th character` `        ``// should be lowercase or not` `        ``int``[] result = ``new` `int``;`   `        ``// Iterate over the range [0, 25]` `        ``for` `(``int` `i = 0; i < 26; i++) {`   `            ``// If the character is present` `            ``// in the string` `            ``if` `(lowerFreq[i] != 0 || upperFreq[i] != 0) {`   `                ``// Store the cost to convert` `                ``// every occurrence of i to` `                ``// uppercase and lowercase` `                ``int` `costToUpper = U * lowerFreq[i];` `                ``int` `costToLower = L * upperFreq[i];`   `                ``// Update result[i] to 1 if` `                ``// lowercase cost is less` `                ``if` `(costToLower < costToUpper) {` `                    ``result[i] = 1;` `                ``}` `            ``}` `        ``}`   `        ``// Traverse the string S` `        ``for` `(``int` `i = 0; i < N; i++) {`   `            ``// Store the index` `            ``// of the character` `            ``int` `index = 0;`   `            ``if` `(``char``.IsLower(s[i]))` `                ``index = s[i] - ``'a'``;` `            ``else` `                ``index = s[i] - ``'A'``;`   `            ``// Convert the current character` `            ``// to uppercase or lowercase` `            ``// according to the condition` `            ``if` `(result[index] == 1) {`   `                ``// Update s[i]` `                ``s[i] = ``char``.ToLower(s[i]);` `            ``}` `            ``else` `{`   `                ``// Update s[i]` `                ``s[i] = ``char``.ToUpper(s[i]);` `            ``}` `        ``}`   `        ``// Print the modified string` `        ``Console.WriteLine(``new` `string``(s));` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``string` `S = ``"aabbAA"``;` `        ``int` `L = 1, U = 1;` `        ``minimumCost(S, L, U);` `    ``}` `}`   `// This code is contributed by ukasp.`

## Javascript

 ``

Output:

`AAbbAA`

Time Complexity: O(N) // only loop is used to traverse the entire string thus the algorithm takes linear time to perform all the operations
Auxiliary Space: O(1) // since no extra array is used the space required by the algorithm is constant

My Personal Notes arrow_drop_up
Related Articles