Longest Happy String

Updated on 13 June, 2025
Longest Happy String header image

Problem Statement

The task is to construct the longest possible "happy" string using a defined number of three letters: 'a', 'b', and 'c'. A string qualifies as "happy" if it adheres to the following criteria:

  • It includes only the characters 'a', 'b', and 'c'.
  • It does not contain the sequences "aaa", "bbb", or "ccc".
  • The occurrences of 'a' do not exceed a specified integer a, occurrences of 'b' do not exceed b, and 'c' does not exceed c.

Given three integers representing the maximum allowable appearances of each character ('a', 'b', and 'c'), the goal is to produce the longest string that conforms to these conditions. The solution should return one example of such a string, or an empty string if a "happy" string isn't possible under the constraints.

Examples

Example 1

Input:

a = 1, b = 1, c = 7

Output:

"ccaccbcc"

Explanation:

"ccbccacc" would also be a correct answer.

Example 2

Input:

a = 7, b = 1, c = 0

Output:

"aabaa"

Explanation:

It is the only correct answer in this case.

Constraints

  • 0 <= a, b, c <= 100
  • a + b + c > 0

Approach and Intuition

The objective is to build the longest string possible without the sequences "aaa", "bbb", or "ccc", while also not exceeding the given number of 'a's, 'b's, and 'c's. Here's how one might approach this problem:

  1. Prioritize adding letters that have the highest remaining count, which assists in making the string as long as possible.
  2. To avoid sequences of three identical characters (like "aaa"), at most two identical characters should be placed consecutively.
  3. When deciding the next letter to add:
  • Check the current suffix of the string being constructed. If the last two characters are the same (for example, "aa"), the next character must differ.
  • If an additional character of a particular type can be added without violating the conditions, it should be added; otherwise, we choose the next most frequent character.
  1. This process involves continuously managing the counts of 'a', 'b', and 'c', ensuring they do not exceed the given limits.
  2. Incorporate a strategy to balance the addition of characters so that one type doesn’t prematurely run out when others are vastly available.
  3. Continue this process until no more characters can be added without breaking the rules.

Through this iterative method of building the string and strategically choosing which character to append next based on the current state of the string and the remaining counts of 'a', 'b', and 'c', we maximize the length of the "happy" string.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    string generateLongestDiverseString(int aCount, int bCount, int cCount) {
        int aStreak = 0, bStreak = 0, cStreak = 0;
        int maxLen = aCount + bCount + cCount;
        string result = "";

        for (int i = 0; i < maxLen; i++) {
            if ((aCount >= bCount && aCount >= cCount && aStreak != 2) ||
                (aCount > 0 && (bStreak == 2 || cStreak == 2))) {
                result += 'a';
                aCount--;
                aStreak++;
                bStreak = 0;
                cStreak = 0;
            } else if ((bCount >= aCount && bCount >= cCount && bStreak != 2) ||
                       (bCount > 0 && (cStreak == 2 || aStreak == 2))) {
                result += 'b';
                bCount--;
                bStreak++;
                aStreak = 0;
                cStreak = 0;
            } else if ((cCount >= aCount && cCount >= bCount && cStreak != 2) ||
                       (cCount > 0 and (aStreak == 2 || bStreak == 2))) {
                result += 'c';
                cCount--;
                cStreak++;
                aStreak = 0;
                bStreak = 0;
            }
        }
        return result;
    }
};

The provided C++ solution tackles the problem of generating the longest string using the characters 'a', 'b', and 'c', such that no three consecutive characters are the same. Here's how the solution approaches the issue:

  • It starts by initializing counters for the streaks of each character (aStreak, bStreak, cStreak) and their respective counts (aCount, bCount, cCount).
  • The function's primary loop runs through the total number of characters available (maxLen), determined by summing aCount, bCount, and cCount.
  • Inside the loop, the solution decides which character to append next based on:
    • The counts of each character relative to the others, ensuring the most frequent character is used unless it would form three consecutive same characters.
    • The streaks of other characters, to avoid having three consecutive occurrences of any character.
  • After selecting a character, it updates the respective character's count and reset the streaks for the other characters to zero while incrementing the streak of the chosen character.
  • This approach strategically balances the characters, using the highest available character count without violating the consecutive character condition, effectively creating the longest diverse string possible.

This solution ensures no conditions like 'aaa', 'bbb', or 'ccc', develop, harnessing checks and balances via streak and count, to construct the string with the necessary constraints.

java
class Solution {

    public String generateLongestString(int x, int y, int z) {
        int countX = 0, countY = 0, countZ = 0;
        int totalLoops = x + y + z;
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < totalLoops; i++) {
            if (
                (x >= y && x >= z && countX != 2) ||
                (x > 0 && (countY == 2 || countZ == 2))
            ) {
                result.append('a');
                x--;
                countX++;
                countY = 0;
                countZ = 0;
            } else if (
                (y >= x && y >= z && countY != 2) ||
                (y > 0 && (countZ == 2 || countX == 2))
            ) {
                result.append('b');
                y--;
                countY++;
                countX = 0;
                countZ = 0;
            } else if (
                (z >= x && z >= y && countZ != 2) ||
                (z > 0 && (countX == 2 || countY == 2))
            ) {
                result.append('c');
                z--;
                countZ++;
                countX = 0;
                countY = 0;
            }
        }
        return result.toString();
    }
}

The Java method generateLongestString provided in the code constructs the "longest happy string" based on the input values of x, y, and z. These values represent the maximum possible counts of 'a', 'b', and 'c' respectively. A string is considered "happy" if no three consecutive characters are the same.

  • The method initializes counters for 'a' (countX), 'b' (countY), and 'c' (countZ), all set to zero.
  • It also calculates the total number of loops required using the sum of x, y, and z.
  • A StringBuilder object result accumulates the resultant string.

In the loop, the method follows these rules to append the correct character:

  1. Append 'a' if either x is the largest number among x, y, and z not having reached 2 consecutive 'a's, or if 'b' or 'c' has reached 2 consecutive additions.
    • After appending 'a', decrement x, increment countX and reset countY and countZ to zero.
  2. Append 'b' under similar conditions: if y is the highest count or if appending 'b' would prevent three consecutive occurrences of 'a' or 'c'.
    • On appending 'b', similarly manage y, countY, countX, and countZ.
  3. Append 'c' if z is either the highest or to prevent a triad of consecutive 'a' or 'b'.
    • Adjust z, countZ, countX, and countY accordingly.

The loop continues until all characters declared by x, y, and z are exhausted, following which the result is converted to string format and returned. This method assures the generation of the longest sequence under the constraints provided, ensuring optimal character use without violating the "happy" condition.

python
class Solution:
    def generateString(self, x: int, y: int, z: int) -> str:
        streakA, streakB, streakC = 0, 0, 0
        iterations = x + y + z
        output = []

        for _ in range(iterations):
            if (x >= y and x >= z and streakA != 2) or (x > 0 and (streakB == 2 or streakC == 2)):
                output.append("a")
                x -= 1
                streakA += 1
                streakB = 0
                streakC = 0
            elif (y >= x and y >= z and streakB != 2) or (y > 0 and (streakC == 2 or streakA == 2)):
                output.append("b")
                y -= 1
                streakB += 1
                streakA = 0
                streakC = 0
            elif (z >= x and z >= y and streakC != 2) or (z > 0 and (streakA == 2 or streakB == 2)):
                output.append("c")
                z -= 1
                streakC += 1
                streakA = 0
                streakB = 0

        return "".join(output)

This Python solution focuses on generating the longest string where no three consecutive characters are the same, given counts of 'a's, 'b's, and 'c's. The solution involves the following steps:

  1. Initialize counters for streaks of 'a', 'b', and 'c' to track consecutive appearances.

  2. Calculate the total number of iterations, which equals the sum of 'a', 'b', and 'c'.

  3. Loop through each iteration to build the string:

    • Choose 'a' if 'a' has the highest count among the remaining letters and its streak is less than 2, or if a reduction is needed to prevent a streak of 3 in 'b' or 'c'.
    • Choose 'b' if 'b' has the highest count among the remaining letters and its streak is less than 2, or if a reduction is needed to prevent a streak of 3 in 'a' or 'c'.
    • Choose 'c' similarly based on the remaining count and current streaks of 'a' and 'b'.
    • After appending a character, update the relevant streaks and reset others to zero.
  4. The function finally joins the list into a string which represents the longest happy string without three consecutive similar characters.

This approach ensures the most balanced usage of 'a's, 'b's, and 'c's based on their provided counts while adhering to the conditions of the problem prompt, resulting in an efficient solution to generate the desired string.

Comments

No comments yet.