# Shortest Majority Substring in C++

C++Server Side ProgrammingProgramming

Suppose we have a lowercase alphabet string s, we have to find the length of the shortest substring (minimum length is 2) such that some letter appears more than the other letters combined. If we cannot find any solution, then return -1.

So, if the input is like "abbbcde", then the output will be 2, the substring "bb" has minimum length and this appears more than other letters.

To solve this, we will follow these steps −

• Define a function ok(), this will take an array cnt,

• total := 0, maxVal := 0

• for each element it in cnt, do

• total := total + it

• maxVal := maximum of maxVal and it

• return true when maxVal > (total - maxVal)

• From the main method, do the following −

• n := size of s

• ret := inf

• for initialize i := 0, when i < n, update (increase i by 1), do −

• if i + 1 < n and s[i] is same as s[i + 1], then −

• return 2

• otherwise when i + 2 < n and s[i] is same as s[i + 2], then −

• ret := 3

• return (if ret is same as inf, then -1, otherwise ret)

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool ok(vector <int>& cnt){
int total = 0;
int maxVal = 0;
for(auto& it : cnt){
total += it;
maxVal = max(maxVal, it);
}
return maxVal > (total - maxVal);
}
int solve(string s) {
int n = s.size();
int ret = INT_MAX;
for(int i = 0; i < n; i++){
if(i + 1 < n && s[i] == s[i + 1]){
return 2;
}else if(i + 2 < n && s[i] == s[i + 2]){
ret = 3;
}
}
return ret == INT_MAX ? -1 : ret;
}
};
int main(){
Solution ob;
cout << (ob.solve("abbbcde"));
}

## Input

"abbbcde"

## Output

2
Published on 02-Sep-2020 12:28:22