#482
License Key Formatting
EasyStringString ManipulationTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach efficiently formats the license key by iterating through the cleaned string in reverse, building the result directly. This minimizes the number of operations and avoids unnecessary string manipulations.
⚙️
Algorithm
4 steps- 1Step 1: Remove dashes and convert to uppercase.
- 2Step 2: Initialize an empty result string and a counter for characters.
- 3Step 3: Iterate through the cleaned string in reverse, adding characters to the result.
- 4Step 4: Insert dashes every k characters, except for the first group.
solution.py10 lines
1def licenseKeyFormatting(s: str, k: int) -> str:
2 s = s.replace('-', '').upper()
3 result = []
4 count = 0
5 for char in reversed(s):
6 if count > 0 and count % k == 0:
7 result.append('-')
8 result.append(char)
9 count += 1
10 return ''.join(reversed(result))ℹ
Complexity note: This approach runs in O(n) time because we make a single pass through the string and build the result in linear time. The space complexity is O(n) due to the storage of the result string.
- 1Removing dashes and converting to uppercase are essential preprocessing steps.
- 2Iterating from the end allows for easier group formation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.