
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Majority Element in C++
- Majority Element II in C++
- Shortest Palindrome in C++
- Majority Element in Java
- Majority Element in Python
- Check for Majority Element in a sorted array in C++
- Shortest Common Supersequence in C++
- Substring in C#
- Substring in C++
- Shortest Word Distance II in C++
- Shortest Word Distance III in C++
- Find the Shortest Superstring in C++
- Replace substring with another substring C++
- Shortest Path in Binary Matrix in C++
- Shortest Distance to Target Color in C++
