DEV Community

Cover image for Leetcode 535. Encode and Decode TinyURL [Solution and Discussion]
Shivam Sharma
Shivam Sharma

Posted on

Leetcode 535. Encode and Decode TinyURL [Solution and Discussion]

The question is very good and real-world related, but the test environment for this question in Leetcode is not up to the mark, As even below code is also accepted and it requires no effort.

class Solution {
public:
    string encode(string longUrl) {
        return longUrl;
    }
    string decode(string shortUrl) {
        return shortUrl;
    }
};
Enter fullscreen mode Exit fullscreen mode

That is happening because Leetcode is creating a new instance for each test case hence there is no need to keep past input/output in the code. Also, there are no constraints on the length of a short URL.

But we are here to learn, so ignoring such a bad test environment, we'll be creating a real-world solution. The best thing about this question is the provided hyperlink to the article.

Difficulty: Medium
Jump To:


Problem Statement

Question: https://leetcode.com/problems/encode-and-decode-tinyurl/

Note: This is a companion problem to the System Design problem: Design TinyURL.

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design the encode and decode methods for the TinyURL service. 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 to the original URL.


Explanation

So the problem is simple, you need to create an algorithm, which will convert a long URL to a short URL and the long URL can be achieved back from the short URL. One thing to take care of is that the short URL should always map to a single long URL but vice versa is not mandatory but good to have.


Solution

There are many solutions possible to this problem, the one we are going to use is mentioned in the attached article with the question, which is "Simple Base conversion". In this method, we have a base and the base for the system is the number of distinct characters available in the system. Simplest example for it is a Decimal System which has base=10 (0-9) or a Hexadecimal Number System which has base=16 (0-9,A-D). So first let's see how we convert a decimal number to a hexadecimal number.

  1. Mod a number by Base and use the character present at this mod value.
  2. Divide the original number by base.
  3. Repeat the above steps until the number becomes zero.
  4. Now write the characters found in a reverse manner.

Eg. 1732 => 6C4

Base Number Remainder Read Direction
16 1732 4
16 108 C
16 6 6
16 0

Now again look at the problem we have a-z, A-Z and 0-9 i.e. 62 characters available to use in short URL, so we can see it as a decimal to 62-based system conversion problem. So we'll convert a number to a 62-based string and this string will be our short URL Hash. This hash can be appended to "http://tinyurl.com/" to form a complete short URL.

Wait a minute??? From where this decimal number came into the picture??? Actually, instead of converting a very long string to a short URL, we'll be converting a decimal number to a short URL and we'll bind this short URL to the long URL. Or to save space we can bind directly the decimal number to the long URL. This number is an increasing counter, which will be increased every time by 1 when encode is called.

For a limited number of long URLs, the first method is OK, but when we are going to convert billions then the second method is way better.

For the first method, In the encoding method, we require only decimal to 62-based conversion and a hash map to store pair of <Short URL Hash, Long URL>. Then in the decoding method, we'll just look up the short URL in this hash map and return the long URL.

In the Second method, we'll have a hashmap for the pair of <integer, Long URL> so we require both decimal to 62-based conversion (for encoding) and 62-based to decimal conversion (for decoding)


Implementation

C++ Code:
For method 1:

class Solution {
public:
    int counter=0;
    unordered_map<string,string> dict;

    string encode(string longUrl) {
        char cmap[] = "abcdefghijklmnopqrstuvwxyz\
            ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        int n = (++counter);
        string shortUrl;
        while(n){
            shortUrl.push_back(cmap[n%62]);
            n=n/62;
        }
        reverse(shortUrl.begin(), shortUrl.end());
        dict[shortUrl] = longUrl;
        return shortUrl;
    }

    string decode(string shortUrl) {
        return dict[shortUrl];
    }
};
Enter fullscreen mode Exit fullscreen mode

For method 2:

class Solution {
public:
    int counter=0;
    unordered_map<int,string> dict;

