Problem · Design
In-Memory URL Shortener
Learn this problemProblem 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.
shortenreceives a long URL. If the URL has appeared before, return its existing token. Otherwise assign the next positive integer ID, starting at1, encode it in Base62 using the alphabet0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ, store both directions of the mapping, and return the token.restorereceives a token returned by an earliershortenoperation 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^5values.length == operations.length- Each operation is exactly
shortenorrestore. - A long URL is nonempty and has length at most
2000. - Every
restoretoken was returned by an earliershortenoperation in the same batch.