Code Logo

License Key Formatting

Published at25 Jul 2026
Medium 1 views
Like0

Given a license key string s containing alphanumeric characters and dashes, and an integer k, reformat the string so that each group contains exactly k characters except the first group which may be shorter. Groups are separated by dashes, and all letters are converted to uppercase.

For example, "5F3Z-2e-9-w" with k=4 becomes "5F3Z-2E9W". "2-5g-3-J" with k=2 becomes "2-5G-3J" (the first group "2" is shorter than k).

License key formatting is a practical text processing problem. It simulates how software license keys are formatted for readability: grouping characters in fixed-size blocks separated by dashes, with uniform letter casing.

The solution removes all existing dashes and converts to uppercase. Then starting from the end, insert a dash every k characters. Finally return the reformatted string.

Edge cases include an empty string (return ""), k larger than the total character count (return the cleaned string with no dashes), and a string with only dashes (return "").

Example Input & Output

Example 1
Input
"---",3
Output
""
Explanation

Only dashes becomes empty

Example 2
Input
"a-a-a-a",1
Output
"A-A-A-A"
Explanation

Single chars

Example 3
Input
"abc",2
Output
"AB-C"
Explanation

First group can be shorter

Example 4
Input
"2-5g-3-J",2
Output
"2-5G-3J"
Explanation

Group by 2 from right

Example 5
Input
"5F3Z-2e-9-w",4
Output
"5F3Z-2E9W"
Explanation

Uppercase, grouped by 4 from right

Algorithm Flow

Recommendation Algorithm Flow for License Key Formatting

Solution Approach

Remove dashes, convert to uppercase, then insert dashes every k characters from the end.

function formatLicense(s, k)
  cleaned = uppercase(remove(s, "-"))
  result = ""
  count = 0
  for i = length(cleaned) - 1 down to 0
    if count == k then result = "-" + result; count = 0
    result = cleaned[i] + result
    count = count + 1
  return result

First remove all dashes and convert to uppercase. Then iterate backward through the cleaned string. Build the result by prepending each character. After every k characters, prepend a dash. This ensures the first group can be shorter than k while all other groups have exactly k characters.

Time complexity is O(n), space complexity is O(n).

Best Answers

java
class Solution {
    public String solution(String s, int k) {
        String c=s.replace("-","").toUpperCase();
        StringBuilder r=new StringBuilder();int i=c.length();
        while(i>0){int st=Math.max(0,i-k);
            if(r.length()>0)r.insert(0,'-');
            r.insert(0,c.substring(st,i));i-=k;
        }return r.toString();
    }
}