Sponsored
Sponsored
This approach utilizes a hash map (dictionary) where each long URL is stored along with a unique identifier that serves as the short URL.
This method involves two main operations:
Time Complexity: O(1) for both encode
and decode
operations.
Space Complexity: O(n), where n is the number of URLs encoded.
1class Solution {
2 constructor() {
3 this.urlMap = new Map();
4 this.chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
5 }
6
7 encode(longUrl) {
8 let code = '';
9 for (let i = 0; i < 6; i++) {
10 code += this.chars.charAt(Math.floor(Math.random() * this.chars.length));
11 }
12 this.urlMap.set(code, longUrl);
13 return 'http://tinyurl.com/' + code;
14 }
15
16 decode(shortUrl) {
17 const code = shortUrl.split('/').pop();
18 return this.urlMap.get(code) || '';
19 }
20}
In this JavaScript solution, we use a Map
to store the mapping between the short code and original URL. A 6-character random code is generated for encoding. decode
simply fetches the mapped URL using the code extracted from the short URL.
This approach converts a unique identifier into a base62 string, which is used as the short URL.
Using this method involves several steps:
Time Complexity: O(log n) for encoding as base conversion takes logn operations. O(1) for decoding.
Space Complexity: O(n), for storing the mappings.
1class Solution:
2
3
This Python implementation utilizes a counter incremented on each URL encoding, converting it to a base62 string as the short URL. The original URL is fetched using this unique code during decoding.