Problem Statement
Encode and Decode TinyURL
You are building a link shortener, the same idea as TinyURL. Someone hands you a long web address, and you give back a short one. Later someone hands you that short address back, and you have to return the exact original long address. So you need two methods: encode(longUrl) turns a long URL into a short one, and decode(shortUrl) turns it back. The trick is simple once you see it. A hash map (a lookup table that connects a key to a value, like a phone book connecting a name to a number) lets you save each pair so you can find the original again instantly. The plan here is to make a short random 6-character code for each long URL and remember which code goes with which URL. With 62 possible characters (lowercase letters, uppercase letters, and digits) in 6 slots, there are 62^6, about 56 billion, possible codes, so you will almost never run out or repeat.
Signals to notice
Brute force first
Not applicable — the challenge is the encoding scheme, not algorithmic complexity.
The key insight
Hash map: generate a unique short code (counter, random, or hash), store the mapping both ways. Encode returns the short URL; decode looks up the original. O(1) per operation.
Trace it on url = "https://leetcode.com/problems/design-tinyurl"
init: urlToCode={}, codeToUrl={}, base="http://tinyurl.com/"
encode(url): url not in urlToCode -> generate code, say "abc123"
while-check: "abc123" not in codeToUrl -> no collision, keep it
store: urlToCode[url]="abc123", codeToUrl["abc123"]=url
encode returns base + "abc123" = "http://tinyurl.com/abc123"
decode("http://tinyurl.com/abc123"): strip base -> code="abc123"
lookup codeToUrl["abc123"] = "https://leetcode.com/problems/design-tinyurl"
returned: original url (decode(encode(url)) == url)What must stay true
The encoding must be bijective — each long URL maps to exactly one short URL and vice versa. A simple incrementing counter or random string works.
Shape of the loop
encode(longUrl): if longUrl in urlToCode: return base + urlToCode[longUrl] code = random 6 chars; while code in codeToUrl: regenerate urlToCode[longUrl] = code; codeToUrl[code] = longUrl return base + code decode(shortUrl): return codeToUrl[ shortUrl without base ]
Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Hash collisions with random codes — either check for collisions or use a counter for guaranteed uniqueness.