License Key Formatting
Problem
Reformat a license key: uppercase letters, then groups of size k separated by '-' (the first group may be shorter).
S = "5F3Z-2e-9-w", k = 4"5F3Z-2E9W"def license_key_formatting(s, k):
cleaned = s.replace("-", "").upper()
n = len(cleaned)
head = n % k or k
if n == 0: return ""
parts = [cleaned[:head]] if head != k or n < k else [cleaned[:k]] if n == k else [cleaned[:head]]
parts = [cleaned[:head]]
i = head
while i < n:
parts.append(cleaned[i:i+k]); i += k
return "-".join(p for p in parts if p)
function licenseKeyFormatting(s, k) {
const c = s.replace(/-/g, "").toUpperCase();
if (!c.length) return "";
const head = c.length % k || k;
const parts = [c.slice(0, head)];
for (let i = head; i < c.length; i += k) parts.push(c.slice(i, i + k));
return parts.filter(Boolean).join("-");
}
class Solution {
public String licenseKeyFormatting(String s, int k) {
String c = s.replace("-", "").toUpperCase();
if (c.isEmpty()) return "";
int head = c.length() % k;
StringBuilder sb = new StringBuilder();
if (head > 0) sb.append(c, 0, head);
for (int i = head; i < c.length(); i += k) {
if (sb.length() > 0) sb.append('-');
sb.append(c, i, i + k);
}
return sb.toString();
}
}
string licenseKeyFormatting(string s, int k) {
string c;
for (char ch : s) if (ch != '-') c += toupper(ch);
if (c.empty()) return "";
int head = c.size() % k;
string out;
if (head > 0) out = c.substr(0, head);
for (int i = head; i < (int)c.size(); i += k) {
if (!out.empty()) out += '-';
out += c.substr(i, k);
}
return out;
}
Explanation
The hard part of this problem is that the first group can be shorter than the rest, while every group after it must be exactly k characters. The trick is to clean the string first, then figure out how big that first group should be.
Step one: remove all dashes and upper-case everything, giving a clean block c. We never touch the original dashes again — we re-build them from scratch.
Step two: the first group's size is head = n % k (the leftover after splitting into full groups of k). After that first chunk, we just walk forward in steps of k, slicing out each full group and collecting them in parts.
Finally we join all the pieces with - between them. The filter step drops any empty piece so we never get a stray leading dash.
Example: "5F3Z-2e-9-w", k = 4. Cleaned is "5F3Z2E9W" (length 8). Since 8 % 4 == 0 there is no short head, so we take "5F3Z" then "2E9W" and join to "5F3Z-2E9W".