InterviewHubPRO
Section Overview
Q14

Question 14 of 100

Part 2: Arrays, Strings & Hash Maps (6 - 18)

14%
DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)

String Encode and Decode.

In Simple Words: Encode each string by prepending its length followed by a delimiter (e.g. length#string). On decoding, read until # to parse exact chunk size and slice bytes safely.

  • Time: $O(N)$ | Space: $O(1)$ auxiliary
Multi-Language Solutions
Switch tabs or choose All
class Codec:
    def encode(self, strs: list[str]) -> str:
        res = []
        for s in strs:
            res.append(f"{len(s)}#{s}")
        return "".join(res)

    def decode(self, s: str) -> list[str]:
        res, i = [], 0
        while i < len(s):
            j = s.find("#", i)
            length = int(s[i:j])
            res.append(s[j + 1 : j + 1 + length])
            i = j + 1 + length
        return res