← 返回 bytedance 的题目列表Design TinyURL (Encode/Decode with collision handling and optional TTL)
类型:online_judge
Problem: Implement a TinyURL encode/decode service
Implement a simplified TinyURL service that encodes a long URL into a short URL and decodes it back.
Requirements
Implement two functions (or equivalent APIs):
encode(longUrl) -> shortUrl
Given a string longUrl, return a short URL shortUrl that can be mapped back to longUrl.
decode(shortUrl) -> longUrl
Given shortUrl, return the original longUrl.
If shortUrl does not exist (or is expired), return an empty string or null (state your choice).
Constraints / Edge Cases
Maintain a mapping between short keys and long URLs (use an in-memory hash map for the interview; optionally explain Redis/DB persistence).
The generated short URL should be reasonably short (typically a fixed-length key).
Handle collisions / duplicate keys: if a generated key already exists but maps to a different long URL, you must resolve it correctly.
Optional: support TTL (expiration).
I/O for Local Testing (one possible format)
Multiple lines of commands:
ENCODE <longUrl>: output the generated shortUrl
DECODE <shortUrl>: output the restored longUrl (or NULL/empty if missing)
Suggested Scale
Up to 1e5 operations
URL length: 1 ~ 2000
Example Test Cases
Basic encode/decode:
ENCODE https://example.com/a/b
DECODE <the short url from previous line>
Encoding the same long URL twice:
Either return the same short URL (idempotent) or different ones, as long as decode works consistently.
Collision handling:
Force the generator to produce the same key for different long URLs; ensure you don’t overwrite incorrectly.
Invalid short URL:
DECODE http://tiny/doesNotExist -> NULL or empty.
TTL (optional):
ENCODE_TTL https://a.com 1
After 2 seconds, DECODE should return NULL/empty.
Example
Input
ENCODE https://example.com/a/b
DECODE http://tiny/xxxxxx
Output
<line1: some short url>
NULL