In-Memory Bidirectional URL Shortener
Medium · Coding & Algorithms · Machine Learning Engineer · Onsite
Problem Statement
Build an in-memory bidirectional link shortener class together with the batch runner function:
def url_shortener(operations: List[str], arguments: List[List[str]]) -> List[Optional[str]]:
Maintain state within a single service instance across all calls in a batch and support two methods:
-
shorten(long_url: str) -> str- If
long_urlhas already been shortened by this instance (matched character-for-character, without normalizing scheme, host casing, trailing slashes, or query parameters), return the exact short link previously assigned to it without advancing the counter. - Otherwise, mint the next sequential integer ID starting from
1(1, 2, 3, ...), format that ID in base 62 using the alphabet"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"(for example,1 -> "1",10 -> "a",61 -> "Z",62 -> "10"), and return"https://short.example/" + token. Two distinctlong_urlstrings must never share a short link.
- If
-
expand(short_url: str) -> Optional[str]- Return the original
long_urlstring associated withshort_urlifshort_urlwas previously issued by this instance. - Return
Nonefor any unknown or malformed input (such as unissued IDs,"https://short.example/0", bare"https://short.example/", empty strings, or URLs belonging to a different domain).
- Return the original
In url_shortener(operations, arguments), instantiate a fresh shortener and process each (operations[i], arguments[i]) pair in order (arguments[i] is [long_url] when operations[i] == "shorten" and [short_url] when operations[i] == "expand"), returning the list of outputs.
Examples
Example 1
Input:
operations = ["shorten", "shorten", "expand", "expand"]
arguments = [
["https://docs.acme.io/guides/setup"],
["https://docs.acme.io/api/v2/users?page=3"],
["https://short.example/2"],
["https://short.example/1"],
]
Output:
[
"https://short.example/1",
"https://short.example/2",
"https://docs.acme.io/api/v2/users?page=3",
"https://docs.acme.io/guides/setup",
]
Explanation:
Two distinct destination URLs receive sequential tokens "1" and "2" under "https://short.example/". Expanding "https://short.example/2" and "https://short.example/1" recovers each exact original string regardless of lookup order.
Example 2
Input:
operations = ["shorten", "shorten", "shorten", "expand"]
arguments = [
["https://blog.acme.io/post/42"],
["https://blog.acme.io/post/42"],
["https://status.acme.io"],
["https://short.example/2"],
]
Output:
[
"https://short.example/1",
"https://short.example/1",
"https://short.example/2",
"https://status.acme.io",
]
Explanation:
Shortening "https://blog.acme.io/post/42" a second time reuses "https://short.example/1" without consuming ID 2, so "https://status.acme.io" receives "https://short.example/2".
Example 3
Input:
operations = ["expand", "shorten", "expand", "expand"]
arguments = [
["https://short.example/1"],
["https://portal.acme.io/login#sso"],
["https://other.domain/1"],
["https://short.example/1"],
]
Output:
[
None,
"https://short.example/1",
None,
"https://portal.acme.io/login#sso",
]
Explanation:
Before any URL is shortened, "https://short.example/1" has not been issued and expands to None. After "https://portal.acme.io/login#sso" is assigned "https://short.example/1", a foreign domain "https://other.domain/1" still returns None, whereas "https://short.example/1" expands to "https://portal.acme.io/login#sso".
Constraints
0 <= len(operations) == len(arguments) <= 6 * 10^4.- Every
operations[i]is either"shorten"or"expand", andlen(arguments[i]) == 1. 0 <= len(arguments[i][0]) <= 2048.- Must run purely in memory using the Python standard library (no external databases or network I/O).
Step-by-step walkthrough
Understand the contract and example behavior
We need an in-memory link shortener with two methods that share state across one instance lifetime: -
shorten(long_url: str) -> str: returns a short link starting withhttps://short.example/. Callingshortenagain on the exact samelong_urlmust return the exact same short link it received the first time without advancing the counter. -expand(short_url: str) -> Optional[str]: returns the originallong_urlfor a short link we previously issued, orNoneifshort_urlwas never issued (as shown in Example 3).Two details from the specification anchor our design: 1. Each new distinct URL receives a sequential base-62 token starting at
1, so the first distinct URL becomeshttps://short.example/1. 2. URLs are matched as exact strings:"https://a.com/x"and"https://a.com/x/"remain distinct entries soexpandalways restores the caller's string character-for-character.Compare the three token schemes
The problem asks us to pick a token strategy and understand collision trade-offs. Here is how the three standard choices compare:
Scheme | Example token | Can two URLs collide? | Needs lookup for repeats? --------------------+---------------+-----------------------+-------------------------- Incrementing ID | 1, 2, ..., 10 | Never (unique counter)| Yes (long_to_short dict) Random token | k9Xp2A1 | Yes (must retry draw) | Yes (long_to_short dict) Truncated URL hash | a7f39c | Yes (hash collision!) | Probe/rehash on mismatchWhy not just take the first 6 characters of
sha256(long_url)without storing a lookup table? Because hash collisions (two different inputs producing the same truncated prefix) are inevitable by the birthday paradox, and hashes cannot be reversed back intolong_urlanyway — soexpandalways needs a dictionary in memory!Because Example 1 maps the first URL to
https://short.example/1, an incrementing integer ID starting at1is the cleanest fit: every new URL gets a brand-new number, so collisions are impossible by construction.Key idea: maintain two dictionaries for O(1) lookup both ways
Suppose we only stored
short_to_long. Thenexpand(short_url)would be a fastO(1)dictionary lookup, butshorten(long_url)would have to scan every value in the dictionary (O(n)) just to check whetherlong_urlwas already shortened!Keeping two synchronized dictionaries makes both directions
O(1)on average:long_to_short[long_url] "https://docs.acme.io/guides/setup" -----------------------> "https://short.example/1" <----------------------- short_to_long[short_url]Notice a subtle benefit of storing the entire
short_urlstring (including"https://short.example/") as the key inshort_to_long: - If someone callsexpand("https://other.domain/1"),"https://short.example/","", or"https://short.example/99", none of those strings is a key inshort_to_long, so.get(short_url)returnsNonewith zero fragile string parsing!Shorten the counter with base-62 encoding
Writing IDs in base 10 (
1, 2, ..., 9999999) works, but encoding the integer in base 62 using0-9,a-z, andA-Zpacks far more IDs into fewer URL-safe characters (62^7is over3.5trillion URLs in just 7 characters!).Base-62 works just like converting a number to base 10: repeatedly divide by
62withdivmod(number, 62). The remainder (0..61) picks the rightmost character fromALPHABET, and the quotient becomes the remaining number. Whennumberreaches0, we reverse the collected characters so the most significant digit comes first:Example: encode_base62(125) 125 divmod 62 -> quotient = 2, remainder = 1 -> ALPHABET[1] = '1' 2 divmod 62 -> quotient = 0, remainder = 2 -> ALPHABET[2] = '2' digits collected right-to-left: ['1', '2'] --> reverse --> "21" Check: 2 * 62 + 1 = 125. Because ALPHABET starts with "0123456789...", IDs 1..9 encode to "1".."9", so ID 1 still produces "https://short.example/1"!HOST = "https://short.example/" # 62 URL-safe characters: 10 digits + 26 lowercase + 26 uppercase. # Starting with '0'..'9' means IDs 1..9 encode to '1'..'9', matching Example 1 ('.../1'). ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def encode_base62(number: int) -> str: """Convert a non-negative integer into base 62 (e.g., 1 -> '1', 61 -> 'Z', 62 -> '10').""" if number == 0: return ALPHABET[0] # Repeatedly divide by 62 to peel off base-62 digits from right (least significant) to left. digits: List[str] = [] while number > 0: number, remainder = divmod(number, 62) digits.append(ALPHABET[remainder]) # Reverse so the most significant digit comes first. digits.reverse() return "".join(digits)Notice we do not even need a
decode_base62function, becauseexpandlooks up the fullshort_urlstring directly inshort_to_long!Implement URLShortener and the operation runner
In
URLShortener: 1.shorten(long_url)checkslong_to_shortbefore touchingself.next_id. That way, repeated calls with the samelong_urlreturn the original short URL without wasting an ID. 2. Only whenlong_urlis brand new do we encodeself.next_id, incrementself.next_id, and write to both dictionaries together so they can never fall out of sync. 3.url_shortener(operations, arguments)creates a singleURLShortenerinstance and dispatches each"shorten"or"expand"call in order.class URLShortener: def __init__(self) -> None: # Next sequential integer ID to hand out when a brand-new long URL arrives. self.next_id: int = 1 # Forward map: long_url -> short_url, e.g. {"https://docs.acme.io/guides/setup": "https://short.example/1"}. self.long_to_short: Dict[str, str] = {} # Reverse map: short_url -> long_url, e.g. {"https://short.example/1": "https://docs.acme.io/guides/setup"}. self.short_to_long: Dict[str, str] = {} def shorten(self, long_url: str) -> str: # Phase 1: Reuse the existing short URL if we have shortened this exact string before. if long_url in self.long_to_short: return self.long_to_short[long_url] # Phase 2: Mint a unique token from `self.next_id` and record both directions atomically. token = encode_base62(self.next_id) self.next_id += 1 short_url = HOST + token self.long_to_short[long_url] = short_url self.short_to_long[short_url] = long_url return short_url def expand(self, short_url: str) -> Optional[str]: # Keying by the full short URL ensures unissued IDs and wrong hosts safely return None. return self.short_to_long.get(short_url)Trace Example 2 and Example 3 step by step
Here is how the dictionaries and
next_idevolve across Example 2:Call | next_id | Action | Return -----------------------------------------+---------+-------------------------------+---------------------------- shorten("https://blog.acme.io/post/42") | 1 -> 2 | Mint "/1", store both maps | "https://short.example/1" shorten("https://blog.acme.io/post/42") | 2 | Hit in long_to_short (no new) | "https://short.example/1" shorten("https://status.acme.io") | 2 -> 3 | Mint "/2", store both maps | "https://short.example/2" expand("https://short.example/2") | 3 | Hit in short_to_long | "https://status.acme.io"And in Example 3,
expand("https://short.example/1")runs first on empty dictionaries and returnsNonewithout advancingnext_id. Onceshorten("https://portal.acme.io/login#sso")mints"https://short.example/1", callingexpand("https://other.domain/1")still missesshort_to_long(None), whileexpand("https://short.example/1")restores"https://portal.acme.io/login#sso".Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple HOST = "https://short.example/" # 62 URL-safe characters: 10 digits + 26 lowercase + 26 uppercase. # Starting with '0'..'9' means IDs 1..9 encode to '1'..'9', matching Example 1 ('.../1'). ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def encode_base62(number: int) -> str: """Convert a non-negative integer into base 62 (e.g., 1 -> '1', 61 -> 'Z', 62 -> '10').""" if number == 0: return ALPHABET[0] # Repeatedly divide by 62 to peel off base-62 digits from right (least significant) to left. digits: List[str] = [] while number > 0: number, remainder = divmod(number, 62) digits.append(ALPHABET[remainder]) # Reverse so the most significant digit comes first. digits.reverse() return "".join(digits) class URLShortener: def __init__(self) -> None: # Next sequential integer ID to hand out when a brand-new long URL arrives. self.next_id: int = 1 # Forward map: long_url -> short_url, e.g. {"https://docs.acme.io/guides/setup": "https://short.example/1"}. self.long_to_short: Dict[str, str] = {} # Reverse map: short_url -> long_url, e.g. {"https://short.example/1": "https://docs.acme.io/guides/setup"}. self.short_to_long: Dict[str, str] = {} def shorten(self, long_url: str) -> str: # Phase 1: Reuse the existing short URL if we have shortened this exact string before. if long_url in self.long_to_short: return self.long_to_short[long_url] # Phase 2: Mint a unique token from `self.next_id` and record both directions atomically. token = encode_base62(self.next_id) self.next_id += 1 short_url = HOST + token self.long_to_short[long_url] = short_url self.short_to_long[short_url] = long_url return short_url def expand(self, short_url: str) -> Optional[str]: # Keying by the full short URL ensures unissued IDs and wrong hosts safely return None. return self.short_to_long.get(short_url) def url_shortener( operations: List[str], arguments: List[List[str]], ) -> List[Optional[str]]: # One URLShortener instance represents one server process lifetime across all calls. shortener = URLShortener() results: List[Optional[str]] = [] for op, args in zip(operations, arguments): if op == "shorten": results.append(shortener.shorten(args[0])) elif op == "expand": results.append(shortener.expand(args[0])) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of a URL shortener like a coat-check counter at a theater. When a guest hands over a coat (long_url) for the first time, the attendant takes the next numbered ticket off a roll (next_id), writes both "Coat -> Ticket #1" and "Ticket #1 -> Coat" in two ledgers, and hands back "Ticket #1". If the same guest asks for their coat's ticket number again, the attendant checks the first ledger and returns "Ticket #1" — a property called idempotency (repeating the exact same request returns the same result without creating duplicate state). When someone later presents "Ticket #1", the attendant checks the second ledger and returns the exact coat.
Why do simpler shortcuts fail? Keeping only a single short -> long dictionary forces shorten to scan every stored entry (O(n) per call) to see whether long_url was already shortened. Truncating a hash of long_url to 6 characters without checking a dictionary fails even worse: two different URLs can suffer a hash collision (two distinct inputs producing the exact same short digest) and silently overwrite or decode to the wrong destination!
Instead, we build an exact bijection (a one-to-one pairing where each stored long URL maps to one unique short URL and vice versa) using two Python dictionaries (long_to_short and short_to_long) plus an incrementing integer counter formatted with base-62 encoding (writing an integer using the 62 URL-safe characters 0-9, a-z, and A-Z instead of just 0-9 so large IDs stay compact).
Walk through Example 2's 4-call trace:
1. shorten("https://blog.acme.io/post/42"): absent from long_to_short; next_id = 1 encodes to "1", stores "https://blog.acme.io/post/42" <-> "https://short.example/1", increments next_id to 2, and returns "https://short.example/1".
2. shorten("https://blog.acme.io/post/42"): hits long_to_short immediately; returns "https://short.example/1" while next_id stays 2.
3. shorten("https://status.acme.io"): absent from long_to_short; next_id = 2 encodes to "2", stores both maps, increments next_id to 3, and returns "https://short.example/2".
4. expand("https://short.example/2"): hits short_to_long and returns "https://status.acme.io" (whereas any unissued link returns None).
Complexity
Let L be the character length of the URL passed to a single call, and n be the number of distinct long URLs shortened so far.
- Time:
O(L + log n)average pershorten, andO(L)average perexpand. Python hashes the input string of lengthLonce inO(L)time and performsO(1)average hash-table lookups/inserts; when a URL is new,encode_base62dividesnext_id(<= n) by62at mostfloor(log_62(n)) + 1times (O(log n), which is at most 7 loop steps for up to 3.5 trillion URLs). Note that Python borrows string object references rather than copying characters on dictionary insert. - Space:
O(n + sum of distinct URL lengths). Each distinct long URL and its short URL (HOSTplusO(log n)characters) are stored once across the two dictionaries; repeatedshortencalls on an existing URL allocate zero new entries.
Edge cases
- Expanding before shortening anything (Example 3): Both dictionaries are empty, so
expandreturnsNonewithout touchingnext_id. - Unissued codes, code
0, or foreign hosts: Becauseshort_to_longis keyed by the exact full short URL we minted,https://short.example/0,https://other.example/1,https://short.example/, and""all cleanly miss the dictionary and returnNone. - Repeated
shortencalls: Handled before incrementingself.next_id, leaving no gaps in issued IDs. - Subtle URL differences (trailing slash, uppercase host,
httpvshttps, Unicode/query strings): Stored verbatim without normalization soexpandalways returns the exact input string. - Empty operation list (
operations = []): Returns[].
Common mistakes
- Minting a new ID on every
shortencall: Breaks the rule that the samelong_urlmust return the sameshort_urlwithin one process lifetime. - Parsing out the trailing path segment in
expandwithout checking the host: Extracting"1"fromshort_url.rsplit("/", 1)[-1]mistakenly expands"https://evil.example/1"to your user's URL. - Using Python's built-in
hash(long_url)to generate tokens: Python randomizes string hash seeds on every process startup (PEP 456) and 64-bit hashes can still collide, especially after truncation. - Normalizing URLs before storing: Lowercasing paths or stripping trailing slashes corrupts case-sensitive paths, query tokens, or signatures when
expandis called.
Alternative approaches
- Random fixed-length tokens: Draw
kcharacters (e.g.k = 7or8) using a cryptographically secure random generator (a random source like Python'ssecretsmodule designed so attackers cannot predict future outputs from past ones), re-drawing in awhile short_url in self.short_to_long:loop to eliminate any collision. This hides link counts and prevents URL enumeration, while still needinglong_to_shortfor repeat stability. - Deterministic SHA-256 prefix with open-addressing probe: Take the first
kbase-62 characters ofsha256(long_url). Ifshort_to_longalready maps that prefix to a differentlong_url, re-hashlong_url + "#1","#2", etc., until you either matchlong_urlor hit an empty slot.
Follow-up questions
- How would you store and index the mappings in a persistent database so links survive process restarts? Persist
(id, token, long_url_sha256, long_url)in a relational or key-value store with a primary key ontoken(for fastexpandlookups) and a secondary index onlong_url_sha256(since arbitrary URLs can exceed B-tree key-length limits, verifyrow.long_url == long_urlon hash hits to guard against collisions). Mint IDs from a durable database sequence or pre-allocated ID block rather than resettingnext_id = 1in memory, and place a read-through cache such as Redis in front ofexpandsince redirects typically outnumber writes by 100:1. - Sequential tokens like /1 and /2 let outsiders enumerate every link—how would you make short codes unpredictable? Draw 8-character tokens using
secrets.choice(ALPHABET)(62^8 ≈ 2.18 * 10^14possibilities; even at10^8stored links, a draw collides with probability< 5 * 10^-7, handled cleanly by a retry loop), or encrypt the 64-bit integer counter with a block cipher / Format-Preserving Encryption (FPE) under a secret server key so consecutive IDs map to pseudorandom tokens with zero collision retries. Avoid simple modular multiplication ((id * prime) % 62^k), because someone who shortens two URLs can subtract their tokens to recover the multiplier. - What concurrency bugs appear if multiple threads call shorten at the same time, and how would you prevent them? Two threads shortening the same brand-new
long_urlconcurrently can both missif long_url in self.long_to_short:and assign two different short URLs, or read the sameself.next_idand overwriteshort_to_long. Inside a single process, guard the check-and-insert critical section inshortenwith athreading.Lock; across distributed application servers, rely on a databaseUNIQUEconstraint (INSERT ... ON CONFLICT DO NOTHINGfollowed bySELECT) so one writer wins and the other returns the winner's short link. - What input validation checks would you add before minting a short link in production? In
expand, returningNone(mapped to HTTP404 Not Found) already handles unknown or malformed short links safely. Inshorten, validatelong_urlbefore consuming an ID: reject empty strings or inputs exceeding a length limit (such as 8 KB), parse viaurllib.parse.urlsplitto requirescheme in {"http", "https"}plus a non-emptynetloc, and blockHOSTitself to prevent self-referential redirect loops.
Follow-up questions
- How would you store and index the mappings in a persistent database so links survive process restarts?
- Sequential tokens like /1 and /2 let outsiders enumerate every link—how would you make short codes unpredictable?
- What concurrency bugs appear if multiple threads call shorten at the same time, and how would you prevent them?
- What input validation checks would you add before minting a short link in production?
Similar questions
- Jaccard Overlap Score Between String Collections
- Set-Based Jaccard Similarity on String Lists
- Storefront Theme Tag Similarity
- Bounded Grid Robot Simulator
- Detect Copied Storefront Themes
- Thread-Safe Fixed-Size LRU Cache
More Shopify interview questions
- Multi-Rover Grid Command Controller Easy
- Grid Rover Navigation Simulator Easy
- Bounded LRU Cache and Gift Exchange Pairing Easy Pro
- Numeric Sequence and Grid Pattern Reasoning Easy Pro
- Rapid Mental Arithmetic and Numerical Bounds Medium Pro
- Measuring Unlicensed Theme Usage and Revenue Impact Medium Pro
- Product Data Scientist Recruiter Screen at Shopify Easy Pro
- Evaluating and Negotiating Values-Intensive Interview Loops Medium Pro
- Automated Order Refund Engine with Idempotent Payouts Medium Pro
- End-to-End Technical Project Walkthrough Easy Pro