Video in progress
How can you generate the short code in a URL shortener?
The simplest way is to convert the database auto-increment ID to base62: 125 → "21". Other options are to generate a random code and check for collisions, or to hash the URL and take the first characters.
📖 Answer
There are three typical approaches.
1. ID + base62. You save the record to the database, get id = 125, and convert it to the [0-9a-zA-Z] alphabet.
static final String ABC =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String encode(long id) {
StringBuilder sb = new StringBuilder();
do {
sb.append(ABC.charAt((int) (id % 62)));
id /= 62;
} while (id > 0);
return sb.reverse().toString();
}
There are no collisions, but the codes are sequential: abc1, abc2 — a stranger can walk through other people's links.
2. Random code. You generate 7 characters with SecureRandom, save with a UNIQUE constraint, and retry on a collision. Hard to guess.
3. Hash. You take MD5/SHA-256 of the URL and use the first 7 characters. The same URL gives the same code, but you still have to check for collisions.
In practice option 2 is chosen most often. If several servers get IDs at the same time, option 1 needs a shared counter or ID ranges handed out to servers in advance.
Sign up to mark studied questions and save your progress.