License Key Formatting

You are given a license key `s` of letters, digits and dashes, and an integer `k`. Reformat it so every group has exactly `k` characters, except the first group, which may be shorter but must have at least one character. Groups are separated by single dashes and all letters become uppercase. Return the reformatted key.

30:00

License Key Formatting
easy
Free written solution
Topics
Companies

You are given a license key s of letters, digits and dashes, and an integer k. Reformat it so every group has exactly k characters, except the first group, which may be shorter but must have at least one character. Groups are separated by single dashes and all letters become uppercase. Return the reformatted key.

Example 1:
Input: {"s":"5F3Z-2e-9-w","k":4}
Output: 5F3Z-2E9W
Constraints:
  • 1≤s.length≤1051 \leq \text{s.length} \leq 10^5

  • s consists of English letters, digits, and dashes '-'.

  • 1≤k≤1041 \leq k \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"5F3Z-2e-9-w","k":4}

Build the key from the right end, so every group fills up to k = 4 and only the leftmost group can come out short.

s, scanned right to left (k = 4)

5
F
3
Z
-
2
e
-
9
-
w

i (scan)

old dash, skipped

already placed

new key, growing leftward

empty

front group

count = 0 / 4

Variables
VariableValue
i-1
s[i]null
count0
key""
DepthFunction Call
Stack empty
0/14