License Key Formatting — Solution in Python, Java & C++
License Key Formatting solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings.
License Key Formatting is an easy coding problem on strings, asked in Amazon, Google and Capital One interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, Google, Capital One
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given a licence key s made of alphanumeric characters and dashes, and an integer k.
Reformat it so that every group contains exactly k characters, except the first group, which may be shorter but must contain at least one character. Groups are joined by a single dash, and every letter is converted to uppercase.
Example 1
Input: s = "5F3Z-2e-9-w", k = 4
Output: 5F3Z-2E9W
Example 2
Input: s = "2-5g-3-J", k = 2
Output: 2-5G-3J
Example 3
Input: s = "---", k = 3
Output:
Explanation: Nothing but dashes leaves an empty key.
Constraints
1 <= s.length <= 40s consists of English letters, digits and dashes.1 <= k <= 40
Hints for License Key Formatting
Hint 1
First strip every dash and uppercase what remains — the grouping is decided only by that cleaned string.
Hint 2
The first group's size is
len % k, or the fullkwhen the length divides evenly.Hint 3
Building from the right in chunks of
kgives the same answer without the modulo case.
How to solve License Key Formatting
Strip dashes and uppercase first; the grouping depends only on that cleaned string. The first group takes len % k characters (or k if that is zero), the rest take k each.
Approach
- Build
cleanfrom the non-dash characters, uppercased; return""if empty. - Set
first = len(clean) % k or k. - Emit
clean[:first], then successive chunks ofk, joined by-.
Why it works
Every group after the first must have exactly k characters, so the remainder of the length modulo k is forced onto the first group; when the length divides evenly, the first group is a full k.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- An input of only dashes must return an empty string, not
"-". - Building from the right in chunks of
kand reversing avoids the modulo case.
Reference solution
Python
def licenseKeyFormatting(s: str, k: int) -> str:
clean = [ch.upper() for ch in s if ch != "-"]
if not clean:
return ""
first = len(clean) % k or k
groups = ["".join(clean[:first])]
for i in range(first, len(clean), k):
groups.append("".join(clean[i:i + k]))
return "-".join(groups)Java
public static String licenseKeyFormatting(String s, int k) {
StringBuilder clean = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '-') clean.append(Character.toUpperCase(s.charAt(i)));
}
int n = clean.length();
if (n == 0) return "";
int first = n % k == 0 ? k : n % k;
StringBuilder out = new StringBuilder(clean.substring(0, first));
for (int i = first; i < n; i += k) {
out.append('-').append(clean, i, i + k);
}
return out.toString();
}C++
string licenseKeyFormatting(string s, int k) {
string clean = "";
for (char c : s) {
if (c != '-') clean += (char) toupper(c);
}
int n = (int) clean.size();
if (n == 0) return "";
int first = n % k == 0 ? k : n % k;
string out = clean.substr(0, first);
for (int i = first; i < n; i += k) {
out += "-";
out += clean.substr(i, k);
}
return out;
}JavaScript
var licenseKeyFormatting = function(s, k) {
const clean = [];
for (let i = 0; i < s.length; i++) {
if (s[i] !== "-") clean.push(s[i].toUpperCase());
}
if (clean.length === 0) return "";
const first = clean.length % k === 0 ? k : clean.length % k;
const groups = [clean.slice(0, first).join("")];
for (let i = first; i < clean.length; i += k) {
groups.push(clean.slice(i, i + k).join(""));
}
return groups.join("-");
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings