Leetcode 535: Encode and Decode TinyURL

grid47
grid47
Exploring patterns and algorithms
Sep 14, 2024 7 min read

A URL being encoded into a short link, with each transformation step gently glowing to indicate the encoding process.
Solution to LeetCode 535: Encode and Decode TinyURL Problem

Design a URL shortening system where you can encode a long URL into a shortened URL and decode it back to the original URL. The system should guarantee that the original URL can always be retrieved using the shortened version.
Problem
Approach
Steps
Complexity
Input: The input consists of a valid long URL (string) that needs to be encoded into a shortened version. The input string will contain a valid URL of length between 1 and 10^4 characters.
Example: Input: longUrl = "https://example.com/article/12345"
Constraints:
• 1 <= longUrl.length <= 10^4
• The URL will be a valid string containing a valid URL.
Output: The output should return the encoded shortened URL, and when decoded, it should return the original URL.
Example: Output: "http://tinyurl.com/4e9iAk"
Constraints:
• The returned shortened URL should be valid and unique.
Goal: To design a system that can encode and decode URLs efficiently while ensuring uniqueness of the shortened URLs.
Steps:
• Use a random generation technique to create a unique short code for each long URL.
• Store the mapping between the original URL and the generated short URL in a data structure (e.g., a map).
• Use the short URL to look up and retrieve the corresponding original URL when decoding.
Goal: Ensure that the system handles valid URLs of up to 10^4 characters and produces unique shortened URLs.
Steps:
• The URL string is guaranteed to be a valid URL.
• The length of the URL string will be between 1 and 10^4 characters.
Assumptions:
• The input URL is valid and properly formatted.
• The solution does not need to handle invalid URLs or URLs that exceed the length limits.
Input: Input: longUrl = "https://example.com/article/12345"
Explanation: The long URL "https://example.com/article/12345" is encoded into a shorter version, such as "http://tinyurl.com/4e9iAk", which can be decoded back to the original URL.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus