First, I was thinking what if I use Counter from collections? Then suddenly I remember the input and output. Counting the unique char is not the thing but counting the consecutive same character.

My initial logic is: - I'll create a prev var to hold pre character. - count to count current character - and the output var

By looping from 1 to n-1 is my thing.

def compress(fullword):

    l1 = len(fullword)
    if l1<2:
        return fullword

    output = ""
    prev = fullword[0]
    count = 1

    for s in fullword[1:]:
        if s == prev:
            count+=1
        else:
            output += (prev+str(count))
            count = 1
            prev = s
    output += (prev+str(count))
    return output if len(output) < len(fullword) else fullword

Space Complexity: O(len(word)) as looping though all the character. Space Complexity: O(1) no extra variable is used except some constants.

test_cases = [ ("aabcccccaaa", "a2b1c5a3"), ("abcdef", "abcdef"), ("aabb", "aabb"), ("aaa", "a3"), ("a", "a"), ("", ""), ]

Random Note


From python 3.7 dict guarantees that order will be kept as they inserted, and popitem will use LIFO order but we need FIFO type system. so we need OrderedDict which have popIten(last = T/F) for this req. One thing, next(iter(dict)) will return the first key of the dict