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
TinyURL: Encode and Decode SystemLong URL Inputhttps://leetcode.com/problemsENCODEDECODEShort URL Outputhttp://tinyurl.com/4e9iAkBidirectional Mapping StorageHash Map 1: Long URL → Short CodeHash Map 2: Short Code → Long URLBoth operations in O(1) time
Understanding the Visualization
1
Input
Long URL or short URL with operation
2
Process
Generate short code or lookup original URL
3
Output
Short URL or original long URL
Key Takeaway
🎯 Key Insight: Use bidirectional hash maps to achieve O(1) encode and decode operations
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