Construct String with given frequency and minimum continuous occurrence of a letter
Last Updated :
31 Mar, 2023
Construct a string that contains a times letter 'A' and b times letter 'B' (a > b) such that the maximum continuous occurrence of a letter is as small as possible.
Examples:
Input: a = 4, b = 3
Output: ABABABA
Explanation: The other possible ways could be "AAAABBB" or "AABBAAB" etc.
But "ABABABA" is the most optimum solution with minimum consecutive occurrence.
Input: a = 5, b = 1
Output: AABAAA
Approach: The approach of the problem is based on the below observation:
Since a > b, it can be easily observed that 'B' is dividing the whole string in (b+1) parts.
According to the pigeonhole principle, at least one region must have at least p = ?a/(b+1)? A's. First, place p number of 'A' in every (b+1) region. Now remaining 'A's can be equally distributed in the regions.
Follow the below steps to solve the problem:
- The region is divided into (b+1) parts. So run a loop from 0 to (b+1) and start inserting for each part.
- First, calculate what should be the current value of insertion of 'A' (Using the Pigeonhole principle p = ceil(a/(b+1)) ) for each left region.
- Insert p times 'A' in the string and decrement the value of a.
- Now one region is completed, so insert a 'B' and decrement the value of b.
- Keep doing this till constraints of a and b allow you to do so.
- Return the final string as the answer.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to construct the string
string generateans(int a, int b)
{
int temp = b + 1;
string s;
// Run a loop until b is greater than 0
while (temp--) {
int each = a / (b + 1);
while (each--) {
s.push_back('A');
a--;
}
if (b > 0) {
s.push_back('B');
b--;
}
}
return s;
}
// Driver code
int main()
{
int a = 4, b = 3;
// Function call
cout << generateans(a, b);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
class GFG {
// Function to construct the string
public static String generateans(int a, int b)
{
int temp = b + 1;
String s = "";
// Run a loop until b is greater than 0
while (temp-- > 0) {
int each = a / (b + 1);
while (each-- > 0) {
s += 'A';
a--;
}
if (b > 0) {
s += 'B';
b--;
}
}
return s;
}
// Driver Code
public static void main(String[] args)
{
int a = 4, b = 3;
// Function call
System.out.print(generateans(a, b));
}
}
// This code is contributed by Rohit Pradhan
Python3
# Python code to implement the approach
# Function to construct the string
def generateans(a, b):
temp = b + 1
s = ""
# Run a loop until b is greater than 0
while temp>0:
each = (a // (b + 1))
while each>0:
s += 'A'
a -= 1
each -= 1
if (b > 0):
s += 'B'
b -= 1
temp -= 1
return s
# Driver code
a,b = 4,3
# Function call
print(generateans(a, b))
# This code is contributed by shinjanpatra
C#
// C# code to implement the approach
using System;
using System.Linq;
public class GFG
{
// Function to construct the string
public static string generateans(int a, int b)
{
int temp = b + 1;
string s = "";
// Run a loop until b is greater than 0
while (temp-- > 0) {
int each = a / (b + 1);
while (each-- > 0) {
s += 'A';
a--;
}
if (b > 0) {
s += 'B';
b--;
}
}
return s;
}
// Driver Code
public static void Main(string[] args)
{
int a = 4, b = 3;
// Function call
Console.WriteLine(generateans(a, b));
}
}
// This code is contributed by code_hunt.
JavaScript
<script>
// JavaScript code to implement the approach
// Function to construct the string
const generateans = (a, b) => {
let temp = b + 1;
let s = "";
// Run a loop until b is greater than 0
while (temp--) {
let each = parseInt(a / (b + 1));
while (each--) {
s += 'A';
a--;
}
if (b > 0) {
s += 'B';
b--;
}
}
return s;
}
// Driver code
let a = 4, b = 3;
// Function call
document.write(generateans(a, b));
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(a+b)
Auxiliary Space: O(a+b) because extra space is used for string s
Another approach:
We can start by appending 'AB' pairs until we are left with only 'a-b' 'A' characters. Then, we can append remaining 'A' characters at the end. This will give us the desired string with minimum consecutive occurrence.
C++
#include <bits/stdc++.h>
using namespace std;
string generateans(int a, int b) {
string s = "";
int countA = a, countB = b;
bool appendA = true;
while (countA > 0 || countB > 0) {
if (appendA) {
s += 'A';
countA--;
}
else {
s += 'B';
countB--;
}
if (countB == 0 && countA > 0) {
s += 'A';
countA--;
}
else if (countA == 0 && countB > 0) {
s += 'B';
countB--;
}
else if (countA > countB) {
appendA = true;
}
else {
appendA = false;
}
}
return s;
}
int main() {
int a = 4, b = 3;
cout << generateans(a, b) << endl;
return 0;
}
Java
// Java program to implement the above approach
import java.util.*;
public class Main {
public static String generateans(int a, int b) {
StringBuilder s = new StringBuilder();
int countA = a, countB = b;
boolean appendA = true;
while (countA > 0 || countB > 0) {
if (appendA) {
s.append('A');
countA--;
} else {
s.append('B');
countB--;
}
if (countB == 0 && countA > 0) {
s.append('A');
countA--;
} else if (countA == 0 && countB > 0) {
s.append('B');
countB--;
} else if (countA > countB) {
appendA = true;
} else {
appendA = false;
}
}
return s.toString();
}
public static void main(String[] args) {
int a = 4, b = 3;
System.out.println(generateans(a, b));
}
}
// Contributed by adityasha4x71
Python3
# Pyhton program to implement the above approach
def generateans(a, b):
s = ""
countA, countB = a, b
appendA = True
while countA > 0 or countB > 0:
if appendA:
s += 'A'
countA -= 1
else:
s += 'B'
countB -= 1
if countB == 0 and countA > 0:
s += 'A'
countA -= 1
elif countA == 0 and countB > 0:
s += 'B'
countB -= 1
elif countA > countB:
appendA = True
else:
appendA = False
return s
a, b = 4, 3
print(generateans(a, b))
# Contributed by adityasha4x71
C#
using System;
public class Program {
public static string GenerateAns(int a, int b)
{
string s = "";
int countA = a, countB = b;
bool appendA = true;
while (countA > 0 || countB > 0) {
if (appendA) {
s += 'A';
countA--;
}
else {
s += 'B';
countB--;
}
if (countB == 0 && countA > 0) {
s += 'A';
countA--;
}
else if (countA == 0 && countB > 0) {
s += 'B';
countB--;
}
else if (countA > countB) {
appendA = true;
}
else {
appendA = false;
}
}
return s;
}
public static void Main()
{
int a = 4, b = 3;
Console.WriteLine(GenerateAns(a, b));
}
}
JavaScript
// JavaScript program to implement the above approach
function generateans(a, b) {
let s = "";
let countA = a, countB = b;
let appendA = true;
while (countA > 0 || countB > 0) {
if (appendA) {
s += 'A';
countA--;
}
else {
s += 'B';
countB--;
}
if (countB == 0 && countA > 0) {
s += 'A';
countA--;
}
else if (countA == 0 && countB > 0) {
s += 'B';
countB--;
}
else if (countA > countB) {
appendA = true;
}
else {
appendA = false;
}
}
return s;
}
// Driver code
let a = 4, b = 3;
console.log(generateans(a, b));
Time Complexity: O(a+b)
Auxiliary Space: O(a+b)
Similar Reads
Pigeonhole Principle for CP | Identification, Approach & Problems In competitive programming, where people solve tough problems with computer code, the Pigeonhole Principle is like a secret tool. Even though it's a simple idea, it helps programmers tackle complex challenges. This article is your guide to understanding how this principle works and why it's crucial
8 min read
Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N Given an array of N integers, the task is to find a non-empty subset such that the sum of elements of the subset is divisible by N. Output any such subset with its size and the indices(1-based indexing) of elements in the original array if it exists. Prerequisites: Pigeonhole PrincipleExamples: Inpu
8 min read
Maximum adjacent difference in an array in its sorted form Given an array arr[] of size N, find the maximum difference between its two consecutive elements in its sorted form. Examples: Input: N = 3, arr[] = {1, 10, 5}Output: 5Explanation: Sorted array would be {1, 5, 10} and maximum adjacent difference would be 10 - 5 = 5 Input: N = 4, arr[] = {2, 4, 8, 11
8 min read
Construct String with given frequency and minimum continuous occurrence of a letter Construct a string that contains a times letter 'A' and b times letter 'B' (a > b) such that the maximum continuous occurrence of a letter is as small as possible. Examples: Input: a = 4, b = 3 Output: ABABABAExplanation: The other possible ways could be "AAAABBB" or "AABBAAB" etc. But "ABABABA"
7 min read
Find a triplet (X, Y, Z) such that all are divisible by A, exactly one is divisible by both A and B, and X + Y = Z Given two integers A and B, the task is to find a triplet (X, Y, Z) such that all of them are divisible by A, exactly one of them is divisible by both A and B, and X + Y = Z. Example: Input: A = 5, B = 3Output: 10 50 60Explanation: For the triplet (10, 50, 60), all of them are divisible by 5, 60 is
4 min read
Find Binary String of size at most 3N containing at least 2 given strings of size 2N as subsequences Given three binary strings a, b, and c each having 2*N characters each, the task is to find a string having almost 3*N characters such that at least two of the given three strings occur as its one of the subsequence. Examples: Input: a = "00", b = "11", c = "01"Output: "010"Explanation: The strings
11 min read
Minimum number of socks required to picked to have at least K pairs of the same color Given an array arr[] consisting of N integers such that arr[i] representing the number of socks of the color i and an integer K, the task is to find the minimum number of socks required to be picked to get at least K pairs of socks of the same color. Examples: Input: arr[] = {3, 4, 5, 3}, K = 6Outpu
5 min read
Count of subarrays of size K having at least one pair with absolute difference divisible by K-1 Given an arr[] consisting of N elements, the task is to count all subarrays of size K having atleast one pair whose absolute difference is divisible by K - 1.Examples: Input: arr[] = {1, 5, 3, 2, 17, 18}, K = 4 Output: 3 Explanation: The three subarrays of size 4 are: {1, 5, 3, 2}: Pair {5, 2} have
4 min read
Largest subset with sum of every pair as prime Given an array A[], find a subset of maximum size in which sum of every pair of elements is a prime number. Print its length and the subset. Consider many queries for different arrays and maximum value of an element as 100000. Examples : Input : A[] = {2, 1, 2} Output : 2 1 2 Explanation : Here, we
13 min read