707603. License Key Formatting

Easy

Here is the detailed Markdown blog post for the "License Key Formatting" problem:

License Key Formatting

Slug: license-key-formatting Difficulty: Easy Id: 707603 Topic Tags: Strings, Data Structures Company Tags: Google

Summary

Given a string of characters representing a license key, and an array of strings representing the valid characters to be used in the formatted key. The task is to format the given license key by replacing each sequence of k consecutive repeated characters with the character followed by the asterisk (). For example, if the input is "AAABBBCCD" and k = 3, then the output will be "ABCD".

Detailed Explanation

To solve this problem, we can iterate over the given license key and check for each sequence of repeated characters. If the length of the sequence is equal to or greater than k, then replace it with the character followed by the asterisk (*). We use a variable count to keep track of the consecutive repeated characters.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty string result to store the formatted license key.
  2. Iterate over each character in the given license key.
  3. For each character, check if it is equal to the previous character. If not, reset the count to 1.
  4. Increment the count for consecutive repeated characters.
  5. If the length of the sequence (count) is equal to or greater than k, then append the character followed by the asterisk (*) to the result string and reset the count to 1.
  6. If the length of the sequence (count) is less than k, then simply append the character to the result string.
  7. After processing all characters in the license key, return the formatted result.

Time complexity: O(n), where n is the length of the given license key. Space complexity: O(1), as we only use a constant amount of space to store the result and variables.

Optimized Solutions

Java

View on GeeksforGeeks
public String licenseKeyFormatting(String s, int k) {
    StringBuilder sb = new StringBuilder();
    int count = 0;
    for (char c : s.toCharArray()) {
        if (c == '-') continue;
        if (count >= k) {
            sb.append('*');
            count = 1;
        } else {
            sb.append(c);
            count++;
        }
    }
    return sb.toString();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.