Encode and Decode TinyURL

medium design hash map string

Problem

Implement encode(long) → short and decode(short) → long for a URL shortener.

Inputencode("https://leetcode.com/problems/design-tinyurl")
Output"http://tinyurl.com/4e9iAk"
Randomize / counter; persist mapping in a hash map.

import random, string
class Codec:
    def __init__(self):
        self.map = {}
        self.base = "http://tinyurl.com/"
    def encode(self, longUrl):
        while True:
            tok = "".join(random.choices(string.ascii_letters + string.digits, k=6))
            if tok not in self.map: break
        self.map[tok] = longUrl
        return self.base + tok
    def decode(self, shortUrl):
        return self.map[shortUrl.split("/")[-1]]
class Codec {
  constructor() { this.map = new Map(); this.base = "http://tinyurl.com/"; }
  encode(longUrl) {
    let tok;
    do { tok = Math.random().toString(36).slice(2, 8); } while (this.map.has(tok));
    this.map.set(tok, longUrl);
    return this.base + tok;
  }
  decode(shortUrl) { return this.map.get(shortUrl.split("/").pop()); }
}
public class Codec {
    Map map = new HashMap<>();
    String base = "http://tinyurl.com/";
    Random rnd = new Random();
    public String encode(String longUrl) {
        String tok;
        do { tok = randTok(); } while (map.containsKey(tok));
        map.put(tok, longUrl);
        return base + tok;
    }
    public String decode(String shortUrl) { return map.get(shortUrl.substring(shortUrl.lastIndexOf('/') + 1)); }
    String randTok() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) sb.append(chars.charAt(rnd.nextInt(chars.length())));
        return sb.toString();
    }
}
class Codec {
    unordered_map mp;
public:
    string encode(string longUrl) {
        string tok;
        const string ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        do { tok.clear(); for (int i = 0; i < 6; i++) tok += ch[rand() % 62]; } while (mp.count(tok));
        mp[tok] = longUrl;
        return "http://tinyurl.com/" + tok;
    }
    string decode(string shortUrl) { return mp[shortUrl.substr(shortUrl.find_last_of('/') + 1)]; }
};
Time: O(1) per op Space: O(n)