A license key s is made of letters, digits and dashes. The dashes split it into groups, but the groups can have any sizes. You are also given a number k.
Rewrite the key so that every group has exactly k characters, with one dash between groups. Only the first group may be shorter, and it still needs at least one character. All letters must be upper case. Return the new key.
Example 1
Input: s = "a7-Kq-2", k = 2 Output: "A-7K-Q2" Why: 5 characters: groups of 1, 2 and 2
2 more examples and the constraints
Example 2
Input: s = "3b-x9-Q", k = 3 Output: "3B-X9Q" Why: the 2 left over after a group of 3 go first
Example 3
Input: s = "--z-", k = 3 Output: "Z" Why: one character, so one group and no dash
Constraints
- 1 ≤ length of s ≤ 100,000
- Each character of s is a letter, a digit or a dash
- 1 ≤ k ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Clean, then cut from the frontO(n)
- One pass from the endO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 100,000-character key | Verdict |
|---|---|---|---|
| Clean, then cut from the front | O(n) | Passes; one extra copy | |
| One pass from the end | O(n) | Best; no length math |
n = the length of s. Both are linear; the second reads the key once.
Edge cases to test
- Only dashes. "---" has no characters, so the answer is "".
- Length divides by k. "abc" with k = 3 is one full group: "ABC", with no dash in front.
- k larger than the key. "1234" with k = 10 stays one group.
- Digits. Upper-casing a digit leaves it as it is.
Common mistakes
- Cutting groups from the front, so the last group comes out short instead of the first.
- Leaving a dash at the start or end of the answer.
- Keeping the old dashes, or forgetting to upper-case the letters.
How to talk through it
- 1Clarify. Do the old dashes matter? What if nothing is left after removing them?
- 2Find the short group. Only the first may be short, so its length is the leftover, length % k.
- 3Simplify by reading backwards. From the right, every group closed is full, so no length math.
- 4Code the pass. Dash before the character when count reaches k; reverse at the end.
- 5Test out loud. Run "---", an exact fit like "abc" with k = 3, and k = 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?