403. Encode and Decode TinyURL
Design the core of a URL-shortening service. Implement a class Codec with two methods:
encode(longUrl)receives a long URL string and returns a shortened URL string.decode(shortUrl)receives a short URL previously produced byencodeand returns the original long URL, character for character.
You are free to choose any format for the short URL — the only contract is the round trip: for every URL your service has encoded, decode(encode(url)) must return exactly the original string. decode is only ever called on strings that came out of encode.
The judge constructs one Codec, feeds it a sequence of URLs, encodes each one, immediately decodes the result, and prints what came back — so any correct codec passes, whatever key scheme you pick.
Example 1:
Input: codec.decode(codec.encode("https://example.com/library/articles?id=42"))
Output: "https://example.com/library/articles?id=42"
Explanation: encode turns the URL into some short form (for example http://tinyurl.com/1); decode maps that short form back to the exact original, which is what gets printed.
Example 2:
Input: codec.decode(codec.encode(url)) for each of the 2 URLs
Output: each original URL, unchanged
Explanation: Each URL round-trips independently through the same codec instance and comes back unchanged.
Constraints:
- 1 ≤ n ≤ 1000 URLs per run
- 1 ≤ url.length ≤ 200
- URLs contain no whitespace
- decode is only called on values returned by encode from the same Codec instance
Hints:
You cannot "uncompress" a short code back into an arbitrary 200-character URL — a 6-character code simply does not carry that much information. So decode must look the answer up somewhere, not compute it.
Keep a hash map from key → original URL. The simplest key that never collides is a counter: the first URL stored gets key "1", the second "2", and so on. decode strips your fixed prefix and looks the key up.
For a production flavor, draw a random 6-character base-62 key, retry on collision, and keep a second map url → key so encoding the same URL twice reuses one code.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: encode then decode "https://example.com/library/articles?id=42"
Expected output: "https://example.com/library/articles?id=42"