License Key Formatting - Problem

You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes.

You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character.

Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.

Return the reformatted license key.

Input & Output

Example 1 — Basic Formatting
$ Input: s = "5F3Z-2e-9-w", k = 4
Output: "5F3Z-2E9W"
💡 Note: The string has 8 valid characters: 5F3Z2E9W. With k=4, we get groups of 4: first group has 8%4=0→4 characters "5F3Z", second group has 4 characters "2E9W".
Example 2 — Shorter First Group
$ Input: s = "2-5g-3-J", k = 2
Output: "2-5G-3J"
💡 Note: Valid characters: 25G3J (5 chars). With k=2, first group has 5%2=1 character "2", then groups of 2: "5G" and "3J".
Example 3 — All Dashes
$ Input: s = "---", k = 3
Output: ""
💡 Note: No valid alphanumeric characters remain after removing dashes, so return empty string.

Constraints

  • 1 ≤ s.length ≤ 3 × 104
  • s consists of English letters, digits, and dashes '-'
  • 1 ≤ k ≤ 104

Visualization

Tap to expand
License Key Formatting: Transform Messy Key to Standard FormatInput: "5F3Z-2e-9-w", k=45F3Z-2e-9-w (messy format)Step 1: Remove dashes, convert to uppercase → "5F3Z2E9W"Step 2: 8 characters total, k=4, so groups: 4 + 45F3Z2E9W-5F3Z-2E9W (formatted)
Understanding the Visualization
1
Input
License key with dashes: "5F3Z-2e-9-w", k=4
2
Process
Remove dashes, uppercase letters, group by k
3
Output
Formatted key: "5F3Z-2E9W"
Key Takeaway
🎯 Key Insight: Processing from right to left naturally handles the variable-length first group without complex calculations
Asked in
Google 25 Microsoft 18 Amazon 15
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen