Last Updated: November 15, 2025
TinyURL is a URL shortening service where you enter a URL such as and it returns a short URL such as . 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 decoding it.
url is guranteed to be a valid URL.The basic idea is to use a simple Integer counter to assign a unique ID to each URL. We maintain a mapping of the ID to the original URL using a HashMap. The ID is then converted to a string and appended to our base URL (e.g., http://tinyurl.com/).
encode and decode methods.To improve collision handling and reduce the size of the keys, we use random strings as keys. Base62 encoding is employed for key generation, consisting of alphanumeric characters (a-z, A-Z, 0-9), allowing for a wide range of unique combinations.
encode and decode methods, on average.