A URL shortener typically requires two main operations: encoding a long URL into a short one and decoding the short URL back to the original.
Encode and Decode TinyURL LeetCode
Lengthy URLs can be quite a hassle, as they’re typically difficult to remember. Their cluttered look is unorganized, which can adversely affect a user’s perception of the website. URL shortener algorithm solves this issue by encoding these longer URLs into shorter ones. TinyURL is the most popular service for this purpose.
Key takeaways:
TinyURL is a URL shortening service that converts long URLs into shorter, more manageable links.
The TinyURL LeetCode challenge involves creating functions to encode and decode URLs efficiently to ensure unique and reversible mappings.
Using a unique identifier for each original URL is crucial for accurate decoding.
Optimal algorithms for URL encoding and decoding utilize data structures like hash maps for quick insertions and lookups.
The time complexity for URL encoding and decoding is typically
, making it efficient for real-time applications.
What is TinyURL?
TinyURL employs a unique approach to generating shortened links. Instead of following the traditional DNS resolution process, it creates distinct URL identifiers through hashing. When a user clicks on a TinyURL, they are redirected to the original content stored in TinyURL’s database. This method allows for the creation of user-friendly links while keeping the DNS process unchanged.
Note: The conventional URLs are translated to the IP address through the DNS on request of the browser, but tiny URLs work differently. It follows the redirection approach instead of following the DNS process. When a user clicks on the tiny URL, it is redirected to the real link saved in the TinyURL database. This way, TinyURLs generate short and user-friendly links, keeping the DNS process unchanged.
Problem statement
This problem is related to encode and decode URLs and consists of the following two parts:
Encoding a lengthy URL into a unique, shortened one.
Decoding the shortened URL back into its original form.
Note: In TinyURL’s case, the base URL is
https://tinyurl.com/, and the encoded characters are appended. We'll also use thehashliblibrary for our hashing purposes.
The diagram below illustrates the URL encoding and decoding.
Knowledge test
Test your understanding of the problem statement below:
What is occurring in the following conversion?
https://tinyurl.com/94636f2 → https://example.com/another-example-url
Encoding
Decoding
Both encoding and decoding
Intuition
The main idea behind this algorithm is to simplify long and complex URLs into shorter, more manageable links while maintaining a connection to the original URLs. By using a hashing technique, we can create unique identifiers for each original URL, allowing us to store and retrieve them efficiently.
If you’re interested in solving more challenging problems related to encoding and decoding, check out the Decode Ways and Group Anagrams problems.
Algorithm
This algorithm for the TinyURL LeetCode problem to encode and decode URLs consists of the following key components:
Initialization: The class initializes with an empty
hashmapto store the relationship between original URLs and their corresponding encoded versions.encode: This takes an original URL and encodes it using MD5 hashing to generate a unique code ofcharacters. The method constructs a new URL by appending the unique code to the base URL ( self.base). It maps the new URL to the original URL in thehashmapand returns the shortened URL.decode: This takes a shortened URL and checks if it exists in thehashmap. If found, retrieve the original URL from thehashmap. If not found, returns a message indicating that the URL isn’t in the map.
Solution implementation
The coding solution to this problem implementing URL encoding and decoding is provided below:
import hashlibclass TinyURL:def __init__(self):self.hashmap = {} # Dictionary to store short-to-long URL mappingsself.base = "https://tinyurl.com/" # Base URL for shortened linksdef encode(self, original_url):"""Encodes a long URL into a short URL using MD5 hashing."""hashed = hashlib.md5(original_url.encode()) # Generate MD5 hashcode = hashed.hexdigest()[:7] # Get first 7 characters as short codeencoded_url = self.base + code # Create short URLself.hashmap[encoded_url] = original_url # Store mappingreturn encoded_urldef decode(self, encoded_url):"""Decodes a short URL back to its original long URL."""if encoded_url in self.hashmap:return self.hashmap[encoded_url] # Return original URL if foundelse:return "URL isn't present in the map" # Error if not found# Example usageoriginal_url = "https://www.example.com/this-is-an-example-URL"print("Original URL: ", original_url)obj = TinyURL()encoded_url = obj.encode(original_url)print("Encoded URL: ", encoded_url)decoded_url = obj.decode(encoded_url)print("Decoded URL: ", decoded_url)
Code explanation
Line 1: Import the
hashliblibrary.Line 3: Define the
TinyURLclass that contains bothencodeanddecodefunctions.Line 5: Define a dictionary called
hashmap, which stores all shortened URLs with their original forms.Line 6: Define the
baseattribute, which is the prefix all of the encoded URLs will share. In this case, it ishttps://tinyurl.com/.Line 8: Define the
encodefunction that takes the original URL as a parameter.Lines 12–16: Use the
hashlib.md5method to hash the URL. We then obtain a hexadecimal representation of the hash using thehexdigest()method stored in thecodevariable. Here, we use[:7]to obtain a slice of the first seven elements of the hash. The value of this shortened URL is then stored inhashmapalongside its original version.Line 18: Define the
decodefunction, which takes the encoded URL as a parameter.Line 22–25: Check whether the encoded URL is present in the dictionary. If it is, we return its corresponding original URL from the
hashmap. If not, we return a string stating that the value isn’t in our dictionary.Lines 30–38: Create the
TinyUrlclass object, and use it to call theencodeanddecodefunctions to encode and decodeoriginal_url, respectively.
Time complexity
Both encoding and decoding are not influenced by the number of previously encoded or decoded URLs, resulting in a constant time complexity for each operation. Therefore, the time complexity of both encode and decode is
Space complexity
The space complexity of this algorithm is hashmap storing the mappings between shortened and original URLs.
To practice more LeetCode coding problems similar to Encode and Decode TinyURL, check out the best-selling Grokking the Coding Interview Patterns series. One of the standout features of this series is that it’s offered in six different programming languages.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What are the key operations required for a URL shortener?
What data structures are commonly used for implementing a URL shortener?
Can I implement URL shortening in multiple programming languages?
What are some similar problems to encode and decode TinyURL on LeetCode?
How can I effectively use LeetCode to prepare for coding interviews?
Free Resources