Python 1405.py
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
result = ""
maximum = a + b + c
for _ in range(maximum):
recent = result[-2:]
# avoid three identical letters
if recent == "aa":
if b > c:
result += "b"
b -= 1
elif c > 0:
result += "c"
c -= 1
continue
if recent == "bb":
if a > c:
result += "a"
a -= 1
elif c > 0:
result += "c"
c -= 1
continue
if recent == "cc":
if a > b:
result += "a"
a -= 1
elif b > 0:
result += "b"
b -= 1
continue
# pick the letter with the highest allowed count
high = max(a, b, c)
if a == high:
result += "a"
a -= 1
elif b == high:
result += "b"
b -= 1
elif c == high:
result += "c"
c -= 1
return result
Difficulty
and has an acceptance rate of about 66% (300k+ submissions).
Typical patterns to solve this problem:
- Greedy
- Heap (Priority Queue)
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation builds a string that contains at most three distinct characters - a, b, and c - while never allowing three identical characters to appear consecutively. The method receives the maximum allowed occurrences for each character (a, b, c) and returns the longest possible string that respects the “no three in a row” rule.
Core Logic
The algorithm proceeds in a single pass, iterating up to the total number of characters that could be placed (a + b + c). In each iteration it decides which character to append based on the recent suffix of the result and the remaining counts.
Initialization
result = ""
maximum = a + b + c
An empty result string is prepared and the loop bound is set to the sum of the three counters, guaranteeing that the loop will not exceed the total supply of characters.
Detecting a Forbidden Pair
Before choosing a new character, the code inspects the last two characters of the current result:
recent = result[-2:]
If the suffix equals "aa", "bb" or "cc" the algorithm is forced to avoid adding the same character again. This check prevents the creation of three identical consecutive letters.
Forced Substitution When a Pair Exists
When the recent suffix is "aa" the code prefers the character with the larger remaining count among b and c. The same pattern applies for "bb" and "cc":
if recent == "aa":
if b > c:
result += "b"
b -= 1
elif c > 0:
result += "c"
c -= 1
continue
The continue statement skips the remainder of the loop body, ensuring that only the forced substitution is performed for that iteration. The analogous blocks for "bb" and "cc" follow the same structure, swapping the roles of the counters.
Selecting the Most Abundant Character
If no forbidden pair is present, the algorithm chooses the character with the highest remaining count:
high = max(a, b, c)
if a == high:
result += "a"
a -= 1
elif b == high:
result += "b"
b -= 1
elif c == high:
result += "c"
c -= 1
By always picking the most plentiful character, the method maximizes the length of the output while still respecting the three-in-a-row constraint.
Loop Termination
The loop runs exactly maximum times, but the internal logic may exhaust one or more counters before the final iteration. When a counter reaches zero, the corresponding branch will no longer be taken because the condition b > 0 or c > 0 (in the forced substitution blocks) prevents appending a depleted character. Consequently, the loop may effectively become a no-op for the remaining iterations, leaving the result unchanged.
Edge Cases Handled
- Immediate Repetition Prevention - The check of the last two characters guarantees that a third identical character is never appended, covering the case where the input supplies many copies of a single letter.
- Zero Availability - Before appending a forced substitution, the code verifies that the alternative character’s count is greater than zero (
c > 0,b > 0). This prevents attempts to use a character that has already been exhausted. - Tie Between Counts - When two or three counters share the same maximum value, the first matching
ifclause (a == high, thenb == high, thenc == high) determines the choice. This deterministic tie-breaking ensures consistent output without violating the rule. - Empty Result Prefix - At the start of the loop
result[-2:]yields an empty string, which does not match any of the forbidden pairs, allowing the algorithm to freely select the most abundant character for the first two positions.
Performance Optimizations
- Single Pass Construction - The algorithm builds the answer in one linear scan, avoiding any nested loops or repeated scanning of the result string.
- Early Continuation - The use of
continueafter handling a forced substitution short-circuits the remaining decision logic for that iteration, reducing unnecessary comparisons. - Direct Counter Updates - Each character addition immediately decrements its counter, keeping the state current without auxiliary data structures.
- Maximum Pre-computation - Storing
maximum = a + b + cbefore the loop eliminates repeated summations inside the loop header.
These choices keep the runtime tight and the memory footprint minimal, relying only on a few integer variables and the growing result string.
ELI5 - Simplified Explanation
Imagine you have a big box of colorful alphabet blocks. Some are red, some are blue, and some are yellow. The goal is to build a long tower using all the blocks, but there is one special rule. You are not allowed to stack three of the same color right on top of each other because that would make the tower wobbly.
To build the tower, this code looks at the blocks you have left in your hand. It always tries to pick the color that has the most blocks remaining so that you do not run out of one type too early. Every time it adds a block to the tower, it acts like a little helper double-checking the last two blocks.
If the last two blocks are the same color, like two red ones, the code knows it must pick a different color for the next block to keep the tower safe and sturdy. It checks if there are enough blue or yellow blocks to use instead. Once it finds a safe block, it puts it on the tower and sets one of those blocks aside until none are left. The tower grows taller and taller one block at a time while following the rule to never have three identical neighbors.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||
| WalkCCC | C++ | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||
| Progiez | C++ | Python | Java | ||||
| github | black-shadows | C++ | |||||
| charles-wangkai | Java | ||||||
| everthis | JS | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| MacJim | C++ | ||||||
| trung-hn | Python | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ | ||||||
| withaarzoo | C++ | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++ | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| black-shadows | C++, C++ | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| MacJim | C++ | ||||||
| trung-hn | Python | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ | ||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 767: Reorganize String
Solved On The Same Day
- problem 892: Surface Area of 3D Shapes
- problem 1266: Minimum Time Visiting All Points
- problem 2481: Minimum Cuts to Divide a Circle
- problem 1530: Number of Good Leaf Nodes Pairs
- problem 1250: Check If It Is a Good Array
- problem 1610: Maximum Number of Visible Points
- problem 2444: Count Subarrays With Fixed Bounds
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality