Problem 482

Abstract / Summary

Format a license key string by inserting hyphens every k characters from the end without changing uppercase letters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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("-")
10 lines | 305 bytes | submitted August 21, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 46% (800k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.96 | σ = 1.35

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
38 links | 25 authors | 10 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

9 solutions   August 21, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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