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

Difficulty: Easy


Problem Description

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.


Key Insights

  • The input string may contain dashes that need to be removed.
  • Groups of characters should be formed in reverse order to ensure the first group can be shorter than k.
  • All characters should be converted to uppercase.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input string s.
Space Complexity: O(n), for the resulting formatted string.


Solution

To solve the problem, we can follow these steps:

  1. Remove all dashes from the string and convert it to uppercase.
  2. Determine the length of the first group by taking the remainder of the total length when divided by k. This will allow us to handle the first group separately if its length is less than k.
  3. Build the formatted string from the end to the beginning, ensuring to insert dashes appropriately between groups.
  4. Finally, join the groups to form the final output.

The primary data structure used here is a string (or list of characters), and we utilize a loop to construct the groups in reverse order.


Code Solutions

def licenseKeyFormatting(s: str, k: int) -> str:
    # Remove dashes and convert to uppercase
    s = s.replace('-', '').upper()
    
    # Length of the formatted string
    n = len(s)
    
    # Determine the length of the first group
    first_group_length = n % k or k
    
    # Initialize the result list
    result = []
    
    # Add the first group
    result.append(s[:first_group_length])
    
    # Add subsequent groups
    for i in range(first_group_length, n, k):
        result.append(s[i:i + k])
    
    # Join the parts with dashes
    return '-'.join(result)
← Back to All Questions