Encode and Decode TinyURL - Problem

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

Implement the URLShortener class:

  • URLShortener() Initializes the object of the system.
  • String encode(String longUrl) Returns a tiny URL for the given longUrl.
  • String decode(String shortUrl) Returns the original long URL for the given shortUrl.

Input & Output

Example 1 — Encode URL
$ Input: operation = "encode", url = "https://leetcode.com/problems/design-tinyurl"
Output: "http://tinyurl.com/4e9iAk"
💡 Note: The system generates a short code and returns the tiny URL. The exact code depends on the implementation approach.
Example 2 — Decode URL
$ Input: operation = "decode", url = "http://tinyurl.com/4e9iAk"
Output: "https://leetcode.com/problems/design-tinyurl"
💡 Note: The system looks up the short code and returns the original long URL that was previously encoded.
Example 3 — Encode Same URL Twice
$ Input: operation = "encode", url = "https://google.com"
Output: "http://tinyurl.com/xyz123"
💡 Note: Encoding the same URL multiple times should return the same short URL to avoid duplicates.

Constraints

  • 1 ≤ url.length ≤ 104
  • url is guaranteed to be a valid URL.

Visualization

Tap to expand
Encode and Decode TinyURL INPUT Long URL: https://leetcode.com/ problems/design-tinyurl encode() Hash Map Storage Key Value "4e9iAk" --> long URL "..." --> ... operation = "encode" url = "https://leetcode..." ALGORITHM STEPS 1 Generate Random Code Create 6-char alphanumeric "4e9iAk" 2 Store in HashMap map[code] = originalURL map["4e9iAk"] = longURL 3 Build Short URL Prefix + random code "http://tinyurl.com/" + "4e9iAk" 4 Decode: Lookup Extract code, query map return map["4e9iAk"] FINAL RESULT Encoded URL: http://tinyurl.com/4e9iAk encode/decode Decoded URL: https://leetcode.com/ problems/design-tinyurl Output: "http://tinyurl.com/ 4e9iAk" OK - Reversible! Key Insight: Use a HashMap to store the mapping between random codes and original URLs. The random 6-character code provides uniqueness (62^6 = 56 billion combinations). Encode generates code, decode looks it up. TutorialsPoint - Encode and Decode TinyURL | Random Code with Hash Map
Asked in
Amazon 45 Microsoft 38 Google 35 Facebook 32
52.0K Views
High Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen