SDE & MLE Prep

535. Encode and Decode TinyURL

Problem

Design a URL shortener Codec: encode(longUrl) returns a short URL, and decode(shortUrl) returns the original long URL. Any scheme works as long as decoding an encoded URL gives back the original.

Example: decode(encode("https://example.com/some/long/path")) → "https://example.com/some/long/path"

Assign each new long URL an incrementing id, encode the id in base62 ([0-9a-zA-Z]) for a short code; keep both maps so repeated URLs reuse the same code. (See the URL shortener system design article for scaling this.)

Complexity: O(L) per call.

class Codec:
    ALPHA = string.digits + string.ascii_letters

    def __init__(self):
        self.long_to_short, self.short_to_long = {}, {}

    def _base62(self, n):
        s = ""
        while True:
            n, r = divmod(n, 62)
            s = self.ALPHA[r] + s
            if n == 0:
                return s

    def encode(self, longUrl: str) -> str:
        if longUrl not in self.long_to_short:
            code = self._base62(len(self.short_to_long) + 1)
            self.long_to_short[longUrl] = code
            self.short_to_long[code] = longUrl
        return "http://tinyurl.com/" + self.long_to_short[longUrl]

    def decode(self, shortUrl: str) -> str:
        return self.short_to_long[shortUrl.rsplit("/", 1)[1]]