Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Create URL Bookmark Manager Using Django
Next article icon

How to design a tiny URL or URL shortener?

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

How to design a system that takes big URLs like “https://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 the database and every URL has an associated integer id. 

One important thing to note is, the long URL should also be uniquely identifiable from the short URL. So we need a Bijective Function  

We strongly recommend that you click here and practice it, before moving on to the solution.

One Simple Solution could be Hashing. Use a hash function to convert long string to short string. In hashing, that may be collisions (2 long URLs map to same short URL) and we need a unique short URL for every long URL so that we can access long URL back.

A Better Solution is to use the integer id stored in the database and convert the integer to a character string that is at most 6 characters long. This problem can basically seen as a base conversion problem where we have a 10 digit input number and we want to convert it into a 6-character long string. 

Below is one important observation about possible characters in 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 a decimal number to base 62 number. 
To get the original long URL, we need to get URL id in the database. The id can be obtained using base 62 to decimal conversion.

Implementation:

C++
// C++ program to generate short url from integer id and // integer id back from short url. #include<iostream> #include<algorithm> #include<string> using namespace std;  // Function to generate a short url from integer ID string idToShortURL(long int n) {     // Map to store 62 possible characters     char map[] = "abcdefghijklmnopqrstuvwxyzABCDEF"                  "GHIJKLMNOPQRSTUVWXYZ0123456789";      string shorturl;      // Convert given integer id to a base 62 number     while (n)     {         // use above map to store actual character         // in short url         shorturl.push_back(map[n%62]);         n = n/62;     }      // Reverse shortURL to complete base conversion     reverse(shorturl.begin(), shorturl.end());      return shorturl; }  // Function to get integer ID back from a short url long int shortURLtoID(string shortURL) {     long int id = 0; // initialize result      // A simple base conversion logic     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 id; }  // Driver program to test above function int main() {     int n = 12345;     string shorturl = idToShortURL(n);     cout << "Generated short url is " << shorturl << endl;     cout << "Id from url is " << shortURLtoID(shorturl);     return 0; } 
Java
// Java program to generate short url from integer id and  // integer id back from short url.  import java.util.*; import java.lang.*; import java.io.*;  class GFG {     // Function to generate a short url from integer ID      static String idToShortURL(int n)      {          // Map to store 62 possible characters          char map[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();               StringBuffer shorturl = new StringBuffer();               // Convert given integer id to a base 62 number          while (n > 0)          {              // use above map to store actual character              // in short url              shorturl.append(map[n % 62]);             n = n / 62;          }               // Reverse shortURL to complete base conversion          return shorturl.reverse().toString();      }           // Function to get integer ID back from a short url      static int shortURLtoID(String shortURL)      {          int id = 0; // initialize result               // A simple base conversion logic          for (int i = 0; i < shortURL.length(); i++)          {              if ('a' <= shortURL.charAt(i) &&                         shortURL.charAt(i) <= 'z')              id = id * 62 + shortURL.charAt(i) - 'a';              if ('A' <= shortURL.charAt(i) &&                         shortURL.charAt(i) <= 'Z')              id = id * 62 + shortURL.charAt(i) - 'A' + 26;              if ('0' <= shortURL.charAt(i) &&                         shortURL.charAt(i) <= '9')              id = id * 62 + shortURL.charAt(i) - '0' + 52;          }          return id;      }           // Driver Code     public static void main (String[] args) throws IOException     {         int n = 12345;          String shorturl = idToShortURL(n);          System.out.println("Generated short url is " + shorturl);          System.out.println("Id from url is " +                              shortURLtoID(shorturl));      } }  // This code is contributed by shubham96301 
Python
# Python3 code for above approach  def idToShortURL(id):     map = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"     shortURL = ""          # for each digit find the base 62     while(id > 0):         shortURL += map[id % 62]         id //= 62      # reversing the shortURL     return shortURL[len(shortURL): : -1]  def shortURLToId(shortURL):     id = 0     for i in shortURL:         val_i = ord(i)         if(val_i >= ord('a') and val_i <= ord('z')):             id = id*62 + val_i - ord('a')         elif(val_i >= ord('A') and val_i <= ord('Z')):             id = id*62 + val_i - ord('A') + 26         else:             id = id*62 + val_i - ord('0') + 52     return id  if (__name__ == "__main__"):     id = 12345     shortURL = idToShortURL(id)     print("Short URL from 12345 is : ", shortURL)     print("ID from", shortURL, "is : ", shortURLToId(shortURL)) 
C#
// C# program to generate short url from integer id and  // integer id back from short url.  using System;  public class GFG {     // Function to generate a short url from integer ID      static String idToShortURL(int n)      {          // Map to store 62 possible characters          char []map = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();               String shorturl = "";                 // Convert given integer id to a base 62 number          while (n > 0)          {              // use above map to store actual character              // in short url              shorturl+=(map[n % 62]);             n = n / 62;          }               // Reverse shortURL to complete base conversion          return reverse(shorturl);      }      static String reverse(String input) {         char[] a = input.ToCharArray();         int l, r = a.Length - 1;         for (l = 0; l < r; l++, r--) {             char temp = a[l];             a[l] = a[r];             a[r] = temp;         }         return String.Join("",a);     }     // Function to get integer ID back from a short url      static int shortURLtoID(String shortURL)      {          int id = 0; // initialize result               // A simple base conversion logic          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 id;      }           // Driver Code     public static void Main(String[] args)     {         int n = 12345;          String shorturl = idToShortURL(n);          Console.WriteLine("Generated short url is " + shorturl);          Console.WriteLine("Id from url is " +                              shortURLtoID(shorturl));      } }  // This code is contributed by 29AjayKumar  
JavaScript
<script> // Javascript program to generate short url from integer id and // integer id back from short url.  // Function to generate a short url from integer ID function idToShortURL(n)  {      // Map to store 62 possible characters     let map = "abcdefghijklmnopqrstuvwxyzABCDEF"     "GHIJKLMNOPQRSTUVWXYZ0123456789";      let shorturl = [];      // Convert given integer id to a base 62 number     while (n)      {         // use above map to store actual character         // in short url         shorturl.push(map[n % 62]);         n = Math.floor(n / 62);     }      // Reverse shortURL to complete base conversion     shorturl.reverse();      return shorturl.join(""); }  // Function to get integer ID back from a short url function shortURLtoID(shortURL) {     let id = 0; // initialize result      // A simple base conversion logic     for (let i = 0; i < shortURL.length; i++) {         if ('a' <= shortURL[i] && shortURL[i] <= 'z')             id = id * 62 + shortURL[i].charCodeAt(0) - 'a'.charCodeAt(0);         if ('A' <= shortURL[i] && shortURL[i] <= 'Z')             id = id * 62 + shortURL[i].charCodeAt(0) - 'A'.charCodeAt(0) + 26;         if ('0' <= shortURL[i] && shortURL[i] <= '9')             id = id * 62 + shortURL[i].charCodeAt(0) - '0'.charCodeAt(0) + 52;     }     return id; }  // Driver program to test above function  let n = 12345; let shorturl = idToShortURL(n); document.write("Generated short url is " + shorturl + "<br>"); document.write("Id from url is " + shortURLtoID(shorturl));  // This code is contributed by gfgking. </script> 

Output
Generated short url is dnh Id from url is 12345

Time complexity : O(n) 
Auxiliary Space : O(1)

Optimization: We can avoid reverse step in idToShortURL(). To make sure that we get the same ID back, we also need to change shortURLtoID() to process characters from the end instead of the beginning.



Next Article
Create URL Bookmark Manager Using Django
author
kartik
Improve
Article Tags :
  • Advanced Data Structure
  • Arrays
  • DSA
  • Strings
  • System Design
  • Hike
  • Microsoft
Practice Tags :
  • Hike
  • Microsoft
  • Advanced Data Structure
  • Arrays
  • Strings

Similar Reads

  • URL Shortner (bit.ly, TinyURL, etc) - System Design
    The need for an efficient and concise URL management system has become a big matter in this technical age. URL shortening services, such as bit.ly, and TinyURL, play a massive role in transforming lengthy web addresses into shorter, shareable links. As the demand for such services grows, it has beco
    12 min read
  • Check if an URL is valid or not using Regular Expression
    Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.Examples : Input : str = "https://www.geeksforgeeks.org/" Output : Yes Explanation : The above URL is a valid URL.Input : str = "https:// www.geeksforgeeks.org/" Output : No Explanation : Note that
    4 min read
  • System Design Interview Questions and Answers [2025]
    In the hiring procedure, system design interviews play a significant role for many tech businesses, particularly those that develop large, reliable software systems. In order to satisfy requirements like scalability, reliability, performance, and maintainability, an extensive plan for the system's a
    7 min read
  • URL Shortener Service with NextJS
    In this article, we will explore the process of building a URL shortener service using NextJS that takes a long URL and generates a shorter, more condensed version that redirects to the original URL when accessed. This shortened URL is typically much shorter and easier to share, especially in situat
    2 min read
  • Create URL Bookmark Manager Using Django
    This article explains how to make a tool called a Bookmark Organizer with Django for a website. With this tool, we can add, create, update, delete, and edit bookmarks easily. We just need to input the title and link, and we can save them. Then, we can click on the link anytime to visit the website.
    5 min read
  • URL Shortener Generator Project
    URL Shortener Generator Project is one of the most common software development projects. In this article, we will make the URL Shortener Generator software development project, from scratch, for final-year students. We will cover all the steps you must do while developing this project. Demo Video: H
    15+ min read
  • Pros and Cons of URL Shorteners
    Prerequisite: URL Shorteners and its API in Python | Set-1, Set-2 . After having a prolonged discussion on URL Shorteners and how they can be used programmatically. Let's jot down a list of pros and cons of these services. URL shortening services have been around for longer than most people realize.
    5 min read
  • URL Shorteners and its API in Python | Set-1
    URL Shortener, as the name suggests, is a service to help to reduce the length of the URL so that it can be shared easily on platforms like Twitter, where number of characters is an issue. There are so many URL Shorteners available in the market today, that will definitely help you out to solve the
    5 min read
  • Build a URL Size Reduce App with Django
    Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this article, we will learn to build a URL shortener using Django. A URL shortener is used to reduce the size of long URLs. Short URLs are better for sharing purposes. In this article, we wi
    5 min read
  • Python | URL shortener using tinyurl API
    There are multiple APIs (e.g-bitly API, etc.) available for URL shortening service but in this article, we will be using Tinyurl API to shorten URLs. Though tinyURL has not officially released its API but we are going to use it unofficially. Here, we can put as input any number of URLs at a time and
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences