Encode and Decode TinyURL
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
Decoding an unknown key returns empty string.
Same URL returns the same key.
Third URL gets key 'c'.
Second URL gets key 'b'.
First URL gets key 'a'.
Algorithm Flow
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.
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
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, "");
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
