Problem statement

https://leetcode.com/problems/license-key-formatting/

Solution

Not very clean formulation. Actually, what is asked is to remove all dashes and then traverse string from the end, creating groups with K symbols.

Complexity

Time and space complexity is O(n)

Code

class Solution:
    def licenseKeyFormatting(self, S, K):
        S = S.replace("-", "").upper()
        n = len(S)
        return "-".join([S[:n%K]] + [S[i:i+K] for i in range(n%K, n, K)]).lstrip("-")