URL Shortener
medium · hashing / encoding, idempotency, expiry
Brief-reported interview attribution (unverified): a standard LLD question at Amazon, Microsoft, Google (the class-level version, not the distributed system)
How to approach an LLD roundDesign the core of a URL shortener as a single class. Short codes are
base62 encodings of a counter starting at 1 (1, 2, …, 9, A, …, Z, a, …,
z, 10, …). Shortening the same URL twice returns the same code. A custom alias
may be requested; a taken alias returns None. A link may have a TTL in seconds;
after it expires, redirect returns None. Time comes from a clock callable
passed to the constructor (default: time.time), so tests can use a fake clock.
class URLShortener:
def __init__(self, clock=None):
# clock: callable returning the current time in seconds
def shorten(self, long_url, custom_alias=None, ttl_seconds=None):
# -> short code (str), or None if the custom alias is taken
def redirect(self, code):
# -> the long URL, or None for an unknown or expired code
def clicks(self, code):
# -> number of successful redirects for the code (0 for an unknown code)
Rules. Base62 alphabet is 0-9A-Za-z in that order. The counter starts at 1,
so the first generated code is "1". An expired code may be reused (shortening
the same URL again after expiry creates a fresh code; a custom alias equal to an
expired code is free again). redirect counts a click only on success. Expiry is
checked as now >= created_at + ttl_seconds.
Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.
Public demo
# Public demo: run after implementing the class API above.
now = [1000.0]
u = URLShortener(clock=lambda: now[0])
print(u.shorten('https://example.com/a'))
print(u.redirect('1'))Starter code
class URLShortener:
def __init__(self, clock=None):
"""clock: callable returning the current time in seconds"""
pass
def shorten(self, long_url, custom_alias=None, ttl_seconds=None):
"""-> short code (str), or None if the custom alias is taken"""
pass
def redirect(self, code):
"""-> the long URL, or None for an unknown or expired code"""
pass
def clicks(self, code):
"""-> number of successful redirects for the code (0 for an unknown code)"""
pass
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python compiler