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 - Reverse Processing INPUT Original String s: 5 F 3 Z - 2 e - 9 - w Lowercase (to convert) Dashes (to remove) Input Values s = "5F3Z-2e-9-w" k = 4 Cleaned (no dashes): 5F3Z2e9w (len=8) ALGORITHM STEPS 1 Remove Dashes Strip all '-' chars 2 Reverse String Process from end w9e2ZF35 3 Group by k=4 Add dash every 4 chars W9E2 - ZF35 4 Reverse Back Uppercase + reverse W9E2-ZF35 5F3Z-2E9W First group can be shorter: 4 chars | 4 chars = OK FINAL RESULT Reformatted License Key: 5F3Z 4 chars - 2E9W 4 chars Output: "5F3Z-2E9W" Verification [OK] All uppercase [OK] Groups of k=4 [OK] Dashes between groups Before: 5F3Z-2e-9-w After: 5F3Z-2E9W Key Insight: Reverse Processing makes grouping easier: By reversing the cleaned string, we can uniformly add dashes every k characters from the start. After reversing back, the first group naturally becomes the shorter one (if total length isn't divisible by k), satisfying the problem constraint. TutorialsPoint - License Key Formatting | Reverse Processing Approach
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