How to design a system that takes big URLs like "https://www.geeksforgeeks.org/dsa/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Â
- A lower case alphabet ['a' to 'z'], total 26 charactersÂ
- An upper case alphabet ['A' to 'Z'], total 26 charactersÂ
- 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:
import java.util.HashMap;
import java.util.Map;
public class SimpleURLShortener {
// Base62 characters
private static final String BASE62 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// Maps to store URL mappings
private static Map<String, String> shortToLong = new HashMap<>();
private static Map<String, String> longToShort = new HashMap<>();
// Counter (simulating auto-increment ID)
private static long counter = 1;
private static final String BASE_URL = "http://tiny.url/";
// Encode long URL to short URL
public static String encode(String longUrl) {
// If already exists, return existing short URL
if (longToShort.containsKey(longUrl)) {
return BASE_URL + longToShort.get(longUrl);
}
// Generate short key using Base62
String shortKey = convertToBase62(counter);
counter++;
// Store mapping
shortToLong.put(shortKey, longUrl);
longToShort.put(longUrl, shortKey);
return BASE_URL + shortKey;
}
// Decode short URL to original long URL
public static String decode(String shortUrl) {
String shortKey = shortUrl.replace(BASE_URL, "");
return shortToLong.getOrDefault(shortKey, "URL not found");
}
// Convert number to Base62
private static String convertToBase62(long num) {
StringBuilder sb = new StringBuilder();
while (num > 0) {
int remainder = (int)(num % 62);
sb.append(BASE62.charAt(remainder));
num = num / 62;
}
return sb.reverse().toString();
}
// Main method
public static void main(String[] args) {
String longUrl = "https://www.geeksforgeeks.org/dsa/count-sum-of-digits-in-numbers-from-1-to-n/";
// Encode
String shortUrl = encode(longUrl);
System.out.println("Short URL: " + shortUrl);
// Decode
String originalUrl = decode(shortUrl);
System.out.println("Original URL: " + originalUrl);
}
}
// Base62 characters
const BASE62 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// Maps to store URL mappings
const shortToLong = new Map();
const longToShort = new Map();
// Counter (simulating auto-increment ID)
let counter = 1;
const BASE_URL = 'http://tiny.url/';
// Encode long URL to short URL
function encode(longUrl) {
// If already exists, return existing short URL
if (longToShort.has(longUrl)) {
return BASE_URL + longToShort.get(longUrl);
}
// Generate short key using Base62
const shortKey = convertToBase62(counter);
counter++;
// Store mapping
shortToLong.set(shortKey, longUrl);
longToShort.set(longUrl, shortKey);
return BASE_URL + shortKey;
}
// Decode short URL to original long URL
function decode(shortUrl) {
const shortKey = shortUrl.replace(BASE_URL, '');
return shortToLong.get(shortKey) || 'URL not found';
}
// Convert number to Base62
function convertToBase62(num) {
let result = '';
while (num > 0) {
const remainder = num % 62;
result = BASE62[remainder] + result;
num = Math.floor(num / 62);
}
return result;
}
// Main method
const longUrl = 'https://www.geeksforgeeks.org/dsa/count-sum-of-digits-in-numbers-from-1-to-n/';
// Encode
const shortUrl = encode(longUrl);
console.log('Short URL:', shortUrl);
// Decode
const originalUrl = decode(shortUrl);
console.log('Original URL:', originalUrl);
Output
Short URL: http://tiny.url/b Original URL: https://www.geeksforgeeks.org/dsa/count-sum-of-digits-in-numbers-from-1-to-n/
Time complexity : Encode â O(L) and Decode â O(1)Â
Auxiliary Space : O(N * L)