Encode and Decode TinyURL

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Design a URL shortening service like TinyURL. Implement two functions:

  • encode(longUrl) — Converts a long URL to a shortened URL.
  • decode(shortUrl) — Converts the shortened URL back to the original long URL.

Your encode and decode functions must be consistent, meaning that calling decode(encode(url)) should always return the original URL.

There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded back to the original URL.

Examples

Example 1:

Input: url = "https://leetcode.com/problems/design-tinyurl"

Output: "https://leetcode.com/problems/design-tinyurl"

Explanation: decode(encode(url)) should return the original URL.

Example 2:

Input: url = "https://example.com"

Output: "https://example.com"

Explanation: The encode function creates a short URL, and decode restores it.

Constraints

  • 1 <= url.length <= 10^4
  • url is guaranteed to be a valid URL
  • You may assume that encode will not be called with the same URL twice
Source: Hash Maps pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle