Intuition

Simply have a key which is the length of the hashmap to avoid collisions, then store the longUrl.

Complexity

Runtime

Space

, where N is the number of encodings.

Code

class Codec:
    def __init__(self):
        self.hm = {}
 
    def encode(self, longUrl: str) -> str:
        """Encodes a URL to a shortened URL.
        """
        key = str(len(self.hm) + 1)
        self.hm[key] = longUrl
        return key
 
    def decode(self, shortUrl: str) -> str:
        """Decodes a shortened URL to its original URL.
        """
        return self.hm[shortUrl]
 
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

Cards

START Basic Front: Encode And Decode Tinyurl Back: Hashmap as length of hashmap + 1 longUrl END


References