LeetCode 535: Encode and Decode TinyURL Solution
Master LeetCode problem 535 (Encode and Decode TinyURL), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
535. Encode and Decode TinyURL
Problem Explanation
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:
- Generate a unique key for each long URL (e.g., using a hash function).
- Store the mapping between the original URL and the generated key in a hash map.
- Return the key as the tiny URL.
Decoding:
- Given a tiny URL, extract the key from it.
- 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.
:
Solution Code
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);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 535 (Encode and Decode TinyURL)?
This page provides optimized solutions for LeetCode problem 535 (Encode and Decode TinyURL) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 535 (Encode and Decode TinyURL)?
The time complexity for LeetCode 535 (Encode and Decode TinyURL) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 535 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 535 in Java, C++, or Python.