code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
|---|---|---|
// C++ program to convert a string from
// upper to lower case.
#include<stdio.h>
const int x = 32;
// Converts a string to lowercase
char * toLowerCase(char *a)
{
for (int i=0; a[i]!='\0'; i++)
a[i] = a[i] | x;
return a;
}
// Driver Code
int main()
{
char str[] = "SanjaYKannA";
printf("%s", toLowerCase(str));
return 0;
}
|
constant
|
linear
|
// CPP Program to find maximum
// lowercase alphabets present
// between two uppercase alphabets
#include <bits/stdc++.h>
using namespace std;
#define MAX_CHAR 26
// Function which computes the
// maximum number of distinct
// lowercase alphabets between
// two uppercase alphabets
int maxLower(string str)
{
int n = str.length();
// Ignoring lowercase characters in the
// beginning.
int i = 0;
for (; i < n; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
i++;
break;
}
}
// We start from next of first capital letter
// and traverse through remaining character.
int maxCount = 0;
int count[MAX_CHAR] = { 0 };
for (; i < n; i++) {
// If character is in uppercase,
if (str[i] >= 'A' && str[i] <= 'Z') {
// Count all distinct lower case
// characters
int currCount = 0;
for (int j = 0; j < MAX_CHAR; j++)
if (count[j] > 0)
currCount++;
// Update maximum count
maxCount = max(maxCount, currCount);
// Reset count array
memset(count, 0, sizeof(count));
}
// If character is in lowercase
if (str[i] >= 'a' && str[i] <= 'z')
count[str[i] - 'a']++;
}
return maxCount;
}
// Driver function
int main()
{
string str = "zACaAbbaazzC";
cout << maxLower(str);
return 0;
}
|
constant
|
linear
|
// CPP Program to find maximum
// lowercase alphabets present
// between two uppercase alphabets
#include <bits/stdc++.h>
using namespace std;
// Function which computes the
// maximum number of distinct
// lowercase alphabets between
// two uppercase alphabets
int maxLower(string str)
{
int n = str.length();
// Ignoring lowercase characters in the
// beginning.
int i = 0;
for (; i < n; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
i++;
break;
}
}
// We start from next of first capital letter
// and traverse through remaining character.
int maxCount = 0;
unordered_set<int> s;
for (; i < n; i++) {
// If character is in uppercase,
if (str[i] >= 'A' && str[i] <= 'Z') {
// Update maximum count if lowercase
// character before this is more.
maxCount = max(maxCount, (int)s.size());
// clear the set
s.clear();
}
// If character is in lowercase
if (str[i] >= 'a' && str[i] <= 'z')
s.insert(str[i]);
}
return maxCount;
}
// Driver function
int main()
{
string str = "zACaAbbaazzC";
cout << maxLower(str);
return 0;
}
|
linear
|
linear
|
// C++ program to convert a
// sentence to gOOGLE cASE.
#include <bits/stdc++.h>
using namespace std;
string convert(string str)
{
// Empty strings
string w = "", z = "";
// Convert input string to upper case
transform(str.begin(), str.end(),
str.begin(), ::toupper);
str += " ";
for(int i = 0; i < str.length(); i++)
{
// Check if character is not a space
// and adding it to string w
char ch = str[i];
if (ch != ' ')
{
w = w + ch;
}
else
{
// Converting first character
// to lower case and subsequent
// initial letter of another
// word to lower case
z = z + char(tolower(w[0])) +
w.substr(1) + " ";
w = "";
}
}
return z;
}
// Driver code
int main()
{
string str = "I got intern at geeksforgeeks";
cout << convert(str) << endl;
return 0;
}
// This code is contributed by rutvik_56
|
linear
|
linear
|
// CPP program to convert given
// sentence to camel case.
#include <bits/stdc++.h>
using namespace std;
// Function to remove spaces and
// convert into camel case
string convert(string s)
{
int n = s.length();
s[0] = tolower(s[0]);
for (int i = 1; i < n; i++)
{
// check for spaces in the sentence
if (s[i] == ' ' && i < n)
{
// conversion into upper case
s[i + 1] = tolower(s[i + 1]);
i++;
}
// If not space, copy character
else
s[i] = toupper(s[i]);
}
// return string to main
return s;
}
// Driver Code
int main()
{
string str = "I get intern at geeksforgeeks";
cout << convert(str);
return 0;
}
|
constant
|
linear
|
// C++ program to print all words in the CamelCase
// dictionary that matches with a given pattern
#include <bits/stdc++.h>
using namespace std;
// Alphabet size (# of upper-Case characters)
#define ALPHABET_SIZE 26
// A Trie node
struct TrieNode
{
TrieNode* children[ALPHABET_SIZE];
// isLeaf is true if the node represents
// end of a word
bool isLeaf;
// vector to store list of complete words
// in leaf node
list<string> word;
};
// Returns new Trie node (initialized to NULLs)
TrieNode* getNewTrieNode(void)
{
TrieNode* pNode = new TrieNode;
if (pNode)
{
pNode->isLeaf = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}
return pNode;
}
// Function to insert word into the Trie
void insert(TrieNode* root, string word)
{
int index;
TrieNode* pCrawl = root;
for (int level = 0; level < word.length(); level++)
{
// consider only uppercase characters
if (islower(word[level]))
continue;
// get current character position
index = int(word[level]) - 'A';
if (!pCrawl->children[index])
pCrawl->children[index] = getNewTrieNode();
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->isLeaf = true;
// push word into vector associated with leaf node
(pCrawl->word).push_back(word);
}
// Function to print all children of Trie node root
void printAllWords(TrieNode* root)
{
// if current node is leaf
if (root->isLeaf)
{
for(string str : root->word)
cout << str << endl;
}
// recurse for all children of root node
for (int i = 0; i < ALPHABET_SIZE; i++)
{
TrieNode* child = root->children[i];
if (child)
printAllWords(child);
}
}
// search for pattern in Trie and print all words
// matching that pattern
bool search(TrieNode* root, string pattern)
{
int index;
TrieNode* pCrawl = root;
for (int level = 0; level < pattern.length(); level++)
{
index = int(pattern[level]) - 'A';
// Invalid pattern
if (!pCrawl->children[index])
return false;
pCrawl = pCrawl->children[index];
}
// print all words matching that pattern
printAllWords(pCrawl);
return true;
}
// Main function to print all words in the CamelCase
// dictionary that matches with a given pattern
void findAllWords(vector<string> dict, string pattern)
{
// construct Trie root node
TrieNode* root = getNewTrieNode();
// Construct Trie from given dict
for (string word : dict)
insert(root, word);
// search for pattern in Trie
if (!search(root, pattern))
cout << "No match found";
}
// Driver function
int main()
{
// dictionary of words where each word follows
// CamelCase notation
vector<string> dict = {
"Hi", "Hello", "HelloWorld", "HiTech", "HiGeek",
"HiTechWorld", "HiTechCity", "HiTechLab"
};
// pattern consisting of uppercase characters only
string pattern = "HT";
findAllWords(dict, pattern);
return 0;
}
|
linear
|
quadratic
|
// CPP program to convert given sentence
/// to camel case.
#include <bits/stdc++.h>
using namespace std;
// Function to remove spaces and convert
// into camel case
string convert(string s)
{
int n = s.length();
int res_ind = 0;
for (int i = 0; i < n; i++) {
// check for spaces in the sentence
if (s[i] == ' ') {
// conversion into upper case
s[i + 1] = toupper(s[i + 1]);
continue;
}
// If not space, copy character
else
s[res_ind++] = s[i];
}
// return string to main
return s.substr(0, res_ind);
}
// Driver program
int main()
{
string str = "I get intern at geeksforgeeks";
cout << convert(str);
return 0;
}
|
constant
|
linear
|
// CPP code to print all permutations
// with respect to cases
#include <bits/stdc++.h>
using namespace std;
// Function to generate permutations
void permute(string ip, string op)
{
// base case
if (ip.size() == 0) {
cout << op << " ";
return;
}
// pick lower and uppercase
char ch = tolower(ip[0]);
char ch2 = toupper(ip[0]);
ip = ip.substr(1);
permute(ip, op + ch);
permute(ip, op + ch2);
}
// Driver code
int main()
{
string ip = "aB";
permute(ip, "");
return 0;
}
|
linear
|
np
|
// CPP code to print all permutations
// with respect to cases
#include <bits/stdc++.h>
using namespace std;
// Function to generate permutations
void permute(string input)
{
int n = input.length();
// Number of permutations is 2^n
int max = 1 << n;
// Converting string to lower case
transform(input.begin(), input.end(), input.begin(),
::tolower);
// Using all subsequences and permuting them
for (int i = 0; i < max; i++) {
// If j-th bit is set, we convert it to upper case
string combination = input;
for (int j = 0; j < n; j++)
if (((i >> j) & 1) == 1)
combination[j] = toupper(input.at(j));
// Printing current combination
cout << combination << " ";
}
}
// Driver code
int main()
{
permute("ABC");
return 0;
}
|
linear
|
quadratic
|
// C++ program to get toggle case of a string
#include <bits/stdc++.h>
using namespace std;
// tOGGLE cASE = swaps CAPS to lower
// case and lower case to CAPS
char *toggleCase(char *a)
{
for(int i = 0; a[i] != '\0'; i++)
{
// Bitwise EXOR with 32
a[i] ^= 32;
}
return a;
}
// Driver Code
int main()
{
char str[] = "CheRrY";
cout << "Toggle case: "
<< toggleCase(str) << endl;
cout << "Original string: "
<< toggleCase(str) << endl;
return 0;
}
// This code is contributed by noob2000
|
constant
|
linear
|
// C++ program to generate short url from integer id and
// integer id back from short url.
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
// Function to generate a short url from integer ID
string idToShortURL(long int n)
{
// Map to store 62 possible characters
char map[] = "abcdefghijklmnopqrstuvwxyzABCDEF"
"GHIJKLMNOPQRSTUVWXYZ0123456789";
string shorturl;
// Convert given integer id to a base 62 number
while (n)
{
// use above map to store actual character
// in short url
shorturl.push_back(map[n%62]);
n = n/62;
}
// Reverse shortURL to complete base conversion
reverse(shorturl.begin(), shorturl.end());
return shorturl;
}
// Function to get integer ID back from a short url
long int shortURLtoID(string shortURL)
{
long int id = 0; // initialize result
// A simple base conversion logic
for (int i=0; i < shortURL.length(); i++)
{
if ('a' <= shortURL[i] && shortURL[i] <= 'z')
id = id*62 + shortURL[i] - 'a';
if ('A' <= shortURL[i] && shortURL[i] <= 'Z')
id = id*62 + shortURL[i] - 'A' + 26;
if ('0' <= shortURL[i] && shortURL[i] <= '9')
id = id*62 + shortURL[i] - '0' + 52;
}
return id;
}
// Driver program to test above function
int main()
{
int n = 12345;
string shorturl = idToShortURL(n);
cout << "Generated short url is " << shorturl << endl;
cout << "Id from url is " << shortURLtoID(shorturl);
return 0;
}
|
constant
|
linear
|
// C++ program to print all permutations
// with repetition of characters
#include <bits/stdc++.h>
#include<string.h>
using namespace std;
/* Following function is used by
the library qsort() function
to sort an array of chars */
int compare (const void * a, const void * b);
/* The main function that recursively
prints all repeated permutations of
the given string. It uses data[] to store all
permutations one by one */
void allLexicographicRecur (char *str, char* data,
int last, int index)
{
int i, len = strlen(str);
// One by one fix all characters at
// the given index and recur for
// the/ subsequent indexes
for ( i = 0; i < len; i++ )
{
// Fix the ith character at index
// and if this is not the last
// index then recursively call
// for higher indexes
data[index] = str[i] ;
// If this is the last index then
// print the string stored in
// data[]
if (index == last)
cout << data << endl;
else // Recur for higher indexes
allLexicographicRecur (str, data, last, index+1);
}
}
/* This function sorts input string,
allocate memory for data (needed
for allLexicographicRecur()) and
calls allLexicographicRecur() for
printing all permutations */
void allLexicographic(char *str)
{
int len = strlen (str) ;
// Create a temp array that will
// be used by allLexicographicRecur()
char *data = (char *) malloc (sizeof(char) * (len + 1)) ;
data[len] = '\0';
// Sort the input string so that
// we get all output strings in
// lexicographically sorted order
qsort(str, len, sizeof(char), compare);
// Now print all permutations
allLexicographicRecur (str, data, len-1, 0);
// Free data to avoid memory leak
free(data);
}
// Needed for library function qsort()
int compare (const void * a, const void * b)
{
return ( *(char *)a - *(char *)b );
}
// Driver code
int main()
{
char str[] = "ABC";
cout << "All permutations with repetition of "<<
str <<" are: "<<endl ;
allLexicographic(str);
return 0;
}
// This code is contributed by rathbhupendra
|
linear
|
np
|
// C++ program to check if a string can be converted to
// a string that has repeated substrings of length k.
#include<bits/stdc++.h>
using namespace std;
// Returns true if str can be converted to a string
// with k repeated substrings after replacing k
// characters.
bool checkString(string str, long k)
{
// Length of string must be a multiple of k
int n = str.length();
if (n%k != 0)
return false;
// Map to store strings of length k and their counts
unordered_map<string, int> mp;
for (int i=0; i<n; i+=k)
mp[str.substr(i, k)]++;
// If string is already a repetition of k substrings,
// return true.
if (mp.size() == 1)
return true;
// If number of distinct substrings is not 2, then
// not possible to replace a string.
if (mp.size() != 2)
return false;
// One of the two distinct must appear exactly once.
// Either the first entry appears once, or it appears
// n/k-1 times to make other substring appear once.
if ((mp.begin()->second == (n/k - 1)) ||
mp.begin()->second == 1)
return true;
return false;
}
// Driver code
int main()
{
checkString("abababcd", 2)? cout << "Yes" :
cout << "No";
return 0;
}
|
linear
|
linear
|
// C++ program to find smallest possible length
// of a string of only three characters
#include<bits/stdc++.h>
using namespace std;
// Program to find length of reduced string
// in a string made of three characters.
#define MAX_LEN 110
// To store results of subproblems
int DP[MAX_LEN][MAX_LEN][MAX_LEN];
// A memoized function find result recursively.
// a, b and c are counts of 'a's, 'b's and
// 'c's in str
int length(int a, int b, int c)
{
// If this subproblem is already evaluated
if(a < 0 or b < 0 or c < 0)
if (DP[a][b] != -1)
return DP[a][b];
// If there is only one type of character
if (a == 0 && b == 0)
return (DP[a][b] = c);
if (a == 0 && c == 0)
return (DP[a][b] = b);
if (b == 0 && c == 0)
return (DP[a][b] = a);
// If only two types of characters are present
if (a == 0)
return (DP[a][b] =
length(a + 1, b - 1, c - 1));
if (b == 0)
return (DP[a][b] =
length(a - 1, b + 1, c - 1));
if (c == 0)
return (DP[a][b] =
length(a - 1, b - 1, c + 1));
// If all types of characters are present.
// Try combining all pairs.
return (DP[a][b] =
min(length(a - 1, b - 1, c + 1),
min(length(a - 1, b + 1, c - 1),
length(a + 1, b - 1, c - 1))));
}
// Returns smallest possible length with given
// operation allowed.
int stringReduction(string str)
{
int n = str.length();
// Counting occurrences of three different
// characters 'a', 'b' and 'c' in str
int count[3] = {0};
for (int i=0; i<n; ++i)
count[str[i]-'a']++;
// Initialize DP[][] entries as -1
for (int i = 0; i <= count[0]; ++i)
for (int j = 0; j < count[1]; ++j)
for (int k = 0; k < count[2]; ++k)
DP[i][j][k] = -1;
return length(count[0], count[1], count[2]);
}
// Driver code
int main()
{
string str = "abcbbaacb";
cout << stringReduction(str);
return 0;
}
|
linear
|
linear
|
// C++ program to find smallest possible length
// of a string of only three characters
#include<bits/stdc++.h>
using namespace std;
// Returns smallest possible length with given
// operation allowed.
int stringReduction(string str)
{
int n = str.length();
// Counint occurrences of three different
// characters 'a', 'b' and 'c' in str
int count[3] = {0};
for (int i=0; i<n; ++i)
count[str[i]-'a']++;
// If all characters are same.
if (count[0] == n || count[1] == n ||
count[2] == n)
return n;
// If all characters are present even number
// of times or all are present odd number of
// times.
if ((count[0] % 2) == (count[1] % 2) &&
(count[1] % 2) == (count[2] % 2))
return 2;
// Answer is 1 for all other cases.
return 1;
}
// Driver code
int main()
{
string str = "abcbbaacb";
cout << stringReduction(str);
return 0;
}
|
constant
|
linear
|
// CPP program to find if its possible to
// distribute balls without repetition
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
// function to find if its possible to
// distribute balls or not
bool distributingBalls(int k, int n, string str)
{
// count array to count how many times
// each color has occurred
int a[MAX_CHAR] = {0};
for (int i = 0; i < n; i++){
// increasing count of each color
// every time it appears
a[str[i] - 'a']++;
}
for (int i = 0; i < MAX_CHAR; i++)
// to check if any color appears
// more than K times if it does
// we will print NO
if (a[i] > k)
return false;
return true;
}
// Driver code
int main()
{
long long int n = 6, k = 3;
string str = "aacaab";
if (distributingBalls(k, n, str))
cout << "YES";
else
cout << "NO";
return 0;
}
|
constant
|
linear
|
// C++ program to find the maximum consecutive
// repeating character in given string
#include<bits/stdc++.h>
using namespace std;
// function to find out the maximum repeating
// character in given string
char maxRepeating(string str)
{
int len = str.length();
int count = 0;
// Find the maximum repeating character
// starting from str[i]
char res = str[0];
for (int i=0; i<len; i++)
{
int cur_count = 1;
for (int j=i+1; j<len; j++)
{
if (str[i] != str[j])
break;
cur_count++;
}
// Update result if required
if (cur_count > count)
{
count = cur_count;
res = str[i];
}
}
return res;
}
// Driver code
int main()
{
string str = "aaaabbaaccde";
cout << maxRepeating(str);
return 0;
}
|
constant
|
quadratic
|
// C++ program to find the maximum consecutive
// repeating character in given string
#include<bits/stdc++.h>
using namespace std;
// Returns the maximum repeating character in a
// given string
char maxRepeating(string str)
{
int n = str.length();
int count = 0;
char res = str[0];
int cur_count = 1;
// Traverse string except last character
for (int i=0; i<n; i++)
{
// If current character matches with next
if (i < n-1 && str[i] == str[i+1])
cur_count++;
// If doesn't match, update result
// (if required) and reset count
else
{
if (cur_count > count)
{
count = cur_count;
res = str[i];
}
cur_count = 1;
}
}
return res;
}
// Driver code
int main()
{
string str = "aaaabbaaccde";
cout << maxRepeating(str);
return 0;
}
|
constant
|
linear
|
// C++ program for a Queue based approach
// to find first non-repeating character
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
// function to find first non repeating
// character of sa stream
void firstnonrepeating(char str[])
{
queue<char> q;
int charCount[MAX_CHAR] = { 0 };
// traverse whole stream
for (int i = 0; str[i]; i++) {
// push each character in queue
q.push(str[i]);
// increment the frequency count
charCount[str[i] - 'a']++;
// check for the non repeating character
while (!q.empty()) {
if (charCount[q.front() - 'a'] > 1)
q.pop();
else {
cout << q.front() << " ";
break;
}
}
if (q.empty())
cout << -1 << " ";
}
cout << endl;
}
// Driver function
int main()
{
char str[] = "aabc";
firstnonrepeating(str);
return 0;
}
|
linear
|
linear
|
// C++ program to find k'th non-repeating character
// in a string
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
// Returns index of k'th non-repeating character in
// given string str[]
int kthNonRepeating(string str, int k)
{
int n = str.length();
// count[x] is going to store count of
// character 'x' in str. If x is not present,
// then it is going to store 0.
int count[MAX_CHAR];
// index[x] is going to store index of character
// 'x' in str. If x is not present or x is
// repeating, then it is going to store a value
// (for example, length of string) that cannot be
// a valid index in str[]
int index[MAX_CHAR];
// Initialize counts of all characters and indexes
// of non-repeating characters.
for (int i = 0; i < MAX_CHAR; i++)
{
count[i] = 0;
index[i] = n; // A value more than any index
// in str[]
}
// Traverse the input string
for (int i = 0; i < n; i++)
{
// Find current character and increment its
// count
char x = str[i];
++count[x];
// If this is first occurrence, then set value
// in index as index of it.
if (count[x] == 1)
index[x] = i;
// If character repeats, then remove it from
// index[]
if (count[x] == 2)
index[x] = n;
}
// Sort index[] in increasing order. This step
// takes O(1) time as size of index is 256 only
sort(index, index+MAX_CHAR);
// After sorting, if index[k-1] is value, then
// return it, else return -1.
return (index[k-1] != n)? index[k-1] : -1;
}
// Driver code
int main()
{
string str = "geeksforgeeks";
int k = 3;
int res = kthNonRepeating(str, k);
(res == -1)? cout << "There are less than k non-"
"repeating characters"
: cout << "k'th non-repeating character"
" is "<< str[res];
return 0;
}
|
linear
|
nlogn
|
#include <bits/stdc++.h>
using namespace std;
#define MAX_CHAR 256
int kthNonRepeating(string input, int k)
{
int inputLength = input.length();
/*
* indexArr will store index of non-repeating
* characters, inputLength for characters not in input
* and inputLength+1 for repeated characters.
*/
int indexArr[MAX_CHAR];
// initialize all values in indexArr as inputLength.
for (int i = 0; i < MAX_CHAR; i++) {
indexArr[i] = inputLength;
}
for (int i = 0; i < inputLength; i++) {
char c = input[i];
if (indexArr == inputLength) {
indexArr = i;
}
else {
indexArr = inputLength + 2;
}
}
sort(indexArr, indexArr + MAX_CHAR);
return (indexArr[k - 1] != inputLength)
? indexArr[k - 1]
: -1;
}
int main()
{
string input = "geeksforgeeks";
int k = 3;
int res = kthNonRepeating(input, k);
if (res == -1)
cout << "There are less than k non-repeating "
"characters";
else
cout << "k'th non-repeating character is "
<< input[res];
return 0;
}
// This code is contributed by gauravrajput1
|
linear
|
nlogn
|
// CPP program to find the first
// repeated character in a string
#include <bits/stdc++.h>
using namespace std;
// Returns first repeating character in str.
char firstRepeating(string &str)
{
// Creates an empty hashset
unordered_set<char> h;
// Traverse the input array from left to right
for (int i=0; i<str.length(); i++)
{
char c = str[i];
// If element is already in hash set, update x
// and then break
if (h.find(c) != h.end())
return c;
else // Else add element to hash set
h.insert(c);
}
// If there was no repeated character
return '\0';
}
// Driver method to test above method
int main ()
{
string str = "geeksforgeeks";
cout << firstRepeating(str);
return 0;
}
|
linear
|
linear
|
// C++ program to find out the second
// most repeated word
#include <bits/stdc++.h>
using namespace std;
// Function to find the word
string secMostRepeated(vector<string> seq)
{
// Store all the words with its occurrence
unordered_map<string, int> occ;
for (int i = 0; i < seq.size(); i++)
occ[seq[i]]++;
// find the second largest occurrence
int first_max = INT_MIN, sec_max = INT_MIN;
for (auto it = occ.begin(); it != occ.end(); it++) {
if (it->second > first_max) {
sec_max = first_max;
first_max = it->second;
}
else if (it->second > sec_max &&
it->second != first_max)
sec_max = it->second;
}
// Return string with occurrence equals
// to sec_max
for (auto it = occ.begin(); it != occ.end(); it++)
if (it->second == sec_max)
return it->first;
}
// Driver program
int main()
{
vector<string> seq = { "ccc", "aaa", "ccc",
"ddd", "aaa", "aaa" };
cout << secMostRepeated(seq);
return 0;
}
|
linear
|
linear
|
// CPP code to find most frequent word in
// an array of strings
#include <bits/stdc++.h>
using namespace std;
void mostFrequentWord(string arr[], int n)
{
// freq to store the freq of the most occurring variable
int freq = 0;
// res to store the most occurring string in the array of
// strings
string res;
// running nested for loops to find the most occurring
// word in the array of strings
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = i + 1; j < n; j++) {
if (arr[j] == arr[i]) {
count++;
}
}
// updating our max freq of occured string in the
// array of strings
if (count >= freq) {
res = arr[i];
freq = count;
}
}
cout << "The word that occurs most is : " << res
<< endl;
cout << "No of times: " << freq << endl;
}
// Driver code
int main()
{
// given set of keys
string arr[]
= { "geeks", "for", "geeks", "a", "portal",
"to", "learn", "can", "be", "computer",
"science", "zoom", "yup", "fire", "in",
"be", "data", "geeks" };
int n = sizeof(arr) / sizeof(arr[0]);
mostFrequentWord(arr, n);
return 0;
}
|
constant
|
constant
|
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to find most frequent word
// in an array of strings.
string mostFrequentWord(string arr[], int n)
{
unordered_map<string, int> freq;
unordered_map<string, int> occurrence;
int max = 0;
string result;
int k = 1;
for (int i = 0; i < n; i++) {
if (occurrence.count(arr[i]) > 0) {
continue;
}
occurrence[arr[i]] = k++;
}
for (int i = 0; i < n; i++) {
freq[arr[i]]++;
if (max <= freq[arr[i]]) {
if (max < freq[arr[i]]) {
max = freq[arr[i]];
result = arr[i];
}
else {
if (occurrence[result]
< occurrence[arr[i]]) {
max = freq[arr[i]];
result = arr[i];
}
}
}
}
return result;
}
};
int main()
{
string arr[]
= { "geeks", "for", "geeks", "a", "portal",
"to", "learn", "can", "be", "computer",
"science", "zoom", "yup", "fire", "in",
"be", "data", "geeks" };
int n = sizeof(arr) / sizeof(arr[0]);
Solution obj;
cout << obj.mostFrequentWord(arr, n) << endl;
return 0;
}
|
linear
|
linear
|
// c++ implementation
// Function returns word with highest frequency
#include <bits/stdc++.h>
using namespace std;
// Function returns word with highest frequency
string findWord(vector<string> arr)
{
// Create HashMap to store word and it's frequency
unordered_map<string, int> hs;
// Iterate through array of words
for (int i = 0; i < arr.size(); i++) {
hs[arr[i]]++;
}
string key = "";
int value = 0;
for (auto me : hs) {
// Check for word having highest frequency
if (me.second > value) {
value = me.second;
key = me.first;
}
}
// Return word having highest frequency
return key;
}
int main()
{
vector<string> arr{ "geeks", "for", "geeks",
"a", "portal", "to",
"learn", "can", "be",
"computer", "science", "zoom",
"yup", "fire", "in",
"be", "data", "geeks" };
string sol = findWord(arr);
// Print word having highest frequency
cout << sol << endl;
}
// This code is contributed by Aarti_Rathi
|
linear
|
linear
|
// CPP code to find most frequent word in
// an array of strings
#include <bits/stdc++.h>
using namespace std;
/*structing the trie*/
struct Trie {
string key;
int cnt;
unordered_map<char, Trie*> map;
};
/* Function to return a new Trie node */
Trie* getNewTrieNode()
{
Trie* node = new Trie;
node->cnt = 0;
return node;
}
/* function to insert a string */
void insert(Trie*& root, string& str, int& maxCount,
string& mostFrequentString)
{
// start from root node
Trie* temp = root;
for (int i = 0; i < str.length(); i++) {
char x = str[i];
/*a new node if path doesn't exists*/
if (temp->map.find(x) == temp->map.end())
temp->map[x] = getNewTrieNode();
// go to next node
temp = temp->map[x];
}
// store key and its count in leaf nodes
temp->key = str;
temp->cnt += 1;
if (maxCount < temp->cnt) {
maxCount = temp->cnt;
mostFrequentString = str;
}
}
void mostFrequentWord(string arr[], int n)
{
// Insert all words in a Trie
Trie* root = getNewTrieNode();
int cnt = 0;
string key = "";
for (int i = 0; i < n; i++)
insert(root, arr[i], cnt, key);
cout << "The word that occurs most is : " << key
<< endl;
cout << "No of times: " << cnt << endl;
}
// Driver code
int main()
{
// given set of keys
string arr[]
= { "geeks", "for", "geeks", "a", "portal",
"to", "learn", "can", "be", "computer",
"science", "zoom", "yup", "fire", "in",
"be", "data", "geeks" };
int n = sizeof(arr) / sizeof(arr[0]);
mostFrequentWord(arr, n);
return 0;
}
|
linear
|
linear
|
// Efficiently check First repeated character
// in C++ program
#include<bits/stdc++.h>
using namespace std;
// Returns -1 if all characters of str are
// unique.
// Assumptions : (1) str contains only characters
// from 'a' to 'z'
// (2) integers are stored using 32
// bits
int FirstRepeated(string str)
{
// An integer to store presence/absence
// of 26 characters using its 32 bits.
int checker = 0;
for (int i = 0; i < str.length(); ++i)
{
int val = (str[i]-'a');
// If bit corresponding to current
// character is already set
if ((checker & (1 << val)) > 0)
return i;
// set bit in checker
checker |= (1 << val);
}
return -1;
}
// Driver code
int main()
{
string s = "abcfdeacf";
int i=FirstRepeated(s);
if (i!=-1)
cout <<"Char = "<< s[i] << " and Index = "<<i;
else
cout << "No repeated Char";
return 0;
}
|
constant
|
linear
|
// Queries for same characters in a repeated
// string
#include <bits/stdc++.h>
using namespace std;
// Print whether index i and j have same
// element or not.
void query(char s[], int i, int j)
{
int n = strlen(s);
// Finding relative position of index i,j.
i %= n;
j %= n;
// Checking is element are same at index i, j.
(s[i] == s[j]) ? (cout << "Yes" << endl)
: (cout << "No" << endl);
}
// Driven Program
int main()
{
char X[] = "geeksforgeeks";
query(X, 0, 8);
query(X, 8, 13);
query(X, 6, 15);
return 0;
}
|
constant
|
constant
|
// C++ program to output the maximum occurring character
// in a string
#include <bits/stdc++.h>
#define ASCII_SIZE 256
using namespace std;
char getMaxOccurringChar(char* str)
{
// Create array to keep the count of individual
// characters and initialize the array as 0
int count[ASCII_SIZE] = { 0 };
// Construct character count array from the input
// string.
int len = strlen(str);
int max = 0; // Initialize max count
char result; // Initialize result
// Traversing through the string and maintaining
// the count of each character
for (int i = 0; i < len; i++) {
count[str[i]]++;
if (max < count[str[i]]) {
max = count[str[i]];
result = str[i];
}
}
return result;
}
// Driver program to test the above function
int main()
{
char str[] = "sample string";
cout << "Max occurring character is "
<< getMaxOccurringChar(str);
}
|
constant
|
linear
|
// C++ program to count occurrences of a given
// character
#include <iostream>
#include <string>
using namespace std;
// Function that return count of the given
// character in the string
int count(string s, char c)
{
// Count variable
int res = 0;
for (int i=0;i<s.length();i++)
// checking character in string
if (s[i] == c)
res++;
return res;
}
// Driver code
int main()
{
string str= "geeksforgeeks";
char c = 'e';
cout << count(str, c) << endl;
return 0;
}
|
constant
|
linear
|
// CPP program to count occurrences of
// a character using library
#include<bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
string str = "geeksforgeeks";
char c = 'e';
// Count returns number of occurrences of
// c between two given positions provided
// as two iterators.
cout << count(str.begin(), str.end(), c);
return 0;
}
|
constant
|
linear
|
// C++ program to print the string in given pattern
#include <bits/stdc++.h>
using namespace std;
// Function to print the string
void printStringAlternate(string str)
{
unordered_map<char, int> occ;
// Start traversing the string
for (int i = 0; i < str.length(); i++) {
// Convert uppercase to lowercase
char temp = tolower(str[i]);
// Increment occurrence count
occ[temp]++;
// If count is odd then print the character
if (occ[temp] & 1)
cout << str[i];
}
cout << endl;
}
// Drivers code
int main()
{
string str = "Geeks for geeks";
string str2 = "It is a long day Dear";
printStringAlternate(str);
printStringAlternate(str2);
return 0;
}
|
linear
|
linear
|
// Program to find all occurrences of the word in
// a matrix
#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 5
// check whether given cell (row, col) is a valid
// cell or not.
bool isvalid(int row, int col, int prevRow, int prevCol)
{
// return true if row number and column number
// is in range
return (row >= 0) && (row < ROW) &&
(col >= 0) && (col < COL) &&
!(row== prevRow && col == prevCol);
}
// These arrays are used to get row and column
// numbers of 8 neighboursof a given cell
int rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1};
// A utility function to do DFS for a 2D boolean
// matrix. It only considers the 8 neighbours as
// adjacent vertices
void DFS(char mat[][COL], int row, int col,
int prevRow, int prevCol, char* word,
string path, int index, int n)
{
// return if current character doesn't match with
// the next character in the word
if (index > n || mat[row][col] != word[index])
return;
//append current character position to path
path += string(1, word[index]) + "(" + to_string(row)
+ ", " + to_string(col) + ") ";
// current character matches with the last character
// in the word
if (index == n)
{
cout << path << endl;
return;
}
// Recur for all connected neighbours
for (int k = 0; k < 8; ++k)
if (isvalid(row + rowNum[k], col + colNum[k],
prevRow, prevCol))
DFS(mat, row + rowNum[k], col + colNum[k],
row, col, word, path, index+1, n);
}
// The main function to find all occurrences of the
// word in a matrix
void findWords(char mat[][COL], char* word, int n)
{
// traverse through the all cells of given matrix
for (int i = 0; i < ROW; ++i)
for (int j = 0; j < COL; ++j)
// occurrence of first character in matrix
if (mat[i][j] == word[0])
// check and print if path exists
DFS(mat, i, j, -1, -1, word, "", 0, n);
}
// Driver program to test above function
int main()
{
char mat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'},
{'H', 'E', 'D', 'E', 'S'},
{'S', 'G', 'N', 'D', 'E'}
};
char word[] ="DES";
findWords(mat, word, strlen(word) - 1);
return 0;
}
|
quadratic
|
quadratic
|
// C++ program to arrange given string
#include <bits/stdc++.h>
using namespace std;
// Function which arrange the given string
void arrangeString(string str, int x, int y)
{
int count_0 = 0;
int count_1 = 0;
int len = str.length();
// Counting number of 0's and 1's in the
// given string.
for (int i = 0; i < len; i++) {
if (str[i] == '0')
count_0++;
else
count_1++;
}
// Printing first all 0's x-times
// and decrement count of 0's x-times
// and do the similar task with '1'
while (count_0 > 0 || count_1 > 0) {
for (int j = 0; j < x && count_0 > 0; j++) {
if (count_0 > 0) {
cout << "0";
count_0--;
}
}
for (int j = 0; j < y && count_1 > 0; j++) {
if (count_1 > 0) {
cout << "1";
count_1--;
}
}
}
}
// Driver Code
int main()
{
string str = "01101101101101101000000";
int x = 1;
int y = 2;
arrangeString(str, x, y);
return 0;
}
|
constant
|
quadratic
|
// Finds maximum occurring digit without using any array/string
#include <bits/stdc++.h>
using namespace std;
// Simple function to count occurrences of digit d in x
int countOccurrences(long int x, int d)
{
int count = 0; // Initialize count of digit d
while (x)
{
// Increment count if current digit is same as d
if (x%10 == d)
count++;
x = x/10;
}
return count;
}
// Returns the max occurring digit in x
int maxOccurring(long int x)
{
// Handle negative number
if (x < 0)
x = -x;
int result = 0; // Initialize result which is a digit
int max_count = 1; // Initialize count of result
// Traverse through all digits
for (int d=0; d<=9; d++)
{
// Count occurrences of current digit
int count = countOccurrences(x, d);
// Update max_count and result if needed
if (count >= max_count)
{
max_count = count;
result = d;
}
}
return result;
}
// Driver program
int main()
{
long int x = 1223355;
cout << "Max occurring digit is " << maxOccurring(x);
return 0;
}
|
constant
|
constant
|
// C++ program to bring all spaces in front of
// string using swapping technique
#include<bits/stdc++.h>
using namespace std;
// Function to find spaces and move to beginning
void moveSpaceInFront(char str[])
{
// Traverse from end and swap spaces
int i = strlen(str)-1;
for (int j = i; j >= 0; j--)
if (str[j] != ' ')
swap(str[i--], str[j]);
}
// Driver code
int main()
{
char str[] = "Hey there, it's GeeksforGeeks";
moveSpaceInFront(str);
cout << str;
return 0;
}
|
constant
|
linear
|
// CPP program to bring all spaces in front of
// string using swapping technique
#include<bits/stdc++.h>
using namespace std;
// Function to find spaces and move to beginning
void moveSpaceInFront(char str[])
{
// Keep copying non-space characters
int i = strlen(str);
for (int j=i; j >= 0; j--)
if (str[j] != ' ')
str[i--] = str[j];
// Move spaces to be beginning
while (i >= 0)
str[i--] = ' ';
}
// Driver code
int main()
{
char str[] = "Hey there, it's GeeksforGeeks";
moveSpaceInFront(str);
cout << str;
return 0;
}
|
constant
|
linear
|
// C++ program to put spaces between words starting
// with capital letters.
#include <iostream>
using namespace std;
// Function to amend the sentence
void amendSentence(string str)
{
// Traverse the string
for(int i=0; i < str.length(); i++)
{
// Convert to lowercase if its
// an uppercase character
if (str[i]>='A' && str[i]<='Z')
{
str[i]=str[i]+32;
// Print space before it
// if its an uppercase character
if (i != 0)
cout << " ";
// Print the character
cout << str[i];
}
// if lowercase character
// then just print
else
cout << str[i];
}
}
// Driver code
int main()
{
string str ="BruceWayneIsBatman";
amendSentence(str);
return 0;
}
|
constant
|
linear
|
// C++ program to remove spaces using stringstream
#include <bits/stdc++.h>
using namespace std;
// Function to remove spaces
string removeSpaces(string str)
{
stringstream ss;
string temp;
// Storing the whole string
// into string stream
ss << str;
// Making the string empty
str = "";
// Running loop till end of stream
while (!ss.eof()) {
// Extracting word by word from stream
ss >> temp;
// Concatenating in the string to be
// returned
str = str + temp;
}
return str;
}
// Driver function
int main()
{
// Sample Inputs
string s = "This is a test";
cout << removeSpaces(s) << endl;
s = "geeks for geeks";
cout << removeSpaces(s) << endl;
s = "geeks quiz is awesome!";
cout << removeSpaces(s) << endl;
s = "I love to code";
cout << removeSpaces(s) << endl;
return 0;
}
|
linear
|
linear
|
// C++ program to remove spaces using stringstream
// and getline()
#include <bits/stdc++.h>
using namespace std;
// Function to remove spaces
string removeSpaces(string str)
{
// Storing the whole string
// into string stream
stringstream ss(str);
string temp;
// Making the string empty
str = "";
// Running loop till end of stream
// and getting every word
while (getline(ss, temp, ' ')) {
// Concatenating in the string
// to be returned
str = str + temp;
}
return str;
}
// Driver function
int main()
{
// Sample Inputs
string s = "This is a test";
cout << removeSpaces(s) << endl;
s = "geeks for geeks";
cout << removeSpaces(s) << endl;
s = "geeks quiz is awesome!";
cout << removeSpaces(s) << endl;
s = "I love to code";
cout << removeSpaces(s) << endl;
return 0;
}
// Code contributed by saychakr13
|
linear
|
linear
|
// C++ program to implement custom trim() function
#include <iostream>
using namespace std;
// Function to in-place trim all spaces in the
// string such that all words should contain only
// a single space between them.
void removeSpaces(string &str)
{
// n is length of the original string
int n = str.length();
// i points to next position to be filled in
// output string/ j points to next character
// in the original string
int i = 0, j = -1;
// flag that sets to true is space is found
bool spaceFound = false;
// Handles leading spaces
while (++j < n && str[j] == ' ');
// read all characters of original string
while (j < n)
{
// if current characters is non-space
if (str[j] != ' ')
{
// remove preceding spaces before dot,
// comma & question mark
if ((str[j] == '.' || str[j] == ',' ||
str[j] == '?') && i - 1 >= 0 &&
str[i - 1] == ' ')
str[i - 1] = str[j++];
else
// copy current character at index i
// and increment both i and j
str[i++] = str[j++];
// set space flag to false when any
// non-space character is found
spaceFound = false;
}
// if current character is a space
else if (str[j++] == ' ')
{
// If space is encountered for the first
// time after a word, put one space in the
// output and set space flag to true
if (!spaceFound)
{
str[i++] = ' ';
spaceFound = true;
}
}
}
// Remove trailing spaces
if (i <= 1)
str.erase(str.begin() + i, str.end());
else
str.erase(str.begin() + i - 1, str.end());
}
// Driver Code
int main()
{
string str = " Hello Geeks . Welcome to"
" GeeksforGeeks . ";
removeSpaces(str);
cout << str;
return 0;
}
|
constant
|
linear
|
#include <bits/stdc++.h>
using namespace std;
void replaceSpaces(string input)
{
string rep = "%20";
for(int i=0 ; i<input.length() ; i++)
{
if(input[i] == ' ')
input.replace(i,1,rep);
}
cout<<input;
}
int main()
{
string input = "Mr John Smith";
replaceSpaces(input);
return 0;
}
|
constant
|
quadratic
|
// C++ program to replace spaces with %20
#include<stdio.h>
// Maximum length of string after modifications.
const int MAX = 1000;
// Replaces spaces with %20 in-place and returns
// new length of modified string. It returns -1
// if modified string cannot be stored in str[]
int replaceSpaces(char str[])
{
// count spaces and find current length
int space_count = 0, i;
for (i = 0; str[i]; i++)
if (str[i] == ' ')
space_count++;
// Remove trailing spaces
while (str[i-1] == ' ')
{
space_count--;
i--;
}
// Find new length.
int new_length = i + space_count * 2 + 1;
// New length must be smaller than length
// of string provided.
if (new_length > MAX)
return -1;
// Start filling character from end
int index = new_length - 1;
// Fill string termination.
str[index--] = '\0';
// Fill rest of the string from end
for (int j=i-1; j>=0; j--)
{
// inserts %20 in place of space
if (str[j] == ' ')
{
str[index] = '0';
str[index - 1] = '2';
str[index - 2] = '%';
index = index - 3;
}
else
{
str[index] = str[j];
index--;
}
}
return new_length;
}
// Driver code
int main()
{
char str[MAX] = "Mr John Smith ";
// Prints the replaced string
int new_length = replaceSpaces(str);
for (int i=0; i<new_length; i++)
printf("%c", str[i]);
return 0;
}
|
constant
|
linear
|
// C++ program to find the string which contain
// the first character of each word of another
// string.
#include<bits/stdc++.h>
using namespace std;
// Function to find string which has first
// character of each word.
string firstLetterWord(string str)
{
string result = "";
// Traverse the string.
bool v = true;
for (int i=0; i<str.length(); i++)
{
// If it is space, set v as true.
if (str[i] == ' ')
v = true;
// Else check if v is true or not.
// If true, copy character in output
// string and set v as false.
else if (str[i] != ' ' && v == true)
{
result.push_back(str[i]);
v = false;
}
}
return result;
}
// Driver code
int main()
{
string str = "geeks for geeks";
cout << firstLetterWord(str);
return 0;
}
|
linear
|
linear
|
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
string processWords(char *input)
{
/* we are splitting the input based on
spaces (s)+ : this regular expression
will handle scenarios where we have words
separated by multiple spaces */
char *p;
vector<string> s;
p = strtok(input, " ");
while (p != NULL)
{
s.push_back(p);
p = strtok(NULL, " ");
}
string charBuffer;
for (string values : s)
/* charAt(0) will pick only the first character
from the string and append to buffer */
charBuffer += values[0];
return charBuffer;
}
// Driver code
int main()
{
char input[] = "geeks for geeks";
cout << processWords(input);
return 0;
}
// This code is contributed by
// sanjeev2552
|
linear
|
quadratic
|
// C++ program to print all strings that can be
// made by placing spaces
#include <bits/stdc++.h>
using namespace std;
void printSubsequences(string str)
{
int n = str.length();
unsigned int opsize = pow(2, n - 1);
for (int counter = 0; counter < opsize; counter++) {
for (int j = 0; j < n; j++) {
cout << str[j];
if (counter & (1 << j))
cout << " ";
}
cout << endl;
}
}
// Driver code
int main()
{
string str = "ABC";
printSubsequences(str);
return 0;
}
|
constant
|
quadratic
|
// C++ program to check whether two strings are anagrams
// of each other
#include <bits/stdc++.h>
using namespace std;
/* function to check whether two strings are anagram of
each other */
bool areAnagram(string str1, string str2)
{
// Get lengths of both strings
int n1 = str1.length();
int n2 = str2.length();
// If length of both strings is not same, then they
// cannot be anagram
if (n1 != n2)
return false;
// Sort both the strings
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
// Compare sorted strings
for (int i = 0; i < n1; i++)
if (str1[i] != str2[i])
return false;
return true;
}
// Driver code
int main()
{
string str1 = "gram";
string str2 = "arm";
// Function Call
if (areAnagram(str1, str2))
cout << "The two strings are anagram of each other";
else
cout << "The two strings are not anagram of each "
"other";
return 0;
}
|
constant
|
nlogn
|
// C++ program to check if two strings
// are anagrams of each other
#include <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
/* function to check whether two strings are anagram of
each other */
bool areAnagram(char* str1, char* str2)
{
// Create 2 count arrays and initialize all values as 0
int count1[NO_OF_CHARS] = { 0 };
int count2[NO_OF_CHARS] = { 0 };
int i;
// For each character in input strings, increment count
// in the corresponding count array
for (i = 0; str1[i] && str2[i]; i++) {
count1[str1[i]]++;
count2[str2[i]]++;
}
// If both strings are of different length. Removing
// this condition will make the program fail for strings
// like "aaca" and "aca"
if (str1[i] || str2[i])
return false;
// Compare count arrays
for (i = 0; i < NO_OF_CHARS; i++)
if (count1[i] != count2[i])
return false;
return true;
}
/* Driver code*/
int main()
{
char str1[] = "gram";
char str2[] = "arm";
// Function Call
if (areAnagram(str1, str2))
cout << "The two strings are anagram of each other";
else
cout << "The two strings are not anagram of each "
"other";
return 0;
}
// This is code is contributed by rathbhupendra
|
constant
|
linear
|
// C++ program to check if two strings
// are anagrams of each other
#include <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
bool areAnagram(char* str1, char* str2)
{
// Create a count array and initialize all values as 0
int count[NO_OF_CHARS] = { 0 };
int i;
// For each character in input strings, increment count
// in the corresponding count array
for (i = 0; str1[i] && str2[i]; i++) {
count[str1[i]]++;
count[str2[i]]--;
}
// If both strings are of different length. Removing
// this condition will make the program fail for strings
// like "aaca" and "aca"
if (str1[i] || str2[i])
return false;
// See if there is any non-zero value in count array
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i])
return false;
return true;
}
// Driver code
int main()
{
char str1[] = "gram";
char str2[] = "arm";
// Function call
if (areAnagram(str1, str2))
cout << "The two strings are anagram of each other";
else
cout << "The two strings are not anagram of each "
"other";
return 0;
}
|
constant
|
linear
|
// C++ implementation of the approach
// Function that returns true if a and b
// are anagarams of each other
#include <bits/stdc++.h>
using namespace std;
bool isAnagram(string a, string b)
{
// Check if length of both strings is same or not
if (a.length() != b.length()) {
return false;
}
// Create a HashMap containing Character as Key and
// Integer as Value. We will be storing character as
// Key and count of character as Value.
unordered_map<char, int> Map;
// Loop over all character of String a and put in
// HashMap.
for (int i = 0; i < a.length(); i++) {
Map[a[i]]++;
}
// Now loop over String b
for (int i = 0; i < b.length(); i++) {
// Check if current character already exists in
// HashMap/map
if (Map.find(b[i]) != Map.end()) {
// If contains reduce count of that
// character by 1 to indicate that current
// character has been already counted as
// idea here is to check if in last count of
// all characters in last is zero which
// means all characters in String a are
// present in String b.
Map[b[i]] -= 1;
}
else {
return false;
}
}
// Loop over all keys and check if all keys are 0.
// If so it means it is anagram.
for (auto items : Map) {
if (items.second != 0) {
return false;
}
}
// Returning True as all keys are zero
return true;
}
// Driver code
int main()
{
string str1 = "gram";
string str2 = "arm";
// Function call
if (isAnagram(str1, str2))
cout << "The two strings are anagram of each other"
<< endl;
else
cout << "The two strings are not anagram of each "
"other"
<< endl;
}
// This code is contributed by shinjanpatra
|
constant
|
linear
|
// C++ program to search all anagrams of a pattern in a text
#include <bits/stdc++.h>
#define MAX 256
using namespace std;
// This function returns true if contents of arr1[] and
// arr2[] are same, otherwise false.
bool compare(char arr1[], char arr2[])
{
for (int i = 0; i < MAX; i++)
if (arr1[i] != arr2[i])
return false;
return true;
}
// This function search for all permutations of pat[] in
// txt[]
void search(char* pat, char* txt)
{
int M = strlen(pat), N = strlen(txt);
// countP[]: Store count of all characters of pattern
// countTW[]: Store count of current window of text
char countP[MAX] = { 0 }, countTW[MAX] = { 0 };
for (int i = 0; i < M; i++) {
(countP[pat[i]])++;
(countTW[txt[i]])++;
}
// Traverse through remaining characters of pattern
for (int i = M; i < N; i++) {
// Compare counts of current window of text with
// counts of pattern[]
if (compare(countP, countTW))
cout << "Found at Index " << (i - M) << endl;
// Add current character to current window
(countTW[txt[i]])++;
// Remove the first character of previous window
countTW[txt[i - M]]--;
}
// Check for the last window in text
if (compare(countP, countTW))
cout << "Found at Index " << (N - M) << endl;
}
/* Driver program to test above function */
int main()
{
char txt[] = "BACDGABCDA";
char pat[] = "ABCD";
search(pat, txt);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
linear
|
linear
|
// C++ program to find minimum number of characters
// to be removed to make two strings anagram.
#include<bits/stdc++.h>
using namespace std;
const int CHARS = 26;
// function to calculate minimum numbers of characters
// to be removed to make two strings anagram
int remAnagram(string str1, string str2)
{
// make hash array for both string and calculate
// frequency of each character
int count1[CHARS] = {0}, count2[CHARS] = {0};
// count frequency of each character in first string
for (int i=0; str1[i]!='\0'; i++)
count1[str1[i]-'a']++;
// count frequency of each character in second string
for (int i=0; str2[i]!='\0'; i++)
count2[str2[i]-'a']++;
// traverse count arrays to find number of characters
// to be removed
int result = 0;
for (int i=0; i<26; i++)
result += abs(count1[i] - count2[i]);
return result;
}
// Driver program to run the case
int main()
{
string str1 = "bcadeh", str2 = "hea";
cout << remAnagram(str1, str2);
return 0;
}
|
constant
|
linear
|
// C++ implementation to count number of deletions
// required from two strings to create an anagram
#include <bits/stdc++.h>
using namespace std;
const int CHARS = 26;
int countDeletions(string str1, string str2)
{
int arr[CHARS] = {0};
for (int i = 0; i < str1.length(); i++)
arr[str1[i] - 'a']++;
for (int i = 0; i < str2.length(); i++)
arr[str2[i] - 'a']--;
long long int ans = 0;
for(int i = 0; i < CHARS; i++)
ans +=abs(arr[i]);
return ans;
}
int main() {
string str1 = "bcadeh", str2 = "hea";
cout << countDeletions(str1, str2);
return 0;
}
|
constant
|
linear
|
// C++ program to check if two strings are k anagram
// or not.
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
// Function to check that string is k-anagram or not
bool arekAnagrams(string str1, string str2, int k)
{
// If both strings are not of equal
// length then return false
int n = str1.length();
if (str2.length() != n)
return false;
int count1[MAX_CHAR] = {0};
int count2[MAX_CHAR] = {0};
// Store the occurrence of all characters
// in a hash_array
for (int i = 0; i < n; i++)
count1[str1[i]-'a']++;
for (int i = 0; i < n; i++)
count2[str2[i]-'a']++;
int count = 0;
// Count number of characters that are
// different in both strings
for (int i = 0; i < MAX_CHAR; i++)
if (count1[i] > count2[i])
count = count + abs(count1[i]-count2[i]);
// Return true if count is less than or
// equal to k
return (count <= k);
}
// Driver code
int main()
{
string str1 = "anagram";
string str2 = "grammar";
int k = 2;
if (arekAnagrams(str1, str2, k))
cout << "Yes";
else
cout<< "No";
return 0;
}
|
constant
|
linear
|
// Optimized C++ program to check if two strings
// are k anagram or not.
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
// Function to check if str1 and str2 are k-anagram
// or not
bool areKAnagrams(string str1, string str2, int k)
{
// If both strings are not of equal
// length then return false
int n = str1.length();
if (str2.length() != n)
return false;
int hash_str1[MAX_CHAR] = {0};
// Store the occurrence of all characters
// in a hash_array
for (int i = 0; i < n ; i++)
hash_str1[str1[i]-'a']++;
// Store the occurrence of all characters
// in a hash_array
int count = 0;
for (int i = 0; i < n ; i++)
{
if (hash_str1[str2[i]-'a'] > 0)
hash_str1[str2[i]-'a']--;
else
count++;
if (count > k)
return false;
}
// Return true if count is less than or
// equal to k
return true;
}
// Driver code
int main()
{
string str1 = "fodr";
string str2 = "gork";
int k = 2;
if (areKAnagrams(str1, str2, k) == true)
cout << "Yes";
else
cout << "No";
return 0;
}
|
constant
|
linear
|
// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check k
// anagram of two strings
bool kAnagrams(string str1, string str2, int k)
{
int flag = 0;
// First Condition: If both the
// strings have different length ,
// then they cannot form anagram
if (str1.length() != str2.length())
return false;
int n = str1.length();
// Converting str1 to Character Array arr1
char arr1[n];
// Converting str2 to Character Array arr2
char arr2[n];
strcpy(arr1, str1.c_str());
strcpy(arr2, str2.c_str());
// Sort arr1 in increasing order
sort(arr1, arr1 + n);
// Sort arr2 in increasing order
sort(arr2, arr2 + n);
vector<char> list;
// Iterate till str1.length()
for (int i = 0; i < str1.length(); i++) {
// Condition if arr1[i] is
// not equal to arr2[i]
// then add it to list
if (arr1[i] != arr2[i]) {
list.push_back(arr2[i]);
}
}
// Condition to check if
// strings for K-anagram or not
if (list.size() <= k)
flag = 1;
if (flag == 1)
return true;
else
return false;
}
// Driver Code
int main()
{
string str1 = "anagram", str2 = "grammar";
int k = 3;
// Function Call
kAnagrams(str1, str2, k);
if (kAnagrams(str1, str2, k) == true)
cout << "Yes";
else
cout << "No";
// This code is contributed by bolliranadheer
}
|
constant
|
linear
|
// C++ program to check if binary
// representations of two numbers are anagrams.
#include <bits/stdc++.h>
using namespace std;
// Check each bit in a number is set or not
// and return the total count of the set bits.
int countSetBits(int n)
{
int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
bool areAnagrams(int A, int B)
{
return countSetBits(A) == countSetBits(B);
}
// Driver code
int main()
{
int a = 8, b = 4;
cout << areAnagrams(a, b) << endl;
return 0;
}
// This code is contributed by phasing17
|
constant
|
constant
|
// C++ program for finding all anagram
// pairs in the given array
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// Utility function for
// printing anagram list
void printAnagram(unordered_map<string,vector<string> >& store)
{
for (auto it:store)
{
vector<string> temp_vec(it.second);
int size = temp_vec.size();
for (int i = 0; i < size; i++)
cout << temp_vec[i] << " ";
cout << "\n";
}
}
// Utility function for storing
// the vector of strings into HashMap
void storeInMap(vector<string>& vec)
{
unordered_map<string,vector<string> > store;
for (int i = 0; i < vec.size(); i++)
{
string tempString(vec[i]);
// sort the string
sort(tempString.begin(),tempString.end());
// make hash of a sorted string
store[tempString].push_back(vec[i]);
}
// print utility function for printing
// all the anagrams
printAnagram(store);
}
// Driver code
int main()
{
// initialize vector of strings
vector<string> arr;
arr.push_back("geeksquiz");
arr.push_back("geeksforgeeks");
arr.push_back("abcd");
arr.push_back("forgeeksgeeks");
arr.push_back("zuiqkeegs");
arr.push_back("cat");
arr.push_back("act");
arr.push_back("tca");
// utility function for storing
// strings into hashmap
storeInMap(arr);
return 0;
}
|
linear
|
quadratic
|
// C++ program to count total anagram
// substring of a string
#include <bits/stdc++.h>
using namespace std;
// Total number of lowercase characters
#define MAX_CHAR 26
// Utility method to return integer index
// of character 'c'
int toNum(char c)
{
return (c - 'a');
}
// Returns count of total number of anagram
// substrings of string str
int countOfAnagramSubstring(string str)
{
int N = str.length();
// To store counts of substrings with given
// set of frequencies.
map<vector<int>, int> mp;
// loop for starting index of substring
for (int i=0; i<N; i++)
{
vector<int> freq(MAX_CHAR, 0);
// loop for length of substring
for (int j=i; j<N; j++)
{
// update freq array of current
// substring
freq[toNum(str[j])]++;
// increase count corresponding
// to this freq array
mp[freq]++;
}
}
// loop over all different freq array and
// aggregate substring count
int result = 0;
for (auto it=mp.begin(); it!=mp.end(); it++)
{
int freq = it->second;
result += ((freq) * (freq-1))/2;
}
return result;
}
// Driver code to test above methods
int main()
{
string str = "xyyx";
cout << countOfAnagramSubstring(str) << endl;
return 0;
}
|
linear
|
quadratic
|
// C++ Program to find minimum number
// of manipulations required to make
// two strings identical
#include <bits/stdc++.h>
using namespace std;
// Counts the no of manipulations
// required
int countManipulations(string s1, string s2)
{
int count = 0;
// store the count of character
int char_count[26];
for (int i = 0; i < 26; i++)
{
char_count[i] = 0;
}
// iterate though the first String
// and update count
for (int i = 0; i < s1.length(); i++)
char_count[s1[i] - 'a']++;
// iterate through the second string
// update char_count.
// if character is not found in
// char_count then increase count
for (int i = 0; i < s2.length(); i++)
{
char_count[s2[i] - 'a']--;
}
for(int i = 0; i < 26; ++i)
{
if(char_count[i] != 0)
{
count+=abs(char_count[i]);
}
}
return count / 2;
}
// Driver code
int main()
{
string s1 = "ddcf";
string s2 = "cedk";
cout<<countManipulations(s1, s2);
}
// This code is contributed by vt_m.
|
constant
|
linear
|
#include <iostream>
#include <string>
using namespace std;
// A utility function to check if a string str is palindrome
bool isPalindrome(string str)
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = str.length() - 1;
// Keep comparing characters while they are same
while (h > l)
if (str[l++] != str[h--])
return false;
// If we reach here, then all characters were matching
return true;
}
// Function to check if a given string is a rotation of a
// palindrome.
bool isRotationOfPalindrome(string str)
{
// If string itself is palindrome
if (isPalindrome(str))
return true;
// Now try all rotations one by one
int n = str.length();
for (int i = 0; i < n - 1; i++) {
string str1 = str.substr(i + 1, n - i - 1);
string str2 = str.substr(0, i + 1);
// Check if this rotation is palindrome
if (isPalindrome(str1.append(str2)))
return true;
}
return false;
}
// Driver program to test above function
int main()
{
cout << isRotationOfPalindrome("aab") << endl;
cout << isRotationOfPalindrome("abcde") << endl;
cout << isRotationOfPalindrome("aaaad") << endl;
return 0;
}
|
linear
|
quadratic
|
#include<iostream>
using namespace std;
// A function to check if n is palindrome
int isPalindrome(int n)
{
// Find reverse of n
int rev = 0;
for (int i = n; i > 0; i /= 10)
rev = rev*10 + i%10;
// If n and rev are same, then n is palindrome
return (n==rev);
}
// prints palindrome between min and max
void countPal(int min, int max)
{
for (int i = min; i <= max; i++)
if (isPalindrome(i))
cout << i << " ";
}
// Driver program to test above function
int main()
{
countPal(100, 2000);
return 0;
}
|
constant
|
logn
|
// A Dynamic Programming based program to find
// minimum number insertions needed to make a
// string palindrome
#include <bits/stdc++.h>
using namespace std;
// A DP function to find minimum
// number of insertions
int findMinInsertionsDP(char str[], int n)
{
// Create a table of size n*n. table[i][j]
// will store minimum number of insertions
// needed to convert str[i..j] to a palindrome.
int table[n][n], l, h, gap;
// Initialize all table entries as 0
memset(table, 0, sizeof(table));
// Fill the table
for (gap = 1; gap < n; ++gap)
for (l = 0, h = gap; h < n; ++l, ++h)
table[l][h] = (str[l] == str[h])?
table[l + 1][h - 1] :
(min(table[l][h - 1],
table[l + 1][h]) + 1);
// Return minimum number of insertions
// for str[0..n-1]
return table[0][n - 1];
}
// Driver Code
int main()
{
char str[] = "geeks";
cout << findMinInsertionsDP(str, strlen(str));
return 0;
}
// This is code is contributed by rathbhupendra
|
quadratic
|
quadratic
|
// An LCS based program to find minimum number
// insertions needed to make a string palindrome
#include <bits/stdc++.h>
using namespace std;
// Returns length of LCS for X[0..m-1], Y[0..n-1].
int lcs( string X, string Y, int m, int n )
{
int L[m+1][n+1];
int i, j;
/* Following steps build L[m+1][n+1] in bottom
up fashion. Note that L[i][j] contains length
of LCS of X[0..i-1] and Y[0..j-1] */
for (i = 0; i <= m; i++)
{
for (j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
}
}
/* L[m][n] contains length of LCS for X[0..n-1]
and Y[0..m-1] */
return L[m][n];
}
void reverseStr(string& str)
{
int n = str.length();
// Swap character starting from two
// corners
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
// LCS based function to find minimum number of
// insertions
int findMinInsertionsLCS(string str, int n)
{
// Creata another string to store reverse of 'str'
string rev = "";
rev = str;
reverseStr(rev);
// The output is length of string minus length of lcs of
// str and it reverse
return (n - lcs(str, rev, n, n));
}
// Driver code
int main()
{
string str = "geeks";
cout << findMinInsertionsLCS(str, str.length());
return 0;
}
// This code is contributed by rathbhupendra
|
quadratic
|
quadratic
|
// An LCS based program to find minimum number
// insertions needed to make a string palindrome
#include <bits/stdc++.h>
using namespace std;
// Returns length of LCS for X[0..m-1], Y[0..n-1].
int lcs(string X, string Y, int m, int n)
{
vector<int> prev(n + 1, 0), curr(n + 1, 0);
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
prev[j] = 0;
else if (X[i - 1] == Y[j - 1])
curr[j] = prev[j - 1] + 1;
else
curr[j] = max(prev[j], curr[j - 1]);
}
prev = curr;
}
/* L[m][n] contains length of LCS for X[0..n-1]
and Y[0..m-1] */
return prev[n];
}
void reverseStr(string& str)
{
int n = str.length();
// Swap character starting from two
// corners
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
// LCS based function to find minimum number of
// insertions
int findMinInsertionsLCS(string str, int n)
{
// Creata another string to store reverse of 'str'
string rev = "";
rev = str;
reverseStr(rev);
// The output is length of string minus length of lcs of
// str and it reverse
return (n - lcs(str, rev, n, n));
}
// Driver code
int main()
{
string str = "geeks";
cout << findMinInsertionsLCS(str, str.length());
return 0;
}
// This code is contributed by Sanskar
|
linear
|
quadratic
|
// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
// easy to understand as compared to previous version.
#include <bits/stdc++.h>
using namespace std;
int maxLength; // variables to store and
string res; // update maxLength and res
// A utility function to get the longest palindrome
// starting and expanding out from given center indices
void cSubUtil(string& s, int l, int r)
{
// check if the indices lie in the range of string
// and also if it is palindrome
while (l >= 0 && r < s.length() && s[l] == s[r]) {
// expand the boundary
l--;
r++;
}
// if it's length is greater than maxLength update
// maxLength and res
if (r - l - 1 >= maxLength) {
res = s.substr(l + 1, r - l - 1);
maxLength = r - l - 1;
}
return;
}
// A function which takes a string prints the LPS and
// returns the length of LPS
int longestPalSubstr(string str)
{
res = "";
maxLength = 1;
// for every index in the string check palindromes
// starting from that index
for (int i = 0; i < str.length(); i++) {
// check for odd length palindromes
cSubUtil(str, i, i);
// check for even length palindromes
cSubUtil(str, i, i + 1);
}
cout << "Longest palindrome substring is: ";
cout << res << "\n";
return maxLength;
}
// Driver program to test above functions
int main()
{
string str = "forgeeksskeegfor";
cout << "\nLength is: " << longestPalSubstr(str)
<< endl;
return 0;
}
|
constant
|
quadratic
|
// c++ program to Count number of ways we
// can get palindrome string from a given
// string
#include<bits/stdc++.h>
using namespace std;
// function to find the substring of the
// string
string substring(string s,int a,int b)
{
string s1="";
// extract the specified position of
// the string
for(int i = a; i < b; i++)
s1 = s1 + s[i];
return s1;
}
// can get palindrome string from a
// given string
vector<string> allPalindromeSubstring(string s)
{
vector<string> v ;
// moving the pivot from starting till
// end of the string
for (float pivot = 0; pivot < s.length();
pivot += .5)
{
// set radius to the first nearest
// element on left and right
float palindromeRadius = pivot -
(int)pivot;
// if the position needs to be
// compared has an element and the
// characters at left and right
// matches
while ((pivot + palindromeRadius)
< s.length() && (pivot - palindromeRadius)
>= 0 && s[((int)(pivot - palindromeRadius))]
== s[((int)(pivot + palindromeRadius))])
{
v.push_back(substring(s,(int)(pivot -
palindromeRadius), (int)(pivot
+ palindromeRadius + 1)));
// increasing the radius by 1 to point
// to the next elements in left and right
palindromeRadius++;
}
}
return v;
}
// Driver code
int main()
{
vector <string> v =
allPalindromeSubstring("hellolle");
cout << v.size() << endl;
for(int i = 0; i < v.size(); i++)
cout << v[i] << ",";
cout << endl;
v = allPalindromeSubstring("geeksforgeeks");
cout << v.size() << endl;
for(int i = 0; i < v.size(); i++)
cout << v[i] << ",";
}
// This code is contributed by Arnab Kundu.
|
linear
|
cubic
|
// C++ program to print all palindromic partitions
// of a given string.
#include <bits/stdc++.h>
using namespace std;
// Returns true if str is palindrome, else false
bool checkPalindrome(string str)
{
int len = str.length();
len--;
for (int i=0; i<len; i++)
{
if (str[i] != str[len])
return false;
len--;
}
return true;
}
void printSolution(vector<vector<string> > partitions)
{
for (int i = 0; i < partitions.size(); ++i)
{
for(int j = 0; j < partitions[i].size(); ++j)
cout << partitions[i][j] << " ";
cout << endl;
}
return;
}
// Goes through all indexes and recursively add remaining
// partitions if current string is palindrome.
void addStrings(vector<vector<string> > &v, string &s,
vector<string> &temp, int index)
{
int len = s.length();
string str;
vector<string> current = temp;
if (index == 0)
temp.clear();
for (int i = index; i < len; ++i)
{
str = str + s[i];
if (checkPalindrome(str))
{
temp.push_back(str);
if (i+1 < len)
addStrings(v,s,temp,i+1);
else
v.push_back(temp);
temp = current;
}
}
return;
}
// Generates all palindromic partitions of 's' and
// stores the result in 'v'.
void partition(string s, vector<vector<string> >&v)
{
vector<string> temp;
addStrings(v, s, temp, 0);
printSolution(v);
return;
}
// Driver code
int main()
{
string s = "geeks";
vector<vector<string> > partitions;
partition(s, partitions);
return 0;
}
|
linear
|
quadratic
|
// Counts Palindromic Subsequence in a given String
#include <cstring>
#include <iostream>
using namespace std;
// Function return the total palindromic subsequence
int countPS(string str)
{
int N = str.length();
// create a 2D array to store the count of palindromic
// subsequence
int cps[N + 1][N + 1];
memset(cps, 0, sizeof(cps));
// palindromic subsequence of length 1
for (int i = 0; i < N; i++)
cps[i][i] = 1;
// check subsequence of length L is palindrome or not
for (int L = 2; L <= N; L++) {
for (int i = 0; i <= N-L; i++) {
int k = L + i - 1;
if (str[i] == str[k])
cps[i][k]
= cps[i][k - 1] + cps[i + 1][k] + 1;
else
cps[i][k] = cps[i][k - 1] + cps[i + 1][k]
- cps[i + 1][k - 1];
}
}
// return total palindromic subsequence
return cps[0][N - 1];
}
// Driver program
int main()
{
string str = "abcb";
cout << "Total palindromic subsequence are : "
<< countPS(str) << endl;
return 0;
}
|
quadratic
|
quadratic
|
// C++ program to counts Palindromic Subsequence
// in a given String using recursion
#include <bits/stdc++.h>
using namespace std;
int n, dp[1000][1000];
string str = "abcb";
// Function return the total
// palindromic subsequence
int countPS(int i, int j)
{
if (i > j)
return 0;
if (dp[i][j] != -1)
return dp[i][j];
if (i == j)
return dp[i][j] = 1;
else if (str[i] == str[j])
return dp[i][j]
= countPS(i + 1, j) +
countPS(i, j - 1) + 1;
else
return dp[i][j] = countPS(i + 1, j) +
countPS(i, j - 1) -
countPS(i + 1, j - 1);
}
// Driver code
int main()
{
memset(dp, -1, sizeof(dp));
n = str.size();
cout << "Total palindromic subsequence are : "
<< countPS(0, n - 1) << endl;
return 0;
}
// this code is contributed by Kushdeep Mittal
|
quadratic
|
quadratic
|
// C++ program for getting minimum character to be
// added at front to make string palindrome
#include<bits/stdc++.h>
using namespace std;
// function for checking string is palindrome or not
bool ispalindrome(string s)
{
int l = s.length();
int j;
for(int i = 0, j = l - 1; i <= j; i++, j--)
{
if(s[i] != s[j])
return false;
}
return true;
}
// Driver code
int main()
{
string s = "BABABAA";
int cnt = 0;
int flag = 0;
while(s.length()>0)
{
// if string becomes palindrome then break
if(ispalindrome(s))
{
flag = 1;
break;
}
else
{
cnt++;
// erase the last element of the string
s.erase(s.begin() + s.length() - 1);
}
}
// print the number of insertion at front
if(flag)
cout << cnt;
}
|
constant
|
quadratic
|
// C++ program for getting minimum character to be
// added at front to make string palindrome
#include <bits/stdc++.h>
using namespace std;
// returns vector lps for given string str
vector<int> computeLPSArray(string str)
{
int M = str.length();
vector<int> lps(M);
int len = 0;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to M-1
int i = 1;
while (i < M)
{
if (str[i] == str[len])
{
len++;
lps[i] = len;
i++;
}
else // (str[i] != str[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0)
{
len = lps[len-1];
// Also, note that we do not increment
// i here
}
else // if (len == 0)
{
lps[i] = 0;
i++;
}
}
}
return lps;
}
// Method returns minimum character to be added at
// front to make string palindrome
int getMinCharToAddedToMakeStringPalin(string str)
{
string revStr = str;
reverse(revStr.begin(), revStr.end());
// Get concatenation of string, special character
// and reverse string
string concat = str + "$" + revStr;
// Get LPS array of this concatenated string
vector<int> lps = computeLPSArray(concat);
// By subtracting last entry of lps vector from
// string length, we will get our result
return (str.length() - lps.back());
}
// Driver program to test above functions
int main()
{
string str = "AACECAAAA";
cout << getMinCharToAddedToMakeStringPalin(str);
return 0;
}
|
linear
|
linear
|
/* A C++ program to answer queries to check whether
the substrings are palindrome or not efficiently */
#include <bits/stdc++.h>
using namespace std;
#define p 101
#define MOD 1000000007
// Structure to represent a query. A query consists
// of (L, R) and we have to answer whether the substring
// from index-L to R is a palindrome or not
struct Query {
int L, R;
};
// A function to check if a string str is palindrome
// in the range L to R
bool isPalindrome(string str, int L, int R)
{
// Keep comparing characters while they are same
while (R > L)
if (str[L++] != str[R--])
return (false);
return (true);
}
// A Function to find pow (base, exponent) % MOD
// in log (exponent) time
unsigned long long int modPow(
unsigned long long int base,
unsigned long long int exponent)
{
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
unsigned long long int temp = modPow(base, exponent / 2);
if (exponent % 2 == 0)
return (temp % MOD * temp % MOD) % MOD;
else
return (((temp % MOD * temp % MOD) % MOD)
* base % MOD)
% MOD;
}
// A Function to calculate Modulo Multiplicative Inverse of 'n'
unsigned long long int findMMI(unsigned long long int n)
{
return modPow(n, MOD - 2);
}
// A Function to calculate the prefix hash
void computePrefixHash(
string str, int n,
unsigned long long int prefix[],
unsigned long long int power[])
{
prefix[0] = 0;
prefix[1] = str[0];
for (int i = 2; i <= n; i++)
prefix[i] = (prefix[i - 1] % MOD
+ (str[i - 1] % MOD
* power[i - 1] % MOD)
% MOD)
% MOD;
return;
}
// A Function to calculate the suffix hash
// Suffix hash is nothing but the prefix hash of
// the reversed string
void computeSuffixHash(
string str, int n,
unsigned long long int suffix[],
unsigned long long int power[])
{
suffix[0] = 0;
suffix[1] = str[n - 1];
for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++)
suffix[j] = (suffix[j - 1] % MOD
+ (str[i] % MOD
* power[j - 1] % MOD)
% MOD)
% MOD;
return;
}
// A Function to answer the Queries
void queryResults(string str, Query q[], int m, int n,
unsigned long long int prefix[],
unsigned long long int suffix[],
unsigned long long int power[])
{
for (int i = 0; i <= m - 1; i++) {
int L = q[i].L;
int R = q[i].R;
// Hash Value of Substring [L, R]
unsigned long long hash_LR
= ((prefix[R + 1] - prefix[L] + MOD) % MOD
* findMMI(power[L]) % MOD)
% MOD;
// Reverse Hash Value of Substring [L, R]
unsigned long long reverse_hash_LR
= ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD
* findMMI(power[n - R - 1]) % MOD)
% MOD;
// If both are equal then
// the substring is a palindrome
if (hash_LR == reverse_hash_LR) {
if (isPalindrome(str, L, R) == true)
printf("The Substring [%d %d] is a "
"palindrome\n",
L, R);
else
printf("The Substring [%d %d] is not a "
"palindrome\n",
L, R);
}
else
printf("The Substring [%d %d] is not a "
"palindrome\n",
L, R);
}
return;
}
// A Dynamic Programming Based Approach to compute the
// powers of 101
void computePowers(unsigned long long int power[], int n)
{
// 101^0 = 1
power[0] = 1;
for (int i = 1; i <= n; i++)
power[i] = (power[i - 1] % MOD * p % MOD) % MOD;
return;
}
/* Driver program to test above function */
int main()
{
string str = "abaaabaaaba";
int n = str.length();
// A Table to store the powers of 101
unsigned long long int power[n + 1];
computePowers(power, n);
// Arrays to hold prefix and suffix hash values
unsigned long long int prefix[n + 1], suffix[n + 1];
// Compute Prefix Hash and Suffix Hash Arrays
computePrefixHash(str, n, prefix, power);
computeSuffixHash(str, n, suffix, power);
Query q[] = { { 0, 10 }, { 5, 8 }, { 2, 5 }, { 5, 9 } };
int m = sizeof(q) / sizeof(q[0]);
queryResults(str, q, m, n, prefix, suffix, power);
return (0);
}
|
linear
|
quadratic
|
// C++ program to get largest palindrome changing
// atmost K digits
#include <bits/stdc++.h>
using namespace std;
// Returns maximum possible
// palindrome using k changes
string maximumPalinUsingKChanges(string str, int k)
{
string palin = str;
// Initialize l and r by leftmost and
// rightmost ends
int l = 0;
int r = str.length() - 1;
// first try to make string palindrome
while (l < r) {
// Replace left and right character by
// maximum of both
if (str[l] != str[r]) {
palin[l] = palin[r] =
max(str[l], str[r]);
k--;
}
l++;
r--;
}
// If k is negative then we can't make
// string palindrome
if (k < 0)
return "Not possible";
l = 0;
r = str.length() - 1;
while (l <= r) {
// At mid character, if K>0 then change
// it to 9
if (l == r) {
if (k > 0)
palin[l] = '9';
}
// If character at lth (same as rth) is
// less than 9
if (palin[l] < '9') {
/* If none of them is changed in the
previous loop then subtract 2 from K
and convert both to 9 */
if (k >= 2 && palin[l] == str[l]
&& palin[r] == str[r]) {
k -= 2;
palin[l] = palin[r] = '9';
}
/* If one of them is changed
in the previous
loop then subtract 1 from K
(1 more is
subtracted already) and make them 9 */
else if (k >= 1
&& (palin[l] != str[l]
|| palin[r] != str[r])) {
k--;
palin[l] = palin[r] = '9';
}
}
l++;
r--;
}
return palin;
}
// Driver code to test above methods
int main()
{
string str = "43435";
int k = 3;
cout << maximumPalinUsingKChanges(str, k);
return 0;
}
|
linear
|
linear
|
// A recursive C++ program to
// check whether a given number
// is palindrome or not
#include <bits/stdc++.h>
using namespace std;
// A recursive function that
// check a str[s..e] is
// palindrome or not.
bool isPalRec(char str[],
int s, int e)
{
// If there is only one character
if (s == e)
return true;
// If first and last
// characters do not match
if (str[s] != str[e])
return false;
// If there are more than
// two characters, check if
// middle substring is also
// palindrome or not.
if (s < e + 1)
return isPalRec(str, s + 1, e - 1);
return true;
}
bool isPalindrome(char str[])
{
int n = strlen(str);
// An empty string is
// considered as palindrome
if (n == 0)
return true;
return isPalRec(str, 0, n - 1);
}
// Driver Code
int main()
{
char str[] = "geeg";
if (isPalindrome(str))
cout << "Yes";
else
cout << "No";
return 0;
}
// This code is contributed by shivanisinghss2110
|
linear
|
linear
|
#include <iostream>
using namespace std;
bool isPalindrome(string s, int i){
if(i > s.size()/2){
return true ;
}
return s[i] == s[s.size()-i-1] && isPalindrome(s, i+1) ;
}
int main()
{
string str = "geeg" ;
if (isPalindrome(str, 0))
cout << "Yes";
else
cout << "No";
return 0;
}
|
linear
|
linear
|
// C++ implementation to find maximum length
// substring which is not palindrome
#include <bits/stdc++.h>
using namespace std;
// utility function to check whether
// a string is palindrome or not
bool isPalindrome(string str)
{
// Check for palindrome.
int n = str.size();
for (int i=0; i < n/2; i++)
if (str.at(i) != str.at(n-i-1))
return false;
// palindrome string
return true;
}
// function to find maximum length
// substring which is not palindrome
int maxLengthNonPalinSubstring(string str)
{
int n = str.size();
char ch = str.at(0);
// to check whether all characters
// of the string are same or not
int i = 1;
for (i=1; i<n; i++)
if (str.at(i) != ch)
break;
// All characters are same, we can't
// make a non-palindromic string.
if (i == n)
return 0;
// If string is palindrome, we can make
// it non-palindrome by removing any
// corner character
if (isPalindrome(str))
return n-1;
// Complete string is not a palindrome.
return n;
}
// Driver program to test above
int main()
{
string str = "abba";
cout << "Maximum length = "
<< maxLengthNonPalinSubstring(str);
return 0;
}
|
linear
|
linear
|
// C++ program to find minimum step to delete a string
#include <bits/stdc++.h>
using namespace std;
/* method returns minimum step for deleting the string,
where in one step a palindrome is removed */
int helper(string str, int si, int ei,
vector<vector<int> >& dp)
{
// if the string is empty
// need no operation
if (si > ei)
return 0;
// string length one
// need one operation
if (ei - si + 1 == 1)
return 1;
// if already calculated
if (dp[si][ei] != -1)
return dp[si][ei];
// to consider three options
int op1 = 1e9, op2 = 1e9, op3 = 1e9;
// delete first char and call
// on the smaller subproblem
op1 = 1 + helper(str, si + 1, ei, dp);
// first two characters are same
if (str[si] == str[si + 1])
op2 = 1 + helper(str, si + 2, ei, dp);
// found another index where the
// character is same as si-th character
for (int i = si + 2; i <= ei; i++) {
if (str[si] == str[i])
op3 = min(op3,
helper(str, si + 1, i - 1, dp)
+ helper(str, i + 1, ei, dp));
}
// return the minimum b/w three options
return dp[si][ei] = min({ op1, op2, op3 });
}
int minStepToDeleteString(string s)
{
int n = s.size();
// dp table to remove repeatations
vector<vector<int> > dp(n, vector<int>(n, -1));
// passing starting and ending index
return helper(s, 0, n - 1, dp);
}
// Driver Code
int main()
{
string str = "2553432";
cout << minStepToDeleteString(str) << endl;
return 0;
}
// this code is contributed by rajdeep999
|
quadratic
|
quadratic
|
// C++ program to query number of palindromic
// substrings of a string in a range
#include <bits/stdc++.h>
using namespace std;
#define M 50
// Utility method to construct the dp array
void constructDP(int dp[M][M], string str)
{
int l = str.length();
// declare 2D array isPalin, isPalin[i][j] will
// be 1 if str(i..j) is palindrome
int isPalin[l + 1][l + 1];
// initialize dp and isPalin array by zeros
for (int i = 0; i <= l; i++) {
for (int j = 0; j <= l; j++) {
isPalin[i][j] = dp[i][j] = 0;
}
}
// loop for starting index of range
for (int i = l - 1; i >= 0; i--) {
// initialize value for one character strings as 1
isPalin[i][i] = 1;
dp[i][i] = 1;
// loop for ending index of range
for (int j = i + 1; j < l; j++) {
/* isPalin[i][j] will be 1 if ith and
jth characters are equal and mid
substring str(i+1..j-1) is also a
palindrome */
isPalin[i][j] = (str[i] == str[j] && (i + 1 > j - 1 || isPalin[i + 1][j - 1]));
/* dp[i][j] will be addition of number
of palindromes from i to j-1 and i+1
to j subtracting palindromes from i+1
to j-1 (as counted twice) plus 1 if
str(i..j) is also a palindrome */
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j];
}
}
}
// method returns count of palindromic substring in range (l, r)
int countOfPalindromeInRange(int dp[M][M], int l, int r)
{
return dp[l][r];
}
// Driver code to test above methods
int main()
{
string str = "xyaabax";
int dp[M][M];
constructDP(dp, str);
int l = 3;
int r = 5;
cout << countOfPalindromeInRange(dp, l, r);
return 0;
}
|
quadratic
|
quadratic
|
// CPP program to find minimum number
// of insertions to make a string
// palindrome
#include <bits/stdc++.h>
using namespace std;
// Function will return number of
// characters to be added
int minInsertion(string str)
{
// To store string length
int n = str.length();
// To store number of characters
// occurring odd number of times
int res = 0;
// To store count of each
// character
int count[26] = { 0 };
// To store occurrence of each
// character
for (int i = 0; i < n; i++)
count[str[i] - 'a']++;
// To count characters with odd
// occurrence
for (int i = 0; i < 26; i++)
if (count[i] % 2 == 1)
res++;
// As one character can be odd return
// res - 1 but if string is already
// palindrome return 0
return (res == 0) ? 0 : res - 1;
}
// Driver program
int main()
{
string str = "geeksforgeeks";
cout << minInsertion(str);
return 0;
}
|
constant
|
linear
|
// C++ program to find n=th even length string.
#include <bits/stdc++.h>
using namespace std;
// Function to find nth even length Palindrome
string evenlength(string n)
{
// string r to store resultant
// palindrome. Initialize same as s
string res = n;
// In this loop string r stores
// reverse of string s after the
// string s in consecutive manner .
for (int j = n.length() - 1; j >= 0; --j)
res += n[j];
return res;
}
// Driver code
int main()
{
string n = "10";
// Function call
cout << evenlength(n);
return 0;
}
|
linear
|
linear
|
//code to make 'ab' free string
#include<bits/stdc++.h>
using namespace std;
// code to make 'ab' free string
int abFree(string s)
{
int n = s.length();
char char_array[n + 1];
// convert string into char array
strcpy(char_array, s.c_str());
// Traverse from end. Keep track of count
// b's. For every 'a' encountered, add b_count
// to result and double b_count.
int b_count = 0;
int res = 0;
for (int i = 0; i < n; i++)
{
if (char_array[n - i - 1] == 'a')
{
res = (res + b_count);
b_count = (b_count * 2);
} else {
b_count += 1;
}
}
return res;
}
// Driver code
int main()
{
string s = "abbaa";
cout<<abFree(s)<<endl;
s = "aab";
cout<<abFree(s)<<endl;
s = "ababab";
cout<<abFree(s)<<endl;
return 0;
}
// This code is contributed by Rajput-Ji
|
linear
|
linear
|
// C++ implementation of program to find the maximum length
// that can be removed
#include<bits/stdc++.h>
using namespace std;
// Function to find the length of longest sub-string that
// can me make removed
// arr --> pair type of array whose first field store
// character in string and second field stores
// corresponding index of that character
int longestNull(string str)
{
vector<pair<char,int> > arr;
// store {'@',-1} in arr , here this value will
// work as base index
arr.push_back({'@', -1});
int maxlen = 0; // Initialize result
// one by one iterate characters of string
for (int i = 0; i < str.length(); ++i)
{
// make pair of char and index , then store
// them into arr
arr.push_back({str[i], i});
// now if last three elements of arr[] are making
// sub-string "100" or not
while (arr.size()>=3 &&
arr[arr.size()-3].first=='1' &&
arr[arr.size()-2].first=='0' &&
arr[arr.size()-1].first=='0')
{
// if above condition is true then delete
// sub-string "100" from arr[]
arr.pop_back();
arr.pop_back();
arr.pop_back();
}
// index of current last element in arr[]
int tmp = arr.back().second;
// This is important, here 'i' is the index of
// current character inserted into arr[]
// and 'tmp' is the index of last element in arr[]
// after continuous deletion of sub-string
// "100" from arr[] till we make it null, difference
// of these to 'i-tmp' gives the length of current
// sub-string that can be make null by continuous
// deletion of sub-string "100"
maxlen = max(maxlen, i - tmp);
}
return maxlen;
}
// Driver program to run the case
int main()
{
cout << longestNull("1011100000100");
return 0;
}
|
linear
|
linear
|
// C++ program to find minimum number of flip to make binary
// string alternate
#include <bits/stdc++.h>
using namespace std;
// Utility method to flip a character
char flip(char ch) { return (ch == '0') ? '1' : '0'; }
// Utility method to get minimum flips when alternate
// string starts with expected char
int getFlipWithStartingCharcter(string str, char expected)
{
int flipCount = 0;
for (int i = 0; i < str.length(); i++) {
// if current character is not expected, increase
// flip count
if (str[i] != expected)
flipCount++;
// flip expected character each time
expected = flip(expected);
}
return flipCount;
}
// method return minimum flip to make binary string
// alternate
int minFlipToMakeStringAlternate(string str)
{
// return minimum of following two
// 1) flips when alternate string starts with 0
// 2) flips when alternate string starts with 1
return min(getFlipWithStartingCharcter(str, '0'),
getFlipWithStartingCharcter(str, '1'));
}
// Driver code to test above method
int main()
{
string str = "0001010111";
cout << minFlipToMakeStringAlternate(str);
return 0;
}
// This code is contributed by Sania Kumari Gupta
// (kriSania804)
|
constant
|
linear
|
// An efficient C++ program to find 2's complement
#include<bits/stdc++.h>
using namespace std;
// Function to find two's complement
string findTwoscomplement(string str)
{
int n = str.length();
// Traverse the string to get first '1' from
// the last of string
int i;
for (i = n-1 ; i >= 0 ; i--)
if (str[i] == '1')
break;
// If there exists no '1' concatenate 1 at the
// starting of string
if (i == -1)
return '1' + str;
// Continue traversal after the position of
// first '1'
for (int k = i-1 ; k >= 0; k--)
{
//Just flip the values
if (str[k] == '1')
str[k] = '0';
else
str[k] = '1';
}
// return the modified string
return str;
}
// Driver code
int main()
{
string str = "00000101";
cout << findTwoscomplement(str);
return 0;
}
|
constant
|
linear
|
// C++ program to count all distinct
// binary strings with two consecutive 1's
#include <iostream>
using namespace std;
// Returns count of n length binary
// strings with consecutive 1's
int countStrings(int n)
{
// Count binary strings without consecutive 1's.
// See the approach discussed on be
// ( http://goo.gl/p8A3sW )
int a[n], b[n];
a[0] = b[0] = 1;
for (int i = 1; i < n; i++)
{
a[i] = a[i - 1] + b[i - 1];
b[i] = a[i - 1];
}
// Subtract a[n-1]+b[n-1] from 2^n
return (1 << n) - a[n - 1] - b[n - 1];
}
// Driver code
int main()
{
cout << countStrings(5) << endl;
return 0;
}
|
linear
|
linear
|
// Recursive C++ program to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
#include <iostream>
using namespace std;
// Recursive function to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
void print(string str, int index)
{
if (index == str.size())
{
cout << str << endl;
return;
}
if (str[index] == '?')
{
// replace '?' by '0' and recurse
str[index] = '0';
print(str, index + 1);
// replace '?' by '1' and recurse
str[index] = '1';
print(str, index + 1);
// No need to backtrack as string is passed
// by value to the function
}
else
print(str, index + 1);
}
// Driver code to test above function
int main()
{
string str = "1??0?101";
print(str, 0);
return 0;
}
|
quadratic
|
np
|
// Iterative C++ program to generate all binary
// strings formed by replacing each wildcard
// character by 0 or 1
#include <iostream>
#include <queue>
using namespace std;
// Iterative function to generate all binary strings
// formed by replacing each wildcard character by 0
// or 1
void print(string str)
{
queue<string> q;
q.push(str);
while (!q.empty())
{
string str = q.front();
// find position of first occurrence of wildcard
size_t index = str.find('?');
// If no matches were found,
// find returns string::npos
if(index != string::npos)
{
// replace '?' by '0' and push string into queue
str[index] = '0';
q.push(str);
// replace '?' by '1' and push string into queue
str[index] = '1';
q.push(str);
}
else
// If no wildcard characters are left,
// print the string.
cout << str << endl;
q.pop();
}
}
// Driver code to test above function
int main()
{
string str = "1??0?101";
print(str);
return 0;
}
|
np
|
quadratic
|
// C++ program to implement the approach
#include <bits/stdc++.h>
using namespace std;
/* we store processed strings in all (array)
we see if string as "?", if so, replace it with 0 and 1
and send it back to recursive func until base case is
reached which is no wildcard left */
vector<string> res;
void genBin(string s)
{
auto pos = s.find('?');
if (pos != string::npos) {
// copying s to s1
string s1 = s;
// replacing first occurrence of ?
// with 0
s1.replace(pos, 1, "0");
// copying s to s2
string s2 = s;
// replacing first occurrence of ?
// with 1
s2.replace(pos, 1, "1");
genBin(s1);
genBin(s2);
}
else {
res.push_back(s);
}
}
// Driver code
int main()
{
genBin("1??0?101");
for (string x : res) {
cout << x << " ";
}
}
// This code is contributed by phasing17
|
np
|
quadratic
|
#include <bits/stdc++.h>
using namespace std;
// The function that adds two-bit sequences and returns the addition
string addBitStrings(string str1, string str2)
{
string ans = "";
int i = str1.size() - 1;
int j = str2.size() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry) {
carry += ((i >= 0) ? (str1[i--] - '0') : (0));
carry += ((j >= 0) ? (str2[j--] - '0') : (0));
ans = char('0' + (carry % 2)) + ans;
carry = carry / 2;
}
return ans;
}
// Driver program to test above functions
int main()
{
string str1 = "1100011";
string str2 = "10";
cout << "Sum is " << addBitStrings(str1, str2);
return 0;
}
|
constant
|
linear
|
// C++ program to count all distinct binary strings
// without two consecutive 1's
#include <iostream>
using namespace std;
int countStrings(int n)
{
int a[n], b[n];
a[0] = b[0] = 1;
for (int i = 1; i < n; i++)
{
a[i] = a[i-1] + b[i-1];
b[i] = a[i-1];
}
return a[n-1] + b[n-1];
}
// Driver program to test above functions
int main()
{
cout << countStrings(3) << endl;
return 0;
}
|
linear
|
linear
|
// C++ program to count all distinct binary strings
// without two consecutive 1's
#include <bits/stdc++.h>
using namespace std;
int countStrings(int n)
{
int a = 1, b = 1;
for (int i = 1; i < n; i++) {
// Here we have used the temp variable because we
// want to assign the older value of a to b
int temp = a + b;
b = a;
a = temp;
}
return a + b;
}
// Driver program to test above functions
int main()
{
cout << countStrings(3) << endl;
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
|
constant
|
linear
|
// C++ program to check if a string is of
// the form a^nb^n.
#include <iostream>
using namespace std;
// Returns true str is of the form a^nb^n.
bool isAnBn(string str)
{
int n = str.length();
// After this loop 'i' has count of a's
int i;
for (i = 0; i < n; i++)
if (str[i] != 'a')
break;
// Since counts of a's and b's should
// be equal, a should appear exactly
// n/2 times
if (i * 2 != n)
return false;
// Rest of the characters must be all 'b'
int j;
for (j = i; j < n; j++)
if (str[j] != 'b')
return false;
return true;
}
// Driver code
int main()
{
string str = "abab";
// Function call
isAnBn(str) ? cout << "Yes" : cout << "No";
return 0;
}
|
constant
|
linear
|
// C++ code to check a^nb^n
// pattern
#include <iostream>
using namespace std;
// Returns "Yes" str is of the form a^nb^n.
string isAnBn(string str)
{
int n = str.length();
if (n & 1)
return "No";
// check first half is 'a' and other half is full of 'b'
int i;
for (i = 0; i < n / 2; i++)
if (str[i] != 'a' || str[n - i - 1] != 'b')
return "No";
return "Yes";
}
// Driver code
int main()
{
string str = "ab";
// Function call
cout << isAnBn(str);
return 0;
}
|
constant
|
linear
|
// C++ implementation to find the binary
// representation of next greater integer
#include <bits/stdc++.h>
using namespace std;
// function to find the required
// binary representation
string nextGreater(string num)
{
int l = num.size();
// examine bits from the right
for (int i=l-1; i>=0; i--)
{
// if '0' is encountered, convert
// it to '1' and then break
if (num.at(i) == '0')
{
num.at(i) = '1';
break;
}
// else convert '1' to '0'
else
num.at(i) = '0';
// if the binary representation
// contains only the set bits
if (i < 0)
num = "1" + num;
}
// final binary representation
// of the required integer
return num;
}
// Driver program to test above
int main()
{
string num = "10011";
cout << "Binary representation of next number = "
<< nextGreater(num);
return 0;
}
|
linear
|
linear
|
// C++ program to find next permutation in a
// binary string.
#include <bits/stdc++.h>
using namespace std;
// Function to find the next greater number
// with same number of 1's and 0's
string nextGreaterWithSameDigits(string bnum)
{
int l = bnum.size();
int i;
for (int i=l-2; i>=1; i--)
{
// locate first 'i' from end such that
// bnum[i]=='0' and bnum[i+1]=='1'
// swap these value and break;
if (bnum.at(i) == '0' &&
bnum.at(i+1) == '1')
{
char ch = bnum.at(i);
bnum.at(i) = bnum.at(i+1);
bnum.at(i+1) = ch;
break;
}
}
// if no swapping performed
if (i == 0)
"no greater number";
// Since we want the smallest next value,
// shift all 1's at the end in the binary
// substring starting from index 'i+2'
int j = i+2, k = l-1;
while (j < k)
{
if (bnum.at(j) == '1' && bnum.at(k) == '0')
{
char ch = bnum.at(j);
bnum.at(j) = bnum.at(k);
bnum.at(k) = ch;
j++;
k--;
}
// special case while swapping if '0'
// occurs then break
else if (bnum.at(i) == '0')
break;
else
j++;
}
// required next greater number
return bnum;
}
// Driver program to test above
int main()
{
string bnum = "10010";
cout << "Binary representation of next greater number = "
<< nextGreaterWithSameDigits(bnum);
return 0;
}
|
constant
|
linear
|
// CPP Program to find the length of
// substring with maximum difference of
// zeros and ones in binary string.
#include <iostream>
using namespace std;
// Returns the length of substring with
// maximum difference of zeroes and ones
// in binary string
int findLength(string str, int n)
{
int current_sum = 0;
int max_sum = 0;
// traverse a binary string from left
// to right
for (int i = 0; i < n; i++) {
// add current value to the current_sum
// according to the Character
// if it's '0' add 1 else -1
current_sum += (str[i] == '0' ? 1 : -1);
if (current_sum < 0)
current_sum = 0;
// update maximum sum
max_sum = max(current_sum, max_sum);
}
// return -1 if string does not contain
// any zero that means all ones
// otherwise max_sum
return max_sum == 0 ? -1 : max_sum;
}
// Driven Program
int main()
{
string s = "11000010001";
int n = 11;
cout << findLength(s, n) << endl;
return 0;
}
|
linear
|
linear
|
// CPP program to find min flips in binary
// string to make all characters equal
#include <bits/stdc++.h>
using namespace std;
// To find min number of flips in binary string
int findFlips(char str[], int n)
{
char last = ' '; int res = 0;
for (int i = 0; i < n; i++) {
// If last character is not equal
// to str[i] increase res
if (last != str[i])
res++;
last = str[i];
}
// To return min flips
return res / 2;
}
// Driver program to check findFlips()
int main()
{
char str[] = "00011110001110";
int n = strlen(str);
cout << findFlips(str, n);
return 0;
}
|
constant
|
linear
|
// C++ program to add two binary strings
#include <bits/stdc++.h>
using namespace std;
// This function adds two binary strings and return
// result as a third string
string addBinary(string A, string B)
{
// If the length of string A is greater than the length
// of B then just swap the string by calling the
// same function and make sure to return the function
// otherwise recursion will occur which leads to
// calling the same function twice
if (A.length() > B.length())
return addBinary(B, A);
// Calculating the difference between the length of the
// two strings.
int diff = B.length() - A.length();
// Initialise the padding string which is used to store
// zeroes that should be added as prefix to the string
// which has length smaller than the other string.
string padding;
for (int i = 0; i < diff; i++)
padding.push_back('0');
A = padding + A;
string res;
char carry = '0';
for (int i = A.length() - 1; i >= 0; i--) {
// This if condition solves 110 111 possible cases
if (A[i] == '1' && B[i] == '1') {
if (carry == '1')
res.push_back('1'), carry = '1';
else
res.push_back('0'), carry = '1';
}
// This if condition solves 000 001 possible cases
else if (A[i] == '0' && B[i] == '0') {
if (carry == '1')
res.push_back('1'), carry = '0';
else
res.push_back('0'), carry = '0';
}
// This if condition solves 100 101 010 011 possible
// cases
else if (A[i] != B[i]) {
if (carry == '1')
res.push_back('0'), carry = '1';
else
res.push_back('1'), carry = '0';
}
}
// If at the end there is carry then just add it to the
// result
if (carry == '1')
res.push_back(carry);
// reverse the result
reverse(res.begin(), res.end());
// To remove leading zeroes
int index = 0;
while (index + 1 < res.length() && res[index] == '0')
index++;
return (res.substr(index));
}
// Driver program
int main()
{
string a = "1101", b = "100";
cout << addBinary(a, b) << endl;
return 0;
}
|
linear
|
linear
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.