Construct the Longest New String - Problem

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.

Input & Output

Example 1 — Balanced Case
$ Input: x = 1, y = 1, z = 1
Output: 6
💡 Note: We have 1 "AA", 1 "BB", 1 "AB". Total A's = 2+1 = 3, Total B's = 2+1 = 3. Since they're equal, we can use all characters: length = 6. One valid arrangement: "AABBAB"
Example 2 — Imbalanced Case
$ Input: x = 2, y = 1, z = 1
Output: 7
💡 Note: We have 2 "AA", 1 "BB", 1 "AB". Total A's = 4+1 = 5, Total B's = 2+1 = 3. Since |5-3| = 2 > 1, we use formula: 2×min(5,3)+1 = 7. One valid arrangement: "AABABAA"
Example 3 — No AB Strings
$ Input: x = 0, y = 1, z = 0
Output: 2
💡 Note: We only have 1 "BB" string. Total A's = 0, Total B's = 2. We can use the entire "BB" string since it doesn't create "BBB". Length = 2.

Constraints

  • 1 ≤ x, y, z ≤ 50

Visualization

Tap to expand
Construct the Longest New String INPUT Available Strings: AA x = 1 BB y = 1 AB z = 1 Constraint No "AAA" substring No "BBB" substring Input: x=1, y=1, z=1 Total strings: 3 ALGORITHM STEPS 1 Balance AA and BB Use min(x,y) pairs 2 Add one extra Add 1 more AA or BB 3 Insert all AB AB never causes AAA/BBB 4 Calculate length Each string = 2 chars Building sequence: AA AB BB Formula: (min(x,y)*2 + 1 + z) * 2 FINAL RESULT Optimal String: A A A B B B "AABABB" Verification: Contains "AAA"? NO - OK Contains "BBB"? NO - OK OUTPUT 6 Key Insight: The greedy approach works because "AB" can be inserted anywhere without creating "AAA" or "BBB". We can use at most min(x,y) pairs of AA and BB alternating, plus one extra AA or BB, and all z copies of AB. Result: (min(x,y)*2 + min(1, |x-y|) + z) * 2 = (1*2 + 1 + 1) * 2 = 6 TutorialsPoint - Construct the Longest New String | Greedy Balancing Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen