Two-Way Link Mapper: Shorten and Restore URLs
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests ability to design a bidirectional hash map structure that assigns stable short identifiers to long URLs and retrieves originals in O(1).
Problem
Build an in-memory link-shortening service backed by two hash maps.
You will drive the service through a sequence of named operations. Each operation is one of:
"encode"— given one long URL, return a shortened URL. The shortened URL must begin with the fixed prefix"http://short.ly/"followed by a numeric identifier (e.g."http://short.ly/3"). Callingencodeon the same long URL more than once must return the same short URL every time; no new identifier is created."decode"— given one short URL, return the original long URL that was encoded to it. If the short URL was never issued, return an empty string"".
The service is stateful: every call in the sequence operates on the same instance, so short URLs produced by earlier encode calls remain valid for later decode calls.
Inputs
| Parameter | Type | Description |
|---|---|---|
operations | List[str] | Ordered list of operation names, each "encode" or "decode" |
arguments | List[List[str]] | Parallel list; each element is a one-item list holding the argument for the corresponding operation |
Output
A List[str] of results, one per operation, in the same order.
Constraints
1 <= len(operations) == len(arguments) <= 10^5- Each element of
argumentscontains exactly one string. - For
encodecalls:1 <= len(long_url) <= 2048;long_urlconsists of printable ASCII characters. - For
decodecalls: the argument may be any string, including strings that were never issued. - Numeric identifiers start at
1and increment by1for each new distinct long URL. - The same long URL encoded a second time returns the previously issued short URL (counter does not advance).
- A short URL that was never issued returns
"".
Examples
Example 1
Input: link_mapper(['encode', 'decode', 'encode', 'decode'], [['https://www.example.com/articles/system-design-basics'], ['http://short.ly/1'], ['https://www.example.com/articles/system-design-basics'], ['http://short.ly/nonexistent']])
Output: ['http://short.ly/1', 'https://www.example.com/articles/system-design-basics', 'http://short.ly/1', '']
Hints
Hint 1
You need to look up in both directions: long → short for encode, and short → long for decode. Two separate dictionaries cover both cases in O(1).
Hint 2
Before minting a new short URL, check whether the long URL already has one. The length of the long-to-short map tells you the next numeric ID to assign.
Hint 3
For decode, a simple dict.get with a default of "" handles missing or never-issued short URLs cleanly — no prefix validation needed beyond whatever the map contains.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that two dictionary lookups cover everything:
long_to_shortmaps each original URL to its assigned short URL — used byencodeto avoid creating a duplicate entry for a URL that already has one.short_to_longmaps each short URL back to its original — used bydecodefor an instant retrieval.
encode checks long_to_short first. If the URL is already there, it returns the stored value and stops. Otherwise it computes the next numeric ID as len(long_to_short) + 1, builds the short URL, writes to both maps, and returns the new short URL.
decode does a single dict.get on short_to_long. If the key was never written, get returns the default "", which is exactly the required behavior for unknown or never-issued short URLs.
Why this is correct
- Stability: the check at the top of
encodemeans a repeated call never reaches the counter, so the same long URL always produces the same short URL. - Uniqueness: the counter advances only when a genuinely new long URL arrives, so no two distinct long URLs can share a short URL.
- Round-trip: both maps are written together in
encode, sodecode(encode(u)) == ufor every URLu. - Unknown short URLs:
dict.get(key, "")returns""without any extra prefix-checking logic.
Complexity
- Time: both
encodeanddecodeperform a constant number of dictionary operations. Hashing a URL string of length L costs O(L), but this is universally treated as O(1) for hash-map problems given the fixed cap of 2048 characters per URL. - Space: O(N · L) where N is the number of distinct long URLs and L is average URL length. Each URL string is stored twice (once as a key, once as a value), but Python interns the object, so no extra copy is made.
Edge cases
- Encoding the same URL twice: returns the original short URL; the counter does not move.
- Decoding a short URL that was never issued (e.g.
"http://short.ly/nonexistent"): returns"". - Decoding with a completely unrelated string: also returns
""via the samedict.getpath.
from typing import List
class _LinkMapper:
PREFIX = "http://short.ly/"
def __init__(self):
self.long_to_short = {} # long_url -> short_url
self.short_to_long = {} # short_url -> long_url
def encode(self, long_url: str) -> str:
if long_url in self.long_to_short:
return self.long_to_short[long_url]
# Numeric IDs start at 1 and increment with each new distinct URL.
short_url = self.PREFIX + str(len(self.long_to_short) + 1)
self.long_to_short[long_url] = short_url
self.short_to_long[short_url] = long_url
return short_url
def decode(self, short_url: str) -> str:
return self.short_to_long.get(short_url, "")
def link_mapper(operations: List[str], arguments: List[List[str]]) -> List[str]:
service = _LinkMapper()
results = []
for op, args in zip(operations, arguments):
if op == "encode":
results.append(service.encode(args[0]))
elif op == "decode":
results.append(service.decode(args[0]))
else:
raise ValueError(f"Unknown operation: {op}")
return results