KatInterview

Two-Way Link Mapper: Shorten and Restore URLs

Data Structure DesignAuto-graded · 15 test cases
MediumAuto-gradedData Structure Designhash-mapdesignstrings

Last 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"). Calling encode on 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

ParameterTypeDescription
operationsList[str]Ordered list of operation names, each "encode" or "decode"
argumentsList[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 arguments contains exactly one string.
  • For encode calls: 1 <= len(long_url) <= 2048; long_url consists of printable ASCII characters.
  • For decode calls: the argument may be any string, including strings that were never issued.
  • Numeric identifiers start at 1 and increment by 1 for 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.