In-Memory URL Shortener: Encode and Decode
MicrosoftSoftware Engineer · Technical ScreenLast updated
Design an in-memory URL shortener class supporting fast encoding and decoding between original long URLs and compact short URLs using hash maps.
Problem Statement
Design an in-memory URL shortening service. Your task is to implement a class URLShortener that provides two primary operations:
encode(long_url: str) -> str: Encodes a given long URL to a unique shortened URL starting with the prefix"http://short.ly/"followed by a unique alphanumeric key (e.g.,"http://short.ly/abc12").decode(short_url: str) -> str: Decodes a shortened URL back to its original long URL. If the short URL does not exist or is invalid, return an empty string"".
Requirements
- Consistency: Repeatedly calling
encodeon the samelong_urlmust return the same shortened URL. - Uniqueness: Different long URLs must never resolve to the same shortened URL.
- Efficiency: Both
encodeanddecodeshould run inO(1)average time complexity.
Class Interface
class URLShortener:
def __init__(self):
pass
def encode(self, long_url: str) -> str:
"""Encodes a URL to a shortened URL."""
pass
def decode(self, short_url: str) -> str:
"""Decodes a shortened URL to its original URL."""
pass
Examples
Example 1
shortener = URLShortener()
url1 = "https://www.example.com/articles/system-design-basics"
short1 = shortener.encode(url1)
# Output: e.g., "http://short.ly/1" or "http://short.ly/aBcDeF"
assert shortener.decode(short1) == url1
assert shortener.encode(url1) == short1 # Must return identical short URL
Example 2
shortener = URLShortener()
assert shortener.decode("http://short.ly/nonexistent") == ""
Constraints
1 <= len(long_url) <= 2048long_urlconsists of printable ASCII characters.- Up to
10^5total calls will be made toencodeanddecodecombined. - All generated keys should use alphanumeric characters (
[a-zA-Z0-9]).
Hints
Hint 1
Consider what data structure provides O(1) average time complexity for both inserting and looking up values.
Hint 2
To ensure that encoding the same URL returns the same short URL while preventing collisions, maintain bidirectional mappings (two hash tables).
Hint 3
You can generate unique keys using an incrementing counter converted into Base62 representation, or via random alphanumeric strings with collision handling.
Follow-up questions
- How would you ensure thread safety if multiple worker threads call `encode` and `decode` concurrently?
- If URLs expire after a certain Time-To-Live (TTL), what data structure would you combine with your hash map to evict expired entries efficiently?
- How would your approach adapt if the service needed to be distributed across multiple independent servers without generating duplicate keys?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.