In-Memory URL Shortener: Encode and Decode
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to design a class-based data structure with paired encode and decode operations that maintain a consistent mapping in memory. It tests object-oriented design and hash map usage for achieving constant-time lookups, commonly asked in coding interviews to assess system design fundamentals at the data-structure level.
Constraints
- 1 <= len(long_url) <= 10^4.
- long_url is a valid URL of printable ASCII characters with no spaces.
- At most 10^4 total encode/decode calls, in any order, on the same Codec instance.
- decode is only ever called with a short URL this instance previously produced.
- Every short URL must begin with the prefix 'http://short.url/'.
Examples
Input: ([["encode", "https://example.com/path?id=42&ref=home"], ["decode", "0"]],)
Expected Output: ["OK", "https://example.com/path?id=42&ref=home"]
Explanation: Encode one URL (short URL has the required prefix so 'OK'), then decode encode-op #0 to recover the exact original URL.
Input: ([],)
Expected Output: []
Explanation: No operations: the result list is empty.
Input: ([["encode", "http://a.com"], ["encode", "http://b.com"], ["encode", "http://a.com"], ["decode", "0"], ["decode", "1"], ["decode", "2"]],)
Expected Output: ["OK", "OK", "OK", "http://a.com", "http://b.com", "http://a.com"]
Explanation: Encoding the same URL twice is fine; each short URL must independently round-trip, so decode #0 and #2 both yield 'http://a.com'.
Input: ([["encode", "http://x.io/1"], ["decode", "0"], ["encode", "http://y.io/2"], ["decode", "1"], ["decode", "0"]],)
Expected Output: ["OK", "http://x.io/1", "OK", "http://y.io/2", "http://x.io/1"]
Explanation: Encodes and decodes interleave; a previously encoded short URL can be decoded again later (decode #0 appears twice).
Input: ([["encode", "https://ex.com/p?a=1&b=2#frag"], ["decode", "0"]],)
Expected Output: ["OK", "https://ex.com/p?a=1&b=2#frag"]
Explanation: URLs with query strings and fragments must survive the round-trip unchanged.
Hints
- Keep a counter and a dictionary. On encode, use the current counter value as the key, store key -> long_url, bump the counter, and return 'http://short.url/' + key.
- On decode, strip the fixed 'http://short.url/' prefix to recover the key, then look it up in your dictionary.
- Because keys are generated fresh each time, encoding the same URL twice yields two independent keys that both round-trip correctly — that is allowed by the contract.
- Both encode and decode are O(1) expected: a hash-map insert and a hash-map lookup.