535. Encode and Decode TinyURL

Explanation:

To encode and decode a URL to a tiny URL and vice versa, we can use a simple approach by utilizing a hash map to store the mapping between the original URL and its corresponding tiny URL. We can generate a unique key for each long URL and use that key as the tiny URL. When decoding, we can retrieve the original URL by looking up the key in the hash map.

Encoding:

  1. Generate a unique key for each long URL (e.g., using a hash function).
  2. Store the mapping between the original URL and the generated key in a hash map.
  3. Return the key as the tiny URL.

Decoding:

  1. Given a tiny URL, extract the key from it.
  2. Look up the key in the hash map to retrieve the original URL.

Time Complexity:

  • Encoding: O(1) on average
  • Decoding: O(1)

Space Complexity: O(n), where n is the number of unique URLs encoded.

:

import java.util.HashMap;

public class Codec {
    HashMap<String, String> urlMap = new HashMap<>();
    String baseUrl = "http://tinyurl.com/";

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        String key = String.valueOf(longUrl.hashCode());
        urlMap.put(key, longUrl);
        return baseUrl + key;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        String key = shortUrl.replace(baseUrl, "");
        return urlMap.get(key);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.