Encode and Decode TinyURL — HashMap Bidirectional Mapping
Advertisement
Problem 189 · Encode and Decode TinyURL
Difficulty: Medium · Pattern: Two-Way Map
Design encode() and decode() for a URL shortener.
Solutions
# Python
import random, string
class Codec:
def __init__(self):
self.enc = {} # short -> long
self.dec = {} # long -> short
self.base = "http://tinyurl.com/"
def encode(self, longUrl: str) -> str:
if longUrl not in self.dec:
key = ''.join(random.choices(string.ascii_letters + string.digits, k=6))
while key in self.enc:
key = ''.join(random.choices(string.ascii_letters + string.digits, k=6))
self.enc[key] = longUrl
self.dec[longUrl] = key
return self.base + self.dec[longUrl]
def decode(self, shortUrl: str) -> str:
return self.enc[shortUrl[len(self.base):]]
// Java
public class Codec {
Map<String,String> enc = new HashMap<>(), dec = new HashMap<>();
String base = "http://tinyurl.com/";
public String encode(String longUrl) {
if (!dec.containsKey(longUrl)) {
String key = Integer.toHexString(longUrl.hashCode());
enc.put(key, longUrl); dec.put(longUrl, key);
}
return base + dec.get(longUrl);
}
public String decode(String shortUrl) {
return enc.get(shortUrl.substring(base.length()));
}
}
// C++
class Codec {
unordered_map<string,string> enc, dec;
string base = "http://tinyurl.com/";
public:
string encode(string longUrl) {
if (!dec.count(longUrl)) {
string key = to_string(hash<string>{}(longUrl));
enc[key] = longUrl; dec[longUrl] = key;
}
return base + dec[longUrl];
}
string decode(string shortUrl) {
return enc[shortUrl.substr(base.size())];
}
};
Complexity
- Time: O(1) encode/decode
- Space: O(n) for n URLs
Advertisement