Encode and Decode TinyURL
Problem Summary
(Write in your own words, not copied from LeetCode. This forces comprehension.)
- Write
encode()anddecode()functions to convert a long url to a tiny url and vice versa https://leetcode.com/problems/encode-and-decode-tinyurl/-> any tiny url- any tiny url ->
https://leetcode.com/problems/encode-and-decode-tinyurl/
Approach Taken
(Step-by-step logic or pseudocode before coding.)
- Instead of trying to come up with some crazy algorithm to convert a string into a smaller string we can simply use a counter
- Store counter to longUrl
- Map counter back to longUrl
Main Concepts Used
(Mark the CS concepts or algorithms used.)
Time & Space Complexity
- Time:
→ Reason: Conversion is - Space:
→ Reason: Storing each long url in our map
Code
class Codec:
def __init__(self):
self.urlMap = {}
self.base = 'https://tinyurl.com'
def hash(self, input: str) -> str:
return len(self.urlMap)
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
key = self.hash(longUrl)
tinyUrl = f'{self.base}/{key}'
self.urlMap[tinyUrl] = longUrl
return tinyUrl
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
return self.urlMap[shortUrl]
Common Mistakes / Things I Got Stuck On
- Trying to come up with some crazy algorithm to convert a long string to a shorter string