License Key Formatting (LeetCode 482): Solution and Explanation

Easy
String

Drop the old dashes, uppercase every letter, and regroup the characters so each group has exactly k characters except the first, which may be shorter.

Intuition

The original dashes carry no information. Strip them away and you are left with a plain sequence of letters and digits that only needs new dashes.

The rule says every group except the first has exactly k characters. So the group boundaries are fixed by counting from the end of the string, not from the start.

That suggests building the answer from the right. Walk backwards, place characters into the current group, and when the group reaches k characters, put a dash down before the next character.

The leftover characters at the front automatically form the short first group, and because a dash is only added right before a character, the result never starts with a dash. Reverse what you built and you are done.

Approach: Build from the right with a group counter

  1. Start with an empty buffer and count = 0.
  2. Walk i from the last index down to 0 and skip any -.
  3. If count == k, append a dash and reset count to 0.
  4. Append the uppercased character and increase count.
  5. Reverse the buffer and return it.

Step-by-step example

s = "5F3Z-2e-9-w", k = 4
  1. From the right: w becomes W, then skip the dash, place 9, skip, place E (from e), place 2. The group W, 9, E, 2 now has 4 characters.
  2. Skip the dash. The next character Z arrives with count = 4, so a dash goes down first, then Z.
  3. Place 3, F and 5. The second group has 4 characters.
  4. The buffer reads W9E2-Z3F5 backwards. Reversed, it is 5F3Z-2E9W.
  5. Return "5F3Z-2E9W".

Code: Python, Java, C++

1class Solution:
2    def licenseKeyFormatting(self, s: str, k: int) -> str:
3        res = []
4        count = 0
5        for i in range(len(s) - 1, -1, -1):
6            if s[i] == '-':
7                continue
8            if count == k:
9                res.append('-')
10                count = 0
11            res.append(s[i].upper())
12            count += 1
13        return ''.join(reversed(res))
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is visited once, and the final reverse is linear.

Space

O(n)

The output has at most n characters plus one dash per k characters.

Other approaches

Compute the first group size (time O(n), space O(n))

Remove dashes and uppercase to get a string of length m. The first group has m % k characters, or k if that is 0. Then emit groups of k from left to right. No reversal needed.

Insert dashes into a cleaned string (time O(n) with a builder, space O(n))

Clean the string, then insert a dash every k characters counting from the end. Inserting into the middle of a string repeatedly is quadratic in many languages, so build a new string instead.

Common mistakes

  • Grouping from the left. Only the first group may be short, so groups must be counted from the right.
  • Adding a dash after every k characters instead of before the next one. That leaves a leading dash when the character count is a multiple of k.
  • Forgetting that the input can be all dashes. Then the answer is the empty string.
  • Uppercasing digits or dashes in a way that changes them. Only lowercase letters should change.

Frequently asked questions

Why build the key backwards?

The full groups are aligned to the end of the key. Walking from the right lets you fill each group to exactly k without knowing the total length first.

What if s has only dashes?

No character is ever placed, so the buffer stays empty and the answer is the empty string.

Can k be larger than the number of characters?

Yes. Then no dash is ever added and the answer is the cleaned, uppercased string as a single group.