AlgoMaster Logo

Encode and Decode TinyURL

Last Updated: November 15, 2025

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. HashMap with Simple Incremental ID

Intuition:

The basic idea is to use a simple Integer counter to assign a unique ID to each URL. We maintain a mapping of the ID to the original URL using a HashMap. The ID is then converted to a string and appended to our base URL (e.g., http://tinyurl.com/).

Steps:

  1. Use a HashMap to store the mapping between an ID and the original URL.
  2. Maintain an Integer counter that increments with each new URL.
  3. To encode a URL, map it with the current counter value and increment the counter.
  4. To decode, simply retrieve the URL from the HashMap using the ID.

Code:

2. HashMap with Random and Base62 Encoding

Intuition:

To improve collision handling and reduce the size of the keys, we use random strings as keys. Base62 encoding is employed for key generation, consisting of alphanumeric characters (a-z, A-Z, 0-9), allowing for a wide range of unique combinations.

Steps:

  1. Use a HashMap to map between encoded keys and URLs.
  2. Generate a unique key for each URL using random strings.
  3. Use Base62 encoding to ensure a consistent string length and avoid collisions.
  4. To encode, generate a key, map it to the URL, and build the tiny URL.
  5. To decode, retrieve the URL directly using the key.

Code: