License Key Formatting - Problem
Transform a messy license key into a perfectly formatted one! You're given a license key string containing alphanumeric characters and dashes scattered throughout. Your mission is to reformat this string so that:
  • Each group contains exactly k characters (except the first group which can be shorter)
  • Groups are separated by dashes
  • All letters are converted to uppercase
  • The first group must contain at least one character
For example: "5F3Z-2e-9-w" with k=4 becomes "5F3Z-2E9W" Think of it like reorganizing a messy product serial number into a clean, standardized format that's easy to read and type!

Input & Output

example_1.py โ€” Basic formatting
$ Input: s = "5F3Z-2e-9-w", k = 4
โ€บ Output: "5F3Z-2E9W"
๐Ÿ’ก Note: The string has 8 valid characters. First group gets 4 characters (5F3Z), second group gets the remaining 4 characters (2E9W), separated by a dash.
example_2.py โ€” Shorter first group
$ Input: s = "2-5g-3-J", k = 2
โ€บ Output: "2-5G-3J"
๐Ÿ’ก Note: 5 valid characters total. First group gets 1 character (2), then two groups of 2 characters each (5G, 3J).
example_3.py โ€” No dashes needed
$ Input: s = "2-4A0r7-4k", k = 4
โ€บ Output: "24A0R74K"
๐Ÿ’ก Note: 8 valid characters fit exactly into 2 groups of 4, but since we want first group to be shorter if needed, all 8 characters form one group less than k*2.

Constraints

  • 1 โ‰ค s.length โ‰ค 3 ร— 104
  • s consists of English letters, digits, and dashes '-'
  • 1 โ‰ค k โ‰ค 104
  • First group can be shorter than k but must contain at least one character

Visualization

Tap to expand
License Key Formatting Assembly LineInput5F3Z-2e-9-wClean & Uppercase5F3Z2E9WReverse ProcessGroups of k=4Processing Steps1Remove dashes: 5F3Z2E9W2Work backwards: W9E2-Z3F53Reverse result: 5F3Z-2E9WFinal Output5F3Z-2E9W
Understanding the Visualization
1
Input Cleaning
Remove all dashes and convert letters to uppercase
2
Reverse Grouping
Process from right to left, creating groups of k characters
3
Final Assembly
Reverse the result to get proper order with dashes between groups
Key Takeaway
๐ŸŽฏ Key Insight: Working backwards naturally ensures all groups except the first have exactly k characters, eliminating complex group size calculations!
Asked in
Google 23 Amazon 18 Microsoft 15 Apple 12
31.5K 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