KatInterview

482. License Key Formatting

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of the problem is to reformat a license key string. This involves three main tasks:

Solution

License Key Formatting in Python

class Solution:
    def licenseKeyFormatting(self, s: str, k: int) -> str:
        res = []
        count = 0
        
        # Iterate through the string from right to left.
        for char in reversed(s):
            # Ignore dashes.
            if char == '-':
                continue
            
            # If we have added k characters to the current group (from the right),
            # we need to add a dash before the next character.
            # The check 'count > 0' is to avoid adding a dash at the very end of the list.
            if count > 0 and count % k == 0:
                res.append('-')
            
            # Append the uppercase character to our list.
            res.append(char.upper())
            count += 1
            
        # The list 'res' holds the characters in reverse order.
        # Reverse it and join to form the final string.
        return "".join(reversed(res))

License Key Formatting in Java

class Solution {
    public String licenseKeyFormatting(String s, int k) {
        StringBuilder sb = new StringBuilder();
        int count = 0;

        // Iterate through the string from right to left.
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            // Ignore dashes.
            if (c == '-') {
                continue;
            }

            // If we have added k characters to the current group (from the right),
            // we need to add a dash before the next character.
            // The check 'count > 0' is to avoid adding a dash at the very end of the StringBuilder.
            if (count > 0 && count % k == 0) {
                sb.append('-');
            }

            // Append the uppercase character to the StringBuilder.
            sb.append(Character.toUpperCase(c));
            count++;
        }

        // The StringBuilder has the result in reverse order. Reverse it and return as a string.
        return sb.reverse().toString();
    }
}

License Key Formatting in C++

class Solution {
public:
    string licenseKeyFormatting(string s, int k) {
        string res = "";
        int count = 0;
        
        // Iterate through the string from right to left.
        for (int i = s.length() - 1; i >= 0; --i) {
            char c = s[i];
            // Ignore dashes.
            if (c == '-') {
                continue;
            }
            
            // If we have added k characters to the current group (from the right),
            // we need to add a dash before the next character.
            // The check 'count > 0' is to avoid adding a dash at the very end of the reversed string.
            if (count > 0 && count % k == 0) {
                res.push_back('-');
            }
            
            // Add the uppercase character to our result string.
            res.push_back(toupper(c));
            count++;
        }
        
        // The result string is built in reverse order, so we need to reverse it to get the final answer.
        reverse(res.begin(), res.end());
        
        return res;
    }
};

License Key Formatting in TypeScript

function licenseKeyFormatting(s: string, k: number): string {
    const result: string[] = [];
    let count = 0;
    
    // Iterate through the string from right to left.
    for (let i = s.length - 1; i >= 0; i--) {
        const char = s[i];
        // Ignore dashes.
        if (char === '-') {
            continue;
        }
        
        // If we have added k characters to the current group (from the right),
        // we need to add a dash before the next character.
        // The check 'count > 0' is to avoid adding a dash at the very end of the array.
        if (count > 0 && count % k === 0) {
            result.push('-');
        }
        
        // Push the uppercase character to our result array.
        result.push(char.toUpperCase());
        count++;
    }
    
    // The result array is built in reverse order.
    // Reverse it and join to form the final string.
    return result.reverse().join('');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.