Minimize the length of string by removing occurrence of only one character
Given a string str containing only lowercase alphabets, the task is to minimize the length of the string after performing the following operation:
- Delete all occurrences of any one character from this string.
Examples:
Input: str = “abccderccwq”
Output: 7
character ‘c’ will be deleted since it has maximum occurrence.
Input: str = “dddded”
Output: 1
Explanation: character ‘d’ will be deleted
Approach:
- Maintain the frequency of each and every character in an array.
- Find the character with the maximum frequency.
- Finally, subtract the length of the original string with the frequency of that character to get the desired answer.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumLength(string s)
{
int maxOcc = 0, n = s.length();
int arr[26] = {0};
for ( int i = 0; i < n; i++)
arr[s[i] - 'a' ]++;
for ( int i = 0; i < 26; i++)
if (arr[i] > maxOcc)
maxOcc = arr[i];
return (n - maxOcc);
}
int main()
{
string str = "afddewqd" ;
cout << minimumLength(str);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int minimumLength(String s)
{
int maxOcc = 0 , n = s.length();
int arr[] = new int [ 26 ];
for ( int i = 0 ; i < n; i++)
arr[s.charAt(i) - 'a' ]++;
for ( int i = 0 ; i < 26 ; i++)
if (arr[i] > maxOcc)
maxOcc = arr[i];
return (n - maxOcc);
}
public static void main (String[] args) {
String str = "afddewqd" ;
System.out.println( minimumLength(str));
}
}
|
Python 3
def minimumLength(s) :
maxOcc = 0
n = len (s)
arr = [ 0 ] * 26
for i in range (n) :
arr[ ord (s[i]) - ord ( 'a' )] + = 1
for i in range ( 26 ) :
if arr[i] > maxOcc :
maxOcc = arr[i]
return n - maxOcc
if __name__ = = "__main__" :
str = "afddewqd"
print (minimumLength( str ))
|
C#
using System;
class GFG
{
static int minimumLength(String s)
{
int maxOcc = 0, n = s.Length;
int []arr = new int [26];
for ( int i = 0; i < n; i++)
arr[s[i] - 'a' ]++;
for ( int i = 0; i < 26; i++)
if (arr[i] > maxOcc)
maxOcc = arr[i];
return (n - maxOcc);
}
public static void Main (String[] args)
{
String str = "afddewqd" ;
Console.WriteLine( minimumLength(str));
}
}
|
Javascript
<script>
function minimumLength(s)
{
var maxOcc = 0, n = s.length;
var arr = Array(26).fill(0);
for ( var i = 0; i < n; i++)
arr[s[i].charCodeAt(0) - 'a' .charCodeAt(0)]++;
for ( var i = 0; i < 26; i++)
if (arr[i] > maxOcc)
maxOcc = arr[i];
return (n - maxOcc);
}
var str = "afddewqd" ;
document.write( minimumLength(str));
</script>
|
Time complexity: O(n) where n is the length of string
Auxiliary space: O(1) since constant space is being used
Last Updated :
03 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...