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]]
c = Codec()
u = "https://leetcode.com/problems/design-tinyurl"
assert c.decode(c.encode(u)) == u and c.encode(u) == c.encode(u)
for u in ("https://example.com/a?b=c#d", "x"):
assert c.decode(c.encode(u)) == u
class Codec {
private static final String ALPHA = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final Map<String, String> longToShort = new HashMap<>(), shortToLong = new HashMap<>();
public String encode(String longUrl) {
String code = longToShort.get(longUrl);
if (code == null) {
long n = shortToLong.size() + 1;
StringBuilder sb = new StringBuilder();
do { sb.append(ALPHA.charAt((int) (n % 62))); n /= 62; } while (n > 0);
code = sb.reverse().toString();
longToShort.put(longUrl, code);
shortToLong.put(code, longUrl);
}
return "http://tinyurl.com/" + code;
}
public String decode(String shortUrl) {
return shortToLong.get(shortUrl.substring(shortUrl.lastIndexOf('/') + 1));
}
}
type Codec struct {
longToShort, shortToLong map[string]string
}
func Constructor() Codec {
return Codec{longToShort: map[string]string{}, shortToLong: map[string]string{}}
}
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func base62(n int) string {
s := ""
for {
s = string(alphabet[n%62]) + s
n /= 62
if n == 0 {
return s
}
}
}
// Encodes a URL to a shortened URL.
func (this *Codec) encode(longUrl string) string {
code, ok := this.longToShort[longUrl]
if !ok { // a counter in base 62: short, unique, no collisions
code = base62(len(this.shortToLong) + 1)
this.longToShort[longUrl] = code
this.shortToLong[code] = longUrl
}
return "http://tinyurl.com/" + code
}
// Decodes a shortened URL to its original URL.
func (this *Codec) decode(shortUrl string) string {
return this.shortToLong[shortUrl[strings.LastIndex(shortUrl, "/")+1:]]
}