Tiny URL is an online URL shortening service, where you get a short version of a given URL as a substitute.
Your task is to design encode the original URL “S”, into a tiny URL and decode the previously encoded tiny URL into the original URL.
Example:
S= “https://youtu.be/dQw4w9WgXcQ”, can be encoded to TinyUrl “http://tinyurl.com/abcdef”, then in future queries “http://tinyurl.com/abcdef” can be decoded into “https://youtu.be/dQw4w9WgXcQ”
Note:
The URL given to you for decoding will always be one of the URLs you have already returned after encoding in the past.
The encoded URL should strictly be of the format “http://tinyurl.com/abcdef”, where instead of “abcdef” you can have any alphanumeric code of length 6.
The first line contains an integer, 'K’ denoting the number of queries.
The second line contains a string ‘S’, denoting the URL.
Output Format:
For each test case, return the decoded URL.
Output for each test case should be in a new line.
Note:
You don't print anything, it has already been taken care of. Just implement the given functions.
1 <= K <= 1000
1 <= |S| <= 50
Where |S| is the length of string S.
Time Limit: 1 sec
1
https://youtu.be/dQw4w9WgXcQ
http://tinyurl.com/abcdef
The decoded URL is of the form as described in the problem i.e. “http://tinyurl.com/” followed by an alphanumeric string of length 6.
Multiple answers are possible for encoding, eg: “http://tinyurl.com/sds5xw”, “http://tinyurl.com/8x9qxt”, “http://tinyurl.com/g4e6cd”, etc.
The only constraint is that once you have encoded a URL ‘S’ into some TinyURL, then you should be able to decode that TinyURL in the future.
2
http://codingninjas.com/code/y8fMRhONFF
http://abc.com/code/DNC3bYvUx
http://tinyurl.com/sds5xw
http://tinyurl.com/8x9qxt
Hash the given URL.
Encoding :
Encoding a URL into TinyURL “http://tinyurl.com/abcdef”, where “abcdef” is an alphanumeric string of length 6, can be done using a simple hashing algorithm, and an alphanumeric string generator.
For an alphanumeric string generator, you can just generate a random alphanumeric string of length 6 and check whether this code is previously used or not. If it isn’t then use it to encode the current URL.
Decoding:
After encoding the URL in the encoding function, you are to hash the original string to TinyURL. Which you can use in the decoding function.
Below is the detailed algorithm:
Encode function:
Decode function:
O( K*log( |S| ) ), where K is the number of queries and |S| is the length of the URL.
There are K queries and in each query, and on each query we are doing O( log(|S|) ) work because of hashing.
O( K*|S| ), where K is the number of queries and |S| is the length of the URL.
For each query, we are storing the string in the hash function, thus the space complexity is O( K*|S| ).