    string encode(string longUrl) {
        char cmap[] = "abcdefghijklmnopqrstuvwxyz\
            ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        int n = (++counter);
        string shortUrl;
        while(n){
            shortUrl.push_back(cmap[n%62]);
            n=n/62;
        }
        reverse(shortUrl.begin(), shortUrl.end());
        dict[counter] = longUrl;
        return shortUrl;
    }

    string decode(string shortUrl) {
        int id = 0; // initialize result
        for (int i=0; i < shortUrl.length(); i++)
        {
            if ('a' <= shortUrl[i] && shortUrl[i] <= 'z')
                id = id*62 + shortUrl[i] - 'a';
            if ('A' <= shortUrl[i] && shortUrl[i] <= 'Z')
                id = id*62 + shortUrl[i] - 'A' + 26;
            if ('0' <= shortUrl[i] && shortUrl[i] <= '9')
                id = id*62 + shortUrl[i] - '0' + 52;
        }
        return dict[id];
    }
};
Enter fullscreen mode Exit fullscreen mode

Runnable C++ code:

Cover Photo by Annie Spratt on Unsplash

We can have a discussion either here or here regarding this question.

Discussion (32)

Collapse
sattamarket profile image
satta matka market

I just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You. satta matka

Collapse
jones009 profile image
abrar aK

First You got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks. library of heaven's path

Collapse
ghoomlullp profile image
fardeen siddiqui

this is our site by the way ghoomly.com

Collapse
jones009 profile image
abrar aK

First You got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks. solo leveling อ่าน

Collapse
jones009 profile image
abrar aK

First You got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks. library of heaven's path

Collapse
samsimth60 profile image
samsimth60

You delivered such an impressive piece to read, 먹튀검증
giving every subject enlightenment for us to gain information. Thanks for sharing such information with us due to which my several concepts have been cleared.

Collapse
samsimth60 profile image
samsimth60 • Edited on

Thanks for picking out the time to discuss this, I feel great about it and love studying more on this topic. It is extremely helpful for me. Thanks for such a valuable help again. 토토커뮤니티

Collapse
thomashenry12312 profile image
thomashenry12312

First You got a great blog .I will be interested in 極速娛樂城 more similar topics. i see you got really very useful topics, i will be always checking your blog thanks. solo leveling

Collapse
jones009 profile image
abrar aK • Edited on

A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work

Collapse
jones009 profile image
abrar aK

Great post full of useful tips! My site is fairly new and I am also having a hard time getting my readers to leave comments. Analytics shows they are coming to the site but I have a feeling “nobody wants to be first”. นิยาย. นิยาย pdf

Collapse
jamesxxxd profile image
MasterX

This topic helped me a lot. thanks for your help I feel like an article like this will disappear a little bit. but i tried to find it come meet your It was absolutely wow. อ่านโดจิน

Collapse
jones009 profile image
abrar aK

First You got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks. กลยุทธ์เด็ด เสพติดรักภรรยาของผม

Collapse
jones009 profile image
abrar aK

Very interesting blog. A lot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definitely interested in this one. Just thought that I would post and let you know rent a car beograd

Collapse
treableanup profile image
Treable

Are you looking for the which is the best company who are provide the corporate gift suppliers in Mumbai then visit our company website Bigimpex are best one

Collapse
ghoomlullp profile image
fardeen siddiqui

Love this!

We are going to use this for our company ghoomly.com

Thank you for this :)

Collapse
okwebsite profile image
Masoud Sourni

We are really grateful for your blog post. You will find a lot of approaches after visiting your post.
قیمت روز آهن

Collapse
merryhere profile image
merryhere

You explained it very well. Thanks for the efforts.
anyror 7/12

Collapse
jones009 profile image
abrar aK

Your blogs are easily accessible and quite enlightening so keep doing the amazing work guys. canadian citizenship

Collapse
samsimth60 profile image
samsimth60

I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people.
먹튀검증