Code Logo

Encode and Decode TinyURL

Published at24 Jul 2026
Medium 0 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
Recommendation Algorithm Flow for Encode and Decode TinyURL

Solution Approach

Maintain two hash maps: long-to-short and short-to-long. For encode, check if already mapped. If not, generate a base-62 key using an auto-increment counter. For decode, look up the key in the short-to-long map.

function solution() {
  var map = {};
  var rev = {};
  var base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  var id = 0;
  return {
    encode: function(url) {
      if (map[url]) return map[url];
      id++;
      var n = id;
      var key = '';
      while (n > 0) { key = base[n % 62] + key; n = Math.floor(n / 62); }
      while (key.length < 6) key = 'a' + key;
      map[url] = key;
      rev[key] = url;
      return key;
    },
    decode: function(key) {
      return rev[key] || '';
    }
  };
}

Time O(1) per operation, Space 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, "");
    }
}