Open In App

Minimum number of conversions to make the frequency of all characters odd

Last Updated : 24 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given string str of lower case alphabets, the task is to output the minimum number of conversions to be made such that all characters are repeated an odd number of times, if the task is not possible, then print -1. Any alphabet can be converted into any other lower-case alphabet.

Examples:

Input: str = “geeksforgeeks”
Output: 2
Explanation: Convert one ‘g’ to ‘e’ and convert one ‘k’ to ‘s’

Input: str = “geeks”
Output: 1
Explanation: Convert ‘e’ to any character that is not present in the string

 

Approach: The given problem can be solved using a hashmap. The idea is to count the number of alphabets repeating an even number of times and storing their frequencies in the hashmap. The below approach can be followed to solve the problem:

  • Iterate the string and put all characters in the hashmap:
  • If the character is already present in the hashmap then increase its frequency by 1
  • Iterate the hashmap and count the number of characters with even frequency and store it in a variable count
  • If the value of count is:
    • Even, then return count / 2
  • Odd and the size of hashmap is:
    • Less than 26 then return count / 2 + 1 
    • Equal to 26 then return -1

C++




// C++ implementation for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return minimum
// number of conversions required
int maxconv(string s)
{
    // Declare a hashmap
    unordered_map<char, int> map;
 
    // Insert character into the map
    for (auto x : s) {
 
        // Increment the frequency of the
        // character present in the string
        map[x]++;
    }
 
    // Count to store number of even
    // frequency elements
    int count = 0;
 
    // Loop to calculate characters
    // with even frequency
    for (auto z : map) {
 
        // If frequency is even
        if (z.second % 2 == 0)
 
            // Increment the count
            count++;
    }
 
    // If characters with even
    // frequency are even
    if (count % 2 == 0)
 
        // return count / 2 as the answer
        return count / 2;
 
    // If characters with even
    // frequency are even are odd
    else if (count % 2 != 0) {
 
        // If map contains less than
        // 26 distinct characters
        if (map.size() < 26) {
 
            // Return count / 2 + 1
            // as the answer
            return (count / 2) + 1;
        }
        else {
 
            // If map contains 26
            // distinct characters
            return -1;
        }
    }
}
int main()
{
    // Initialize the string
    string s = "geeksforgeeks";
 
    // Call the function and
    // print the output
    cout << maxconv(s) << "\n";
}


Java




// Java code for the above approach
import java.util.*;
class GFG
{
   
    // Function to return minimum
    // number of conversions required
    static int maxconv(String s)
    {
       
        // Declare a hashmap
        HashMap<Character, Integer> map
            = new HashMap<Character, Integer>();
 
        // Converting given string to char array
 
        char[] strArray =s.toCharArray();
 
        // Insert character into the map
        for (char c : strArray) {
            if (map.containsKey(c)) {
 
                // If char is present in charCountMap,
                // incrementing it's count by 1
                map.put(c, map.get(c) + 1);
            }
            else {
 
                // If char is not present in charCountMap,
                // putting this char to charCountMap with 1
                // as it's value
                map.put(c, 1);
            }
        }
 
        // Count to store number of even
        // frequency elements
        int count = 0;
 
        // Loop to calculate characters
        // with even frequency
        for (Map.Entry entry : map.entrySet())
        {
            if ((int)entry.getValue() % 2 == 0)
            {
               
                // Increment the count
                count++;
            }
        }
 
        // If characters with even
        // frequency are even
        if ((count % 2) == 0)
 
            // return count / 2 as the answer
            return count / 2;
 
        // If characters with even
        // frequency are even are odd
        else if (count % 2 != 0) {
 
            // If map contains less than
            // 26 distinct characters
            if (map.size() < 26) {
 
                // Return count / 2 + 1
                // as the answer
                return (count / 2) + 1;
            }
            else {
 
                // If map contains 26
                // distinct characters
                return -1;
            }
        }
      return -1;
    }
    public static void main(String[] args)
    {
       
        // Initialize the string
        String s = "geeksforgeeks";
 
        // Call the function and
        // print the output
 
        System.out.println(maxconv(s));
    }
}
 
// This code is contributed by Potta Lokesh


Python3




# python implementation for the above approach
 
# Function to return minimum
# number of conversions required
def maxconv(s):
 
    # Declare a hashmap
    map = {}
 
    # Insert character into the map
    for x in s:
 
        # Increment the frequency of the
        # character present in the string
        if x in map:
            map[x] += 1
        else:
            map[x] = 1
 
        # Count to store number of even
        # frequency elements
    count = 0
 
    # Loop to calculate characters
    # with even frequency
    for z in map:
 
                # If frequency is even
        if (map[z] % 2 == 0):
 
                        # Increment the count
            count += 1
 
        # If characters with even
        # frequency are even
    if (count % 2 == 0):
 
                # return count / 2 as the answer
        return count // 2
 
        # If characters with even
        # frequency are even are odd
    elif (count % 2 != 0):
 
        # If map contains less than
        # 26 distinct characters
        if (len(map) < 26):
 
            # Return count / 2 + 1
            # as the answer
            return (count // 2) + 1
 
        else:
 
            # If map contains 26
            # distinct characters
            return -1
 
if __name__ == "__main__":
 
        # Initialize the string
    s = "geeksforgeeks"
 
    # Call the function and
    # print the output
    print(maxconv(s))
 
    # This code is contributed by rakeshsahni


C#




// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
    // Function to return minimum
    // number of conversions required
    static int maxconv(String s)
    {
 
        // Declare a hashmap
        Dictionary<char, int> map = new Dictionary<char, int>();
 
        // Converting given string to char array
        char[] strArray = s.ToCharArray();
 
        // Insert character into the map
        foreach (char c in strArray)
        {
            if (map.ContainsKey(c))
            {
 
                // If char is present in charCountMap,
                // incrementing it's count by 1
                map = map + 1;
            }
            else
            {
 
                // If char is not present in charCountMap,
                // putting this char to charCountMap with 1
                // as it's value
                map = 1;
            }
        }
 
        // Count to store number of even
        // frequency elements
        int count = 0;
 
        // Loop to calculate characters
        // with even frequency
        foreach (int entry in map.Values)
        {
            if (entry % 2 == 0)
            {
 
                // Increment the count
                count++;
            }
        }
 
        // If characters with even
        // frequency are even
        if ((count % 2) == 0)
 
            // return count / 2 as the answer
            return count / 2;
 
        // If characters with even
        // frequency are even are odd
        else if (count % 2 != 0)
        {
 
            // If map contains less than
            // 26 distinct characters
            if (map.Count < 26)
            {
 
                // Return count / 2 + 1
                // as the answer
                return (count / 2) + 1;
            }
            else
            {
 
                // If map contains 26
                // distinct characters
                return -1;
            }
        }
        return -1;
    }
   
    public static void Main()
    {
 
        // Initialize the string
        String s = "geeksforgeeks";
 
        // Call the function and
        // print the output
        Console.Write(maxconv(s));
    }
}
 
// This code is contributed by gfgking


Javascript




<script>
// Javascript implementation for the above approach
 
// Function to return minimum
// number of conversions required
function maxconv(s)
{
 
  // Declare a hashmap
  let map = new Map();
 
  // Insert character into the map
  for (x of s) {
 
    // Increment the frequency of the
    // character present in the string
    if (map.has(x)) {
      map.set(x, map.get(x) + 1)
    } else {
      map.set(x, 1)
    }
  }
 
  // Count to store number of even
  // frequency elements
  let count = 0;
 
  // Loop to calculate characters
  // with even frequency
  for (z of map) {
 
    // If frequency is even
    if (z[1] % 2 == 0)
 
      // Increment the count
      count++;
  }
 
  // If characters with even
  // frequency are even
  if (count % 2 == 0)
 
    // return count / 2 as the answer
    return Math.floor(count / 2);
 
  // If characters with even
  // frequency are even are odd
  else if (count % 2 != 0) {
 
    // If map contains less than
    // 26 distinct characters
    if (map.length < 26) {
 
      // Return count / 2 + 1
      // as the answer
      return Math.floor(count / 2) + 1;
    }
    else {
 
      // If map contains 26
      // distinct characters
      return -1;
    }
  }
}
 
// Initialize the string
let s = "geeksforgeeks";
 
// Call the function and
// print the output
document.write(maxconv(s))
 
// This code is contributed by gfgking.
</script>


Output

2

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



Similar Reads

Minimum characters to be replaced to make frequency of all characters same
Given a string S consisting of alphabets ['A' - 'Z'], the task is to find the minimum number of operations required to make frequency of every character equal. In one operation any character of the string can be chosen and replaced with another valid character.Examples: Input: S = "ABCB" Output: 1 Explanation: In the given string character 'C' can
6 min read
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Make all the elements of array odd by incrementing odd-indexed elements of odd-length subarrays
Given an array arr[] of size N, the task is to make all the array elements odd by choosing an odd length subarray of arr[] and increment all odd positioned elements by 1 in this subarray. Print the count of such operations required. Examples: Input: arr[] = {2, 3, 4, 3, 5, 3, 2}Output: 2Explanation:In first operation, choose the subarray {2, 3, 4}
9 min read
Minimum steps required to convert X to Y where a binary matrix represents the possible conversions
Given a binary matrix of size NxN where 1 denotes that the number i can be converted to j, and 0 denotes it cannot be converted to. Also given are two numbers X(&lt;N)and Y(&lt;N), the task is to find the minimum number of steps required to convert the number X to Y. If there is no such way possible, print -1. Examples: Input: {{ 0, 0, 0, 0, 0, 0,
13 min read
Minimum operations to make frequency of all characters equal K
Given a string S of length N. The task is to find the minimum number of steps required on strings, so that it has exactly K different alphabets all with the same frequency.Note: In one step, we can change a letter to any other letter.Examples: Input: S = "abbc", N = 4, K = 2 Output: 1 In one step convert 'c' to 'a'. Hence string has two different l
8 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Number System and Base Conversions
Electronic and Digital systems may use a variety of different number systems, (e.g. Decimal, Hexadecimal, Octal, Binary), or even Duodecimal or less well known but better named Uncial. All the other bases other than Decimal result from computer usage. Uncial (named from Latin for 1/12 "uncia" the base twelve analogue of Decimal from the Latin word
5 min read
Minimum number of operations to move all uppercase characters before all lower case characters
Given a string str, containing upper case and lower case characters. In a single operations, any lowercase character can be converted to an uppercase character and vice versa. The task is to print the minimum number of such operations required so that the resultant string consists of zero or more upper case characters followed by zero or more lower
8 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
Minimum characters to be replaced in given String to make all characters same
Given a string str of size N consisting of lowercase English characters, the task is to find the minimum characters to be replaced to make all characters of string str same. Any character can be replaced by any other character. Example: Input: str="geeksforgeeks"Output: 9Explanation: Replace all the characters except 'e' of the string with 'e'. Inp
7 min read
Practice Tags :