Medium
Subtopics
design·hash-function·hash-table·string
Companies
adobe·amazon·bloomberg·facebook·google·microsoft·oracle·uberLast updated: Aug 2, 2025
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 Solution class:
Solution() 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. It is guaranteed that the given shortUrl was encoded by the same object.
Input: url ="https://leetcode.com/problems/design-tinyurl"Output: "https://leetcode.com/problems/design-tinyurl"Explanation:
Solution obj =new Solution();string tiny = obj.encode(url);// returns the encoded tiny url.
string ans = obj.decode(tiny);// returns the original url after deconding it.
What if we want fixed length url, then this method can help. So, we do following
Use index to map generated short url to long url
Use revIndex to map long url to short url (We can also use set here, but can help if we need to extend the problem)
We use do while loop to generate 6 digit random string, so that we enter the loop at-least once. We will just generate the short url or key. If it is already present in index, we will try again, till we find a new key which is not yet present in index. This avoids collisions.
Now, we are out loop, we save this generated key or shortUrl to index and reverse mapping to revIndex.