
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Shortest Majority Substring in C++
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
#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
- Related Questions & Answers
- Majority Element in C++
- Majority Element II in C++
- Shortest Palindrome in C++
- Majority Element in Java
- Majority Element in Python
- Shortest Common Supersequence in C++
- Substring in C#
- Substring in C++
- Replace substring with another substring C++
- Find the Shortest Superstring in C++
- Shortest Word Distance II in C++
- Shortest Word Distance III in C++
- Check for Majority Element in a sorted array in C++
- C# Substring() Method
- Shortest Path in Binary Matrix in C++