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


Substring a String

  • string[start:end:step]
  • from first string[2:6]
  • last char string[-1]
  • last char by index string[-1]
  • from last string[-5:]
  • first to last string[1:-4]