Problem · Design

In-Memory URL Shortener

Learn this problem
MediumRevolut logoRevolutFULLTIMEPHONE SCREEN

Problem statement

Implement the core of an in-memory URL shortener. The service starts empty and processes operations from left to right. The parallel values array supplies each operation's argument.

  • shorten receives a long URL. If the URL has appeared before, return its existing token. Otherwise assign the next positive integer ID, starting at 1, encode it in Base62 using the alphabet 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ, store both directions of the mapping, and return the token.
  • restore receives a token returned by an earlier shorten operation and returns its original long URL.

Return one string result for every operation, in order. Tokens are path components only; do not prepend a domain.

Function

runUrlShortener(operations: String[], values: String[]) → String[]

Examples

Example 1

operations = ["shorten","shorten","restore","shorten","restore"]values = ["https://example.com/articles/alpha","https://example.com/docs/beta","1","https://example.com/articles/alpha","2"]return = ["1","2","https://example.com/articles/alpha","1","https://example.com/docs/beta"]

The first two distinct URLs receive tokens 1 and 2. Restoring token 1 returns the first URL, and shortening that URL again reuses token 1.

Example 2

operations = ["shorten","shorten","shorten","shorten","shorten","shorten","shorten","shorten","shorten","shorten","restore"]values = ["u1","u2","u3","u4","u5","u6","u7","u8","u9","u10","a"]return = ["1","2","3","4","5","6","7","8","9","a","u10"]

The tenth positive ID is encoded as a in the declared Base62 alphabet, and restoring that token returns the tenth URL.

Constraints

  • 1 <= operations.length <= 2 * 10^5
  • values.length == operations.length
  • Each operation is exactly shorten or restore.
  • A long URL is nonempty and has length at most 2000.
  • Every restore token was returned by an earlier shorten operation in the same batch.
drafts saved locally
public String[] runUrlShortener(String[] operations, String[] values) {
    // write your code here
}
operations["shorten","shorten","restore","shorten","restore"]
values["https://example.com/articles/alpha","https://example.com/docs/beta","1","https://example.com/articles/alpha","2"]
expected["1", "2", "https://example.com/articles/alpha", "1", "https://example.com/docs/beta"]
checking account