Design a tiny URL or URL Shortner

Design a system that takes big URLs like “http://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/” and converts them into a short 6 character URL. It is given that URLs are stored in database and every URL has an associated integer id.  So your program should take an integer id and generate a 6 character long URL. 

A URL character can be one of the following

  1. A lower case alphabet [‘a’ to ‘z’], total 26 characters
  2. An upper case alphabet [‘A’ to ‘Z’], total 26 characters
  3. A digit [‘0′ to ‘9’], total 10 characters

There are total 26 + 26 + 10 = 62 possible characters.

So the task is to convert an integer (database id) to a base 62 number where digits of 62 base are "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

Input:
The first line of input contains an integer T denoting the number of test cases.
 The second line consists of a long integer.

Output:
For each testcase, in a new line, print the shortened string in the first line and convert the shortened string back to ID (to make sure that your conversion works fine) and print that in the second line.

Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 232-1

Example:
Input:
1
12345

Output:
dnh
12345

The link of this problem is https://practice.geeksforgeeks.org/problems/design-a-tiny-url-or-url-shortener/0 

Solution:

CPP

#include<iostream>

using namespace std;

int main()

{

    int t;

    cin>>t;

    while(t--)

    {

        long long int n;

        cin>>n;

        long long int k=n;

        unordered_map<int,char> h;

        int j=0;

        for(char i='a';i<='z';i++)

        {

            h[j]=i;

            j++;

        }

        for(char i='A';i<='Z';i++)

        {

            h[j]=i;

            j++;

        }

        for(char i='0';i<='9';i++)

        {

            h[j]=i;

            j++;

        }

        stack<char> s;

        while(n!=0)

        {

            int rem=n%62;

            s.push(h[rem]);

            n=n/62;

        }

        while(!s.empty())

        {

            cout<<s.top();

            s.pop();

        }

        cout<<endl;

        cout<<k;

        cout<<endl;

    }

return 0;

}

Comments

  1. Very Good.
    I have a job opportunity as a backend software engineer .
    Please comment of interested

    ReplyDelete

Post a Comment

Popular posts from this blog

Floyd Warshall algorithm and it's applications.

Digits in Factorial