KatInterview

535. Encode and Decode TinyURL

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of this problem is to design a system that maps a long URL to a short URL and vice versa. The key requirements are:

Solution

Encode and Decode TinyURL in Python

class Codec:
    def __init__(self):
        self.url_to_id = {}
        self.id_to_url = {}
        self.counter = 1
        self.alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        self.base_url = "http://tinyurl.com/"

    def _to_base62(self, n: int) -> str:
        """Converts a decimal number to a base-62 string."""
        if n == 0:
            return self.alphabet[0]
        result = []
        while n > 0:
            result.append(self.alphabet[n % 62])
            n //= 62
        return "".join(result[::-1])

    def _to_base10(self, s: str) -> int:
        """Converts a base-62 string to a decimal number."""
        n = 0
        for char in s:
            n *= 62
            if '0' <= char <= '9':
                n += ord(char) - ord('0')
            elif 'a' <= char <= 'z':
                n += ord(char) - ord('a') + 10
            else:
                n += ord(char) - ord('A') + 36
        return n

    def encode(self, longUrl: str) -> str:
        """Encodes a URL to a shortened URL."""
        # If the URL has not been encoded yet, assign a new ID and store it.
        if longUrl not in self.url_to_id:
            self.url_to_id[longUrl] = self.counter
            self.id_to_url[self.counter] = longUrl
            self.counter += 1
        
        # Convert the ID to a base-62 string and append to the base URL.
        url_id = self.url_to_id[longUrl]
        short_key = self._to_base62(url_id)
        return self.base_url + short_key
        

    def decode(self, shortUrl: str) -> str:
        """Decodes a shortened URL to its original URL."""
        # Extract the short key from the URL.
        short_key = shortUrl[len(self.base_url):]
        # Convert the key back to a decimal ID.
        url_id = self._to_base10(short_key)
        # Look up the ID to find the original long URL.
        return self.id_to_url[url_id]

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

Encode and Decode TinyURL in Java

public class Codec {
    private Map<Long, String> idToUrl = new HashMap<>();
    private Map<String, Long> urlToId = new HashMap<>();
    private long counter = 1L;
    private static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String BASE_URL = "http://tinyurl.com/";

    // Converts a decimal number to a base-62 string.
    private String toBase62(long n) {
        StringBuilder sb = new StringBuilder();
        if (n == 0) {
            return "0";
        }
        while (n > 0) {
            sb.append(ALPHABET.charAt((int)(n % 62)));
            n /= 62;
        }
        return sb.reverse().toString();
    }

    // Converts a base-62 string to a decimal number.
    private long toBase10(String s) {
        long n = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            n = n * 62;
            if (c >= '0' && c <= '9') {
                n += c - '0';
            } else if (c >= 'a' && c <= 'z') {
                n += c - 'a' + 10;
            } else {
                n += c - 'A' + 36;
            }
        }
        return n;
    }

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        // If the URL has not been encoded yet, assign a new ID and store it.
        if (!urlToId.containsKey(longUrl)) {
            urlToId.put(longUrl, counter);
            idToUrl.put(counter, longUrl);
            counter++;
        }
        // Convert the ID to a base-62 string and append to the base URL.
        return BASE_URL + toBase62(urlToId.get(longUrl));
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        // Extract the short key from the URL.
        String shortKey = shortUrl.substring(BASE_URL.length());
        // Convert the key back to a decimal ID.
        long id = toBase10(shortKey);
        // Look up the ID to find the original long URL.
        return idToUrl.get(id);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));

Encode and Decode TinyURL in C++

class Solution {
private:
    std::unordered_map<long long, std::string> idToUrl;
    std::unordered_map<std::string, long long> urlToId;
    long long counter = 1;
    const std::string ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const std::string BASE_URL = "http://tinyurl.com/";

    // Converts a decimal number to a base-62 string.
    std::string toBase62(long long n) {
        if (n == 0) return "0";
        std::string result = "";
        while (n > 0) {
            result += ALPHABET[n % 62];
            n /= 62;
        }
        std::reverse(result.begin(), result.end());
        return result;
    }

    // Converts a base-62 string to a decimal number.
    long long toBase10(std::string s) {
        long long result = 0;
        for (char c : s) {
            result *= 62;
            if (c >= '0' && c <= '9') {
                result += c - '0';
            } else if (c >= 'a' && c <= 'z') {
                result += c - 'a' + 10;
            } else {
                result += c - 'A' + 36;
            }
        }
        return result;
    }

public:

    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        // If the URL has not been encoded yet, assign a new ID and store it.
        if (urlToId.find(longUrl) == urlToId.end()) {
            urlToId[longUrl] = counter;
            idToUrl[counter] = longUrl;
            counter++;
        }
        // Convert the ID to a base-62 string and append to the base URL.
        return BASE_URL + toBase62(urlToId[longUrl]);
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        // Extract the short key from the URL.
        std::string shortKey = shortUrl.substr(BASE_URL.length());
        // Convert the key back to a decimal ID.
        long long id = toBase10(shortKey);
        // Look up the ID to find the original long URL.
        return idToUrl[id];
    }
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));

Encode and Decode TinyURL in TypeScript

const urlToId = new Map<string, number>();
const idToUrl = new Map<number, string>();
let counter = 1;
const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const BASE_URL = "http://tinyurl.com/";

/** Converts a decimal number to a base-62 string. */
function toBase62(n: number): string {
    if (n === 0) {
        return ALPHABET[0];
    }
    let result = '';
    while (n > 0) {
        // Prepend character to avoid reversing the string at the end
        result = ALPHABET[n % 62] + result;
        n = Math.floor(n / 62);
    }
    return result;
}

/** Converts a base-62 string to a decimal number. */
function toBase10(s: string): number {
    let n = 0;
    for (let i = 0; i < s.length; i++) {
        const char = s[i];
        n *= 62;
        if (char >= '0' && char <= '9') {
            n += char.charCodeAt(0) - '0'.charCodeAt(0);
        } else if (char >= 'a' && char <= 'z') {
            n += char.charCodeAt(0) - 'a'.charCodeAt(0) + 10;
        } else {
            n += char.charCodeAt(0) - 'A'.charCodeAt(0) + 36;
        }
    }
    return n;
}

/**
 * Encodes a URL to a shortened URL.
 */
function encode(longUrl: string): string {
	// If the URL has not been encoded yet, assign a new ID and store it.
    if (!urlToId.has(longUrl)) {
        urlToId.set(longUrl, counter);
        idToUrl.set(counter, longUrl);
        counter++;
    }
    // Convert the ID to a base-62 string and append to the base URL.
    const id = urlToId.get(longUrl)!;
    const shortKey = toBase62(id);
    return BASE_URL + shortKey;
};

/**
 * Decodes a shortened URL to its original URL.
 */
function decode(shortUrl: string): string {
	// Extract the short key from the URL.
    const shortKey = shortUrl.substring(BASE_URL.length);
    // Convert the key back to a decimal ID.
    const id = toBase10(shortKey);
    // Look up the ID to find the original long URL.
    return idToUrl.get(id)!;
};

/**
 * Your functions will be called as such:
 * decode(encode(strs));
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.