Problem Description
Implement a URL shortening service that converts a long URL to a shortened version and decodes the shortened URL back to the original long URL. There is no restriction on how your algorithm should work, but ensure that a URL can be encoded to a tiny URL and that tiny URL can be reliably decoded to the original URL.
Key Insights
- Use a hash table (or dictionary/map) to store the mapping between the tiny URL code and the original long URL.
- Generate a unique key (e.g., a random 6-character string) to serve as the shortened identifier.
- Handle potential collisions by regenerating the key when necessary.
- Both encoding and decoding operations should be efficient (preferably O(1) time complexity).
Space and Time Complexity
Time Complexity: O(1) for both encode and decode operations on average.
Space Complexity: O(n), where n is the number of URLs stored.
Solution
We use a hash map to maintain the mapping between a randomly generated 6-character code and its corresponding long URL. For the encode function, a random code is generated and then concatenated with a base URL (e.g., http://tinyurl.com/). If the generated code already exists in the hash map (collision), we generate a new one until a unique code is obtained. The decode function simply extracts the code part from the tiny URL and looks up the original URL in the hash map.