We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

License Key Formatting

Number: 482

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given a license key string that includes alphanumeric characters and dashes, reformat it so that each group (separated by dashes) contains exactly k characters—except possibly the first group, which may be shorter but must contain at least one character. In addition, all letters must be transformed to uppercase, and extra dashes should be removed.


Key Insights

  • Remove all dashes from the string and convert every letter to uppercase.
  • Iterate over the cleaned string in reverse to simplify grouping into segments of exactly k characters.
  • Insert dashes after every k characters, taking care of the first group which may be shorter.
  • Reverse the result to return the correctly ordered reformatted license key.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input string since we process each character. Space Complexity: O(n), for storing the intermediate cleaned string and the final result.


Solution

We start by cleaning the string: remove all dashes and convert to uppercase. Then, using a reverse iteration allows us to handle the group segmentation without a special case for the first group. We keep a counter to track when to insert a dash after k characters. Once the reverse iteration is complete, the temporarily built string (in reverse order) is reversed again to form the final formatted license key. The algorithm employs a string or list as a mutable collection and uses basic loop constructs, ensuring both time and space remain linear relative to the input size.


Code Solutions

def licenseKeyFormatting(s: str, k: int) -> str:
    # Remove all dashes and convert to uppercase
    s_clean = s.replace("-", "").upper()
    result = []
    # Iterate backwards over the cleaned string, appending characters and dashes as needed
    for i in range(len(s_clean)):
        # Insert a dash after every group of k characters
        if i > 0 and i % k == 0:
            result.append("-")
        result.append(s_clean[-(i + 1)])
    # Reverse the result to get the correct order and join into a single string
    return "".join(result[::-1])

# Example usage:
# print(licenseKeyFormatting("5F3Z-2e-9-w", 4))  # Output: "5F3Z-2E9W"
← Back to All Questions