<- Back

EncodeDecode Strings

All credits to the question go to Neetcode.io. I am merely borrowing from him.

Link - Neetcode 150

Approach 1

For encode:

    Parse string and encode in the format 
    `prefix` + `count` + `original string`

For decode:

    Parse string and decode 
    Check for presence of prefix
        Check for the next digit/set of digits for count
        Get the string

Approach 2

For encode:

    Parse string and encode in the format 
     `count` + `prefix` + `original string`

For decode:

    Parse string linearly with current pointer
        Check for presence of prefix in a loop and keep track of index
        
        Get the count by slicing the string until prefix index and current pointer
        Get the word by slicing string
        repeat

Code

def encode(self, strs: List[str]) -> str:

        final_str = ""
        prefix = "#"
        for word in strs:
            word_len = len(word)
            encoded_word = str(word_len) + prefix + word
            final_str+=encoded_word
        # print(final_str)
        return final_str

    def decode(self, s: str) -> List[str]:
        
        decoded_string = list()
        i = 0 
        j = 0
        while i < len(s):
            while s[j] != "#":
                j+=1
            
            count = int(s[i:j])
            start = j+1
            end = start+count

            word = s[start: end]
            decoded_string.append(word)

            i = end
            j=i
        return decoded_string

This logic fixes our previous issue because now, we know the count of characters already and the # just indicates where the word begins so we can ignore any subsequent #'s and directly obtain our slice.