Code Logo

License Key Formatting

Published at25 Jul 2026
Medium 0 views
Like0

Given a license key string s and an integer k, format the license key according to the rules: uppercase all letters, remove dashes, then regroup characters into groups of length k from the right. The first group (leftmost) can be shorter than k.

First, strip all dashes and convert to uppercase. Then, from the end, insert a dash every k characters. The first group on the left may have fewer than k characters.

Time complexity is O(n) and space is O(n). The key insight is processing from right to left to handle the potentially shorter first group.

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
Recommendation Algorithm Flow for License Key Formatting

Solution Approach

function solution(s, k) {
  var clean = s.replace(/-/g, '').toUpperCase();
  var result = [];
  for (var i = clean.length; i > 0; i -= k) {
    result.push(clean.substring(Math.max(0, i - k), i));
  }
  return result.reverse().join('-');
}

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();
    }
}