License Key Formatting
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
Only dashes becomes empty
Single chars
First group can be shorter
Group by 2 from right
Uppercase, grouped by 4 from right
Algorithm Flow
Solution Approach
Remove dashes, convert to uppercase, then insert dashes every k characters from the end.
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
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();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
