VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-string-with-given-frequency-and-minimum-continuous-occurrence-of-a-letter/

⇱ Construct String with given frequency and minimum continuous occurrence of a letter - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct String with given frequency and minimum continuous occurrence of a letter

Last Updated : 23 Jul, 2025

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.


Output
ABABABA

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.


Output
ABABABA

Time Complexity: O(a+b)

Auxiliary Space: O(a+b)

Comment