Encode and Decode TinyURL
- 1 min read
- String
- LC-Medium
Solution
Read this: https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/
Solution is pretty simple if we're just using a mapping of numbers to strings
| Time | Space | Explanation |
|---|
O() | O() | |
class Codec:
def __init__(self):
self.counter = 1
self.base_url = 'http://tinyurl.com/'
self.backward_map = {}
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
self.backward_map[self.counter] = longUrl
self.counter += 1
return f'{self.base_url}{self.counter - 1}'
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
counter_val = int(shortUrl.split(self.base_url)[1])
return self.backward_map[counter_val]