Code Logo

Encode and Decode TinyURL

Published at24 Jul 2026
Medium 1 views
Like0

Design a URL shortening service like TinyURL. Implement two functions:encode(longUrl) that returns a unique short URL key, and decode(shortKey) that returns the original long URL. The short key should be a 6-character alphanumeric string. The mapping must be bijective — each long URL maps to exactly one short key, and vice versa.

A hash map is the natural choice here. We use one map to store longUrl → shortKey for encoding, and a second map to store shortKey → longUrl for decoding. When encode is called, check if the URL was already shortened. If so, return the existing key to avoid duplicates. Otherwise, generate a new 6-character key from a character set, store both mappings, and return the key.

The key generation can use a counter or random selection. Using a counter ensures uniqueness but makes keys predictable. Using random characters with a set of 62 characters (a-z, A-Z, 0-9) gives 62^6 ≈ 56 billion possibilities, making collisions extremely unlikely. For simplicity, this solution uses a counter converted to base-62 encoding.

Edge cases include decoding a key that does not exist (return an empty string), encoding the same URL twice (return the same key both times), and handling very long URLs.

Example Input & Output

Example 1
Input
"nonexistent"
Output
""
Explanation

Decoding an unknown key returns empty string.

Example 2
Input
"https://example.com/very/long/url/1"
Output
"a"
Explanation

Same URL returns the same key.

Example 3
Input
"https://example.com/url/3"
Output
"c"
Explanation

Third URL gets key 'c'.

Example 4
Input
"https://example.com/very/long/url/2"
Output
"b"
Explanation

Second URL gets key 'b'.

Example 5
Input
"https://example.com/very/long/url/1"
Output
"a"
Explanation

First URL gets key 'a'.

Algorithm Flow

Recommendation Algorithm Flow for Encode and Decode TinyURL

Solution Approach

Design a URL shortening service. Use two hash maps: one mapping short codes to long URLs, and another mapping long URLs to short codes to avoid duplicates. Generate a random 6-character alphanumeric code for each new long URL. Encode returns the short code, decode returns the original long URL.

var codeToUrl = {}, urlToCode = {}, chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
function encode(longUrl) {
  if (urlToCode[longUrl]) return 'http://tinyurl.com/' + urlToCode[longUrl];
  var code = '';
  for (var i = 0; i < 6; i++) code += chars[Math.floor(Math.random() * 62)];
  codeToUrl[code] = longUrl;
  urlToCode[longUrl] = code;
  return 'http://tinyurl.com/' + code;
}
function decode(shortUrl) {
  var code = shortUrl.replace('http://tinyurl.com/', '');
  return codeToUrl[code];
}

The 6-character code provides 62^6 possible combinations, sufficient for non-malicious use. The urlToCode map ensures the same URL always gets the same short code.

Time complexity is O(1), space complexity is O(n).

Best Answers

java
import java.util.*;
class Solution {
    private Map<String,String> map = new HashMap<>();
    private Map<String,String> rev = new HashMap<>();
    private String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private int id = 0;
    public String encode(String longUrl) {
        if (map.containsKey(longUrl)) return map.get(longUrl);
        id++;
        int n = id;
        StringBuilder key = new StringBuilder();
        while (n > 0) {
            key.insert(0, base.charAt(n % 62));
            n /= 62;
        }
        while (key.length() < 6) key.insert(0, 'a');
        String k = key.toString();
        map.put(longUrl, k);
        rev.put(k, longUrl);
        return k;
    }
    public String decode(String shortKey) {
        return rev.getOrDefault(shortKey, "");
    }
}