You are given three integers x, y, and z.
You have x strings equal to "AA", y strings equal to "BB", and z strings equal to "AB". You want to choose some (possibly all or none) of these strings and concatenate them in some order to form a new string. This new string must not contain "AAA" or "BBB" as a substring.
Return the maximum possible length of the new string.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: x = 2, y = 5, z = 1 Output: 12 Explanation: We can concactenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB". That string has length 12, and we can show that it is impossible to construct a string of longer length.
Example 2:
Input: x = 3, y = 2, z = 2 Output: 14 Explanation: We can concactenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA". That string has length 14, and we can show that it is impossible to construct a string of longer length.
Constraints:
1 <= x, y, z <= 50Problem Overview: You are given counts of three string pieces: "AA", "BB", and "AB". The task is to construct the longest possible string by concatenating these pieces without ever creating the substrings "AAA" or "BBB". Each piece has length 2, so the challenge is deciding the order that avoids three identical consecutive characters.
Approach 1: Greedy Approach Using Balancing (O(1) time, O(1) space)
The key observation is that two "AA" pieces cannot be placed back‑to‑back because "AA" + "AA" creates "AAAA", which contains "AAA". The same restriction applies to "BB". This means "AA" and "BB" must alternate whenever both exist. A greedy strategy pairs them as much as possible using min(x, y). If one type has an extra piece, you can safely add exactly one more at either end, but not two consecutively. The "AB" pieces naturally break runs because they end with B, so they can be appended after "BB" or other "AB" pieces without forming forbidden triples. Counting the maximum valid placements directly yields the final length in constant time. This approach works because the only dangerous patterns are consecutive identical blocks, so balancing the counts eliminates invalid configurations. Greedy reasoning like this frequently appears in greedy and math problems where local constraints determine the global maximum.
Approach 2: Dynamic Tenet with Separation Strategy (O(n) states, O(n) space)
A dynamic programming formulation helps if you want to explicitly model valid transitions. Track the remaining counts of AA, BB, and AB, along with the type of the last block used. The state transition checks whether adding another block would create AAA or BBB. For example, adding AA is disallowed if the previous block already ended with AA, while AB can follow most blocks because it introduces a separating character. The DP explores valid placements and records the maximum achievable length. Each transition reduces one block count, ensuring the state space stays manageable. This method makes the constraints explicit and is useful if the rules become more complex, which is common in dynamic programming interview variants.
Recommended for interviews: The greedy balancing approach is the expected solution. It runs in constant time and relies on a simple observation about alternating AA and BB blocks. Explaining the constraint that identical blocks cannot appear consecutively demonstrates problem understanding, while deriving the direct count formula shows strong optimization skills.
To avoid having 'AAA' or 'BBB', we can construct a string using a greedy approach by alternately using 'AA' and 'BB'. We can intersperse 'AB' between sequences of 'AA' or 'BB' where needed. The goal is to balance the number of 'AA' and 'BB' used and maximize the use of 'AB' to separate them if necessary.
The idea is to:
This C solution calculates the overall length of the new string by summing up both 'AA' and 'BB' string lengths and adding twice the 'AB' strings, considering also if x and y are not equal we can additionally use one more 'AA' or 'BB' because the alternation will accommodate one extra at the ends.
Time Complexity: O(1) since it computes the result directly.
Space Complexity: O(1) since it uses a constant amount of space.
This approach leverages the idea of dynamic choices between construction paths for each set input. By understanding each 'AA', 'BB', and 'AB' unit in constructing long sequences, including alternating and staggered constructs with 'AB' as separators, it aims at optimal spacing and filling.
The strategy stands as:
This approach diversifies between pairing and increment patterns by qualifying separation points as essential blocks, optimizing the total result by multiplicative capacities.
Time Complexity: O(1) because direct calculations are employed.
Space Complexity: O(1) since no extra space allocations are needed.
We observe that the string 'AA' can only be followed by 'BB', and the string 'AB' can be placed at the beginning or end of the string. Therefore:
x < y, we can first alternately place 'BBAABBAA..BB', placing a total of x 'AA' and x+1 'BB', then place the remaining z 'AB', with a total length of (x times 2 + z + 1) times 2;x > y, we can first alternately place 'AABBAABB..AA', placing a total of y 'BB' and y+1 'AA', then place the remaining z 'AB', with a total length of (y times 2 + z + 1) times 2;x = y, we only need to alternately place 'AABB', placing a total of x 'AA' and y 'BB', then place the remaining z 'AB', with a total length of (x + y + z) times 2.The time complexity is O(1), and the space complexity is O(1).
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Greedy Approach Using Balancing | Time Complexity: O(1) since it computes the result directly. |
| Dynamic Tenet with Separation Strategy | Time Complexity: O(1) because direct calculations are employed. |
| Case Discussion | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy Balancing | O(1) | O(1) | Best for interviews and production solutions when counts of blocks are known and constraints allow direct reasoning. |
| Dynamic Tenet with Separation Strategy | O(x + y + z) | O(x + y + z) | Useful when demonstrating correctness through explicit state transitions or when constraints are extended. |
Leetcode BiWeekly contest 107 - Medium - Construct the Longest New String • Prakhar Agrawal • 790 views views
Watch 7 more video solutions →Practice Construct the Longest New String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor