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:

  1. shorten(long_url: str) -> str

    • If long_url has 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 distinct long_url strings must never share a short link.
  2. expand(short_url: str) -> Optional[str]

    • Return the original long_url string associated with short_url if short_url was previously issued by this instance.
    • Return None for 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).

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", and len(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

  1. 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 with https://short.example/. Calling shorten again on the exact same long_url must return the exact same short link it received the first time without advancing the counter. - expand(short_url: str) -> Optional[str]: returns the original long_url for a short link we previously issued, or None if short_url was 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 becomes https://short.example/1. 2. URLs are matched as exact strings: "https://a.com/x" and "https://a.com/x/" remain distinct entries so expand always restores the caller's string character-for-character.

  2. 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 mismatch
    

    Why 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 into long_url anyway — so expand always needs a dictionary in memory!

    Because Example 1 maps the first URL to https://short.example/1, an incrementing integer ID starting at 1 is the cleanest fit: every new URL gets a brand-new number, so collisions are impossible by construction.

  3. Key idea: maintain two dictionaries for O(1) lookup both ways

    Suppose we only stored short_to_long. Then expand(short_url) would be a fast O(1) dictionary lookup, but shorten(long_url) would have to scan every value in the dictionary (O(n)) just to check whether long_url was 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_url string (including "https://short.example/") as the key in short_to_long: - If someone calls expand("https://other.domain/1"), "https://short.example/", "", or "https://short.example/99", none of those strings is a key in short_to_long, so .get(short_url) returns None with zero fragile string parsing!

  4. Shorten the counter with base-62 encoding

    Writing IDs in base 10 (1, 2, ..., 9999999) works, but encoding the integer in base 62 using 0-9, a-z, and A-Z packs far more IDs into fewer URL-safe characters (62^7 is over 3.5 trillion URLs in just 7 characters!).

    Base-62 works just like converting a number to base 10: repeatedly divide by 62 with divmod(number, 62). The remainder (0..61) picks the rightmost character from ALPHABET, and the quotient becomes the remaining number. When number reaches 0, 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_base62 function, because expand looks up the full short_url string directly in short_to_long!

  5. Implement URLShortener and the operation runner

    In URLShortener: 1. shorten(long_url) checks long_to_short before touching self.next_id. That way, repeated calls with the same long_url return the original short URL without wasting an ID. 2. Only when long_url is brand new do we encode self.next_id, increment self.next_id, and write to both dictionaries together so they can never fall out of sync. 3. url_shortener(operations, arguments) creates a single URLShortener instance 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)
    
  6. Trace Example 2 and Example 3 step by step

    Here is how the dictionaries and next_id evolve 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 returns None without advancing next_id. Once shorten("https://portal.acme.io/login#sso") mints "https://short.example/1", calling expand("https://other.domain/1") still misses short_to_long (None), while expand("https://short.example/1") restores "https://portal.acme.io/login#sso".

  7. 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 per shorten, and O(L) average per expand. Python hashes the input string of length L once in O(L) time and performs O(1) average hash-table lookups/inserts; when a URL is new, encode_base62 divides next_id (<= n) by 62 at most floor(log_62(n)) + 1 times (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 (HOST plus O(log n) characters) are stored once across the two dictionaries; repeated shorten calls on an existing URL allocate zero new entries.

Edge cases

  • Expanding before shortening anything (Example 3): Both dictionaries are empty, so expand returns None without touching next_id.
  • Unissued codes, code 0, or foreign hosts: Because short_to_long is 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 return None.
  • Repeated shorten calls: Handled before incrementing self.next_id, leaving no gaps in issued IDs.
  • Subtle URL differences (trailing slash, uppercase host, http vs https, Unicode/query strings): Stored verbatim without normalization so expand always returns the exact input string.
  • Empty operation list (operations = []): Returns [].

Common mistakes

  • Minting a new ID on every shorten call: Breaks the rule that the same long_url must return the same short_url within one process lifetime.
  • Parsing out the trailing path segment in expand without checking the host: Extracting "1" from short_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 expand is called.

Alternative approaches

  • Random fixed-length tokens: Draw k characters (e.g. k = 7 or 8) using a cryptographically secure random generator (a random source like Python's secrets module designed so attackers cannot predict future outputs from past ones), re-drawing in a while short_url in self.short_to_long: loop to eliminate any collision. This hides link counts and prevents URL enumeration, while still needing long_to_short for repeat stability.
  • Deterministic SHA-256 prefix with open-addressing probe: Take the first k base-62 characters of sha256(long_url). If short_to_long already maps that prefix to a different long_url, re-hash long_url + "#1", "#2", etc., until you either match long_url or 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 on token (for fast expand lookups) and a secondary index on long_url_sha256 (since arbitrary URLs can exceed B-tree key-length limits, verify row.long_url == long_url on hash hits to guard against collisions). Mint IDs from a durable database sequence or pre-allocated ID block rather than resetting next_id = 1 in memory, and place a read-through cache such as Redis in front of expand since 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^14 possibilities; even at 10^8 stored 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_url concurrently can both miss if long_url in self.long_to_short: and assign two different short URLs, or read the same self.next_id and overwrite short_to_long. Inside a single process, guard the check-and-insert critical section in shorten with a threading.Lock; across distributed application servers, rely on a database UNIQUE constraint (INSERT ... ON CONFLICT DO NOTHING followed by SELECT) 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, returning None (mapped to HTTP 404 Not Found) already handles unknown or malformed short links safely. In shorten, validate long_url before consuming an ID: reject empty strings or inputs exceeding a length limit (such as 8 KB), parse via urllib.parse.urlsplit to require scheme in {"http", "https"} plus a non-empty netloc, and block HOST itself to prevent self-referential redirect loops.

Follow-up questions

Similar questions

More Shopify interview questions

All 63 Shopify questions →