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 givenlongUrl.String decode(String shortUrl)Returns the original long URL for the givenshortUrl.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code