Open In App

Minimum characters to be replaced in given String to make all characters same

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

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: 9
Explanation: Replace all the characters except ‘e’ of the string with ‘e’.

Input: str=”data”
Output: 2

 

Brute Force Approach: In this approach, we are iterating through all the possible characters from ‘a’ to ‘z’ and counting the cost to convert all the other characters to the current character. We are taking the minimum cost of all the characters and returning it as the result.

  • Initialize a variable min_cost as INT_MAX.
  • Traverse all possible characters ch from ‘a’ to ‘z’.
    • Initialize a variable cost as 0.
    • Traverse the string word from index i = 0 to N-1.
      • If the character at index i is not equal to ch, increment the cost by 1.
    • Update min_cost as the minimum of min_cost and cost.
  • Return min_cost as the minimum characters to be replaced to make all characters of the string word the same.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum characters
// to be replaced to make all characters
// of string str same
int minCost(char* word, int N)
{
    int min_cost = INT_MAX;
    for (char ch = 'a'; ch <= 'z'; ch++) {
        int cost = 0;
        for (int i = 0; i < N; i++) {
            if (word[i] != ch) {
                cost++;
            }
        }
        min_cost = min(min_cost, cost);
    }
 
    return min_cost;
}
 
// Driver Code
int main()
{
    char str[] = "data";
    int N = sizeof(str) / sizeof(char);
 
    cout << minCost(str, N - 1);
    return 0;
}


Java




// Java code for above approach
import java.util.Arrays;
 
public class GFG {
    // Function to find the minimum characters
    // to be replaced to make all characters
    // of string str same
    static int minCost(char[] word, int N) {
        int min_cost = Integer.MAX_VALUE;
        for (char ch = 'a'; ch <= 'z'; ch++) {
            int cost = 0;
            for (int i = 0; i < N; i++) {
                if (word[i] != ch) {
                    cost++;
                }
            }
            min_cost = Math.min(min_cost, cost);
        }
 
        return min_cost;
    }
 
    // Driver Code
    public static void main(String[] args) {
        char[] str = "data".toCharArray();
        int N = str.length;
 
        System.out.println(minCost(str, N));
    }
}
 
// This code is contributed by Utkarsh Kumar.


Python3




# Function to find the minimum characters
# to be replaced to make all characters
# of string str same
def min_cost(word):
    min_cost = float('inf')
    for ch in range(ord('a'), ord('z') + 1):
        cost = 0
        for char in word:
            if char != chr(ch):
                cost += 1
        min_cost = min(min_cost, cost)
    return min_cost
 
# Driver Code
if __name__ == "__main__":
    word = "data"
    N = len(word)
    print(min_cost(word))


C#




using System;
 
class Program
{
    // Function to find the minimum characters
    // to be replaced to make all characters
    // of string str same
    static int MinCost(char[] word)
    {
        int min_cost = int.MaxValue;
 
        // Iterate over each character from 'a' to 'z'
        for (char ch = 'a'; ch <= 'z'; ch++)
        {
            int cost = 0;
 
            // Count the number of characters that need to be replaced
            for (int i = 0; i < word.Length; i++)
            {
                if (word[i] != ch)
                {
                    cost++;
                }
            }
 
            // Update the minimum cost if the current character's replacement cost is lower
            min_cost = Math.Min(min_cost, cost);
        }
 
        return min_cost;
    }
 
    // Driver Code
    static void Main(string[] args)
    {
        char[] str = "data".ToCharArray();
        int N = str.Length;
        Console.WriteLine(MinCost(str));
    }
}


Javascript




// Function to find the minimum characters
// to be replaced to make all characters
// of string str same
function minCost(word, N) {
    let min_cost = Number.MAX_SAFE_INTEGER;
    for (let ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ch++) {
        let cost = 0;
        for (let i = 0; i < N; i++) {
            if (word[i] != String.fromCharCode(ch)) {
                cost++;
            }
        }
        min_cost = Math.min(min_cost, cost);
    }
 
    return min_cost;
}
 
// Driver Code
let str = "data";
let N = str.length;
 
console.log(minCost(str, N));


Output:

2

Time Complexity: O(26*N)
Auxiliary Space: O(1)

Efficient Approach: The minimum number of characters to be replaced to make all characters the same is basically the number of characters not equal to the most frequent character, i.e. N – (frequency of most frequent character). Now follow the steps below to solve this problem:

  1. Store Frequencies of all characters in vector freq
  2. Find the maximum frequency mxfreq.
  3. Return (N – mxfreq) as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum characters
// to be replaced to make all characters
// of string str same
int minCost(char* word, int N)
{
    int mxfreq = 0;
    vector<int> freq(26, 0);
 
    for (int i = 0; i < strlen(word); i++) {
        freq[word[i] - 'a']++;
        mxfreq = max(mxfreq,
                     freq[word[i] - 'a']);
    }
 
    return N - mxfreq;
}
 
// Driver Code
int main()
{
    char str[] = "data";
    int N = sizeof(str) / sizeof(char);
 
    cout << minCost(str, N - 1);
    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 characters
// to be replaced to make all characters
// of string str same
static int minCost(String word, int N)
{
    int mxfreq = 0;
    int[] freq = new int[26];
 
    for (int i = 0; i < N; i++) {
          char ch = word.charAt(i);
        freq[ch - 'a']++;
        mxfreq = Math.max(mxfreq, freq[ch - 'a']);
    }
 
    return N - mxfreq;
}
 
    public static void main (String[] args) {
      
           String str = "data";
        int N = str.length();
        System.out.println(minCost(str, N - 1));
    }
}
 
// This code is contributed by hrithikgarg03188


Python3




# Python code for the above approach
 
# Function to find the minimum characters
# to be replaced to make all characters
# of string str same
def minCost(word, N):
    mxfreq = 0;
    freq = [0] * 26
    for i in range(len(word)):
        freq[ord(word[i]) - ord('a')] = freq[ord(word[i]) - ord('a')] + 1;
        mxfreq = max(mxfreq, freq[ord(word[i]) -  ord('a')]);
    return N - mxfreq + 1;
 
# Driver Code
str = "data";
N = len(str)
 
print(minCost(str, N - 1));
 
# This code is contributed by Saurabh Jaiswal


C#




// C# program for the above approach
using System;
class GFG
{
 
  // Function to find the minimum characters
  // to be replaced to make all characters
  // of string str same
  static int minCost(string word, int N)
  {
    int mxfreq = 0;
    int[] freq = new int[26];
 
    for (int i = 0; i < N; i++) {
      char ch = word[i];
      freq[ch - 'a']++;
      mxfreq = Math.Max(mxfreq, freq[ch - 'a']);
    }
 
    return N - mxfreq;
  }
 
  // Driver code
  public static void Main ()
  {
 
    string str = "data";
    int N = str.Length;
    Console.WriteLine(minCost(str, N - 1));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find the minimum characters
       // to be replaced to make all characters
       // of string str same
       function minCost(word, N) {
           let mxfreq = 0;
           let freq = new Array(26).fill(0);
           for (let i = 0; i < word.length; i++) {
               freq[word[i].charCodeAt(0) - 'a'.charCodeAt(0)] =
               freq[word[i].charCodeAt(0) - 'a'.charCodeAt(0)] + 1;
               mxfreq = Math.max(mxfreq, freq[word[i].charCodeAt(0) -
               'a'.charCodeAt(0)]);
           }
           return N - mxfreq + 1;
       }
 
       // Driver Code
 
       let str = "data";
       let N = str.length;
 
       document.write(minCost(str, N - 1));
 
        // This code is contributed by Potta Lokesh
   </script>


Output

2






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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads