Encode and Decode TinyURL
Hashing
Problem Statement
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.
Example
Example 1:
Input: url = "https://leetcode.com/problems/design-tinyurl"
Output: "http://tinyurl.com/4e9iAk"
Solution (Two Hash Maps)
We can use two hash maps to store the mappings from long URL to short URL and vice-versa. This allows for O(1) time complexity for both encoding and decoding.
Algorithm Steps
- Initialize two hash maps: `encodeMap` and `decodeMap`.
- For `encode`, if the long URL is not in `encodeMap`, generate a new short URL. A simple way is to use a counter.
- Store the mapping in both hash maps.
- For `decode`, simply return the long URL from `decodeMap`.
Long URL
↔
Short URL
Enter a URL and click play to encode.
URL Mappings
Encode and Decode TinyURL Solution