Python 0482.py
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
s = s.replace("-", "").upper()
result = ""
while len(s) > k:
result = s[-k:] + "-" + result
s = s[:-k]
result = s + "-" + result
return result.rstrip("-")
Difficulty
and has an acceptance rate of about 46% (800k+ submissions).
Typical patterns to solve this problem:
- 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 formats a raw license key string according to a grouping rule. It removes existing hyphens, converts all alphabetic characters to uppercase, and then inserts hyphens so that each group (except possibly the first) contains exactly k characters. The algorithm works in a single pass from the end of the cleaned string toward the beginning, building the result incrementally.
Core Steps
Cleaning the Input
The first operation strips all hyphens from the input and normalizes the case.
s = s.replace("-", "").upper()
By performing these two transformations up front, the rest of the logic can assume a contiguous sequence of alphanumeric characters without worrying about mixed case or stray separators.
Building the Formatted String
The algorithm uses a loop that repeatedly extracts the last k characters from the cleaned string and prefixes them to the result, inserting a hyphen between groups.
result = ""
while len(s) > k:
result = s[-k:] + "-" + result
s = s[:-k]
When the remaining portion of s becomes shorter than or equal to k, the loop exits. The final group (which may be shorter than k) is then added to the front of the result.
result = s + "-" + result
A trailing hyphen can appear if the original string was empty after cleaning; the final rstrip call removes any such leftover delimiter.
return result.rstrip("-")
Edge-Case Handling
The code gracefully manages several boundary conditions without additional branching.
When the input consists solely of hyphens, the cleaning step yields an empty string. The loop body never executes because len(s) > k is false, and the subsequent concatenation produces "-" which is then stripped, returning an empty string.
If the length of the cleaned string is exactly a multiple of k, the loop extracts groups until len(s) becomes zero. The final concatenation adds an empty prefix followed by a hyphen, and rstrip("-") removes the trailing hyphen, leaving a correctly hyphen-separated sequence.
When k equals one, the loop extracts single characters, effectively inserting a hyphen between every character. The algorithm still respects the leading group rule because the final concatenation adds the remaining (possibly empty) prefix before the hyphen-separated tail.
If k is larger than the length of the cleaned string, the loop never runs. The single concatenation step places the entire string as the first group, followed by a hyphen and an empty result; the trailing hyphen is removed, yielding the original string in uppercase.
Performance Optimizations
The implementation avoids repeated string concatenations inside the loop by always constructing the new result from a slice of s and the previously built result. Because Python strings are immutable, each concatenation creates a new object, but the number of concatenations is limited to the number of groups, which is at most ceil(len(s)/k). This keeps the overhead proportional to the output size rather than the square of the input length.
By processing the string from the end toward the beginning, the algorithm eliminates the need for a reverse operation after grouping. The final rstrip("-") call is a constant-time operation that cleans up a possible extra delimiter without scanning the entire string.
The use of slicing (s[-k:] and s[:-k]) leverages Python’s efficient substring handling, which runs in time proportional to the slice length. Since each slice extracts at most k characters, the per-iteration cost remains bounded.
Overall, the method achieves linear time behavior relative to the length of the input string while maintaining a low memory footprint: only the cleaned string, the growing result, and a few temporary slices exist simultaneously.
ELI5 - Simplified Explanation
Imagine there is a big pile of mixed-up letters and dashes that need to be organized neatly. The first step is to take out all the extra dashes and turn every small letter into a big uppercase letter so everything matches.
Think of the group of letters as a long line of toy blocks. The goal is to take a small handful of these blocks at a time, specifically a number of blocks equal to the value of k. Starting from the very end of the line, these blocks are pulled off and put into a new pile. A dash is then placed after this little group to keep it separate from the rest. This process repeats over and over, taking a group of blocks and a dash, then another group of blocks and a dash, until there are only a few blocks left.
Once there are not enough blocks left to make a full group, those last remaining blocks are placed at the very front of the pile. Finally, if there is a rogue dash stuck at the very end when everything is put together, it gets brushed away so the final result looks perfectly clean and tidy.
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++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 108: Convert Sorted Array to Binary Search Tree
- problem 72: Edit Distance
- problem 122: Best Time to Buy and Sell Stock II
- problem 167: Two Sum II - Input Array Is Sorted
- problem 453: Minimum Moves to Equal Array Elements
- problem 515: Find Largest Value in Each Tree Row
- problem 535: Encode and Decode TinyURL
- problem 123: Best Time to Buy and Sell Stock III
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