Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

License Key Formatting

C++, Python and TypeScript solutions for License Key Formatting.

The License Key Formatting solutions are below.

Solution files

Python•license-key-formatting/synced-solution.py
def licenseKeyFormatting(S, K):
    cleaned = S.replace('-', '').upper()

    if not cleaned:
        return ""

    result = []
    for i in range(len(cleaned) - 1, -1, -1):
        if len(result) > 0 and len(result) % (K + 1) == K:
            result.append('-')
        result.append(cleaned[i])

    return ''.join(reversed(result))
C++•license-key-formatting/synced-solution.cpp
class Solution {
public:
    string licenseKeyFormatting(string S, int K) {
        string cleaned = "";
        for (char c : S) {
            if (c != '-') {
                cleaned += toupper(c);
            }
        }

        if (cleaned.empty()) return "";

        string result = "";
        int count = 0;
        for (int i = cleaned.length() - 1; i >= 0; i--) {
            if (count == K) {
                result = "-" + result;
                count = 0;
            }
            result = cleaned[i] + result;
            count++;
        }

        return result;
    }
};
TypeScript•license-key-formatting/synced-solution.ts
function licenseKeyFormatting(S: string, K: number): string {
    const cleaned = S.replace(/-/g, '').toUpperCase();

    if (cleaned.length === 0) return "";

    const result: string[] = [];
    for (let i = cleaned.length - 1; i >= 0; i--) {
        if (result.length > 0 && result.length % (K + 1) === K) {
            result.push('-');
        }
        result.push(cleaned[i]);
    }

    return result.reverse().join('');
}