Java String Program · S31
Encode and Decode a TinyURL in Java
Build a tiny URL shortener: encode() turns a long URL into a short link and decode() turns it back. Two maps and a good code generator are all you need.
Problem Statement
Design a class with two methods: encode(longUrl) returns a short URL, and decode(shortUrl) returns the original long URL.
Different long URLs must get different short codes, and encoding the same URL twice should return the same short URL. The short links use the placeholder domain https://short.example/.
Input/Output Examples
"https://javabytechie.com/java-tutorial"Output"https://short.example/1"Explanation: with a counter, the first URL gets code 1."https://javabytechie.com/spring-boot-tutorial"Output"https://short.example/2"Explanation: each new URL gets the next code."https://javabytechie.com/java-tutorial"Output"https://short.example/1"Explanation: the reverse map returns the existing code.Visual Explanation
- encode()long URL…/java-tutorialnew URL → id 1 base 62: 1 → "1"
- StorecodeToUrl1 → …/java-tutorialurlToCode…/java-tutorial → 1two maps
- decode()short URLshort.example/1strip the prefix, look up "1"
- Done…/java-tutorial
codeToUrl makes decoding O(1), and urlToCode makes repeated encoding of the same URL return the same code instead of using up a new one.
Approaches
Both approaches store the same two maps. They differ in how the short code is chosen.
Approach 1: Counter With Base-62 Codes (Recommended)
Idea: give each new URL the next number and write it with the 62 characters 0-9, a-z and A-Z.
- If the URL already has a code, return it.
- Otherwise, take
nextId++and convert it to base 62. - Store the pair in both maps and return the base URL plus the code.
decode()removes the prefix and looks the code up.
Time: O(1) · Space: O(N). N is the number of stored URLs; code length grows only logarithmically.
Approach 2: Random Codes With Collision Check
Idea: draw a random 6-character base-62 code and draw again if it is already taken.
- Return the existing code for a known URL.
- Build a random 6-character code.
- If the code is free, store the pair; otherwise draw again.
Time: O(1) expected · Space: O(N).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. The counter version produces short sequential codes; the random version produces 6-character codes, so the two outputs differ by design. The random version uses a fixed seed so that its output is repeatable.
Approach 1: Counter With Base-62 Codes (Recommended)
Codes are as short as possible and never collide. Six base-62 characters cover more than 56 billion URLs.
import java.util.HashMap;
import java.util.Map;
public class TinyUrlCounter {
private static final String BASE = "https://short.example/";
private static final String DIGITS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final Map<String, String> codeToUrl = new HashMap<>();
private final Map<String, String> urlToCode = new HashMap<>();
private long nextId = 1;
// Each new URL gets the next number, written in base 62
String encode(String longUrl) {
String code = urlToCode.get(longUrl);
if (code == null) {
code = toBase62(nextId++);
urlToCode.put(longUrl, code);
codeToUrl.put(code, longUrl);
}
return BASE + code;
}
String decode(String shortUrl) {
return codeToUrl.get(shortUrl.substring(BASE.length()));
}
private static String toBase62(long n) {
StringBuilder sb = new StringBuilder();
while (n > 0) {
sb.append(DIGITS.charAt((int) (n % 62)));
n /= 62;
}
return sb.reverse().toString();
}
public static void main(String[] args) {
TinyUrlCounter codec = new TinyUrlCounter();
String[] urls = {"https://javabytechie.com/java-tutorial", "https://javabytechie.com/spring-boot-tutorial",
"https://javabytechie.com/java-tutorial"};
for (String url : urls) {
String shortUrl = codec.encode(url);
System.out.println(shortUrl + " -> " + codec.decode(shortUrl));
}
System.out.println("62nd URL code: " + toBase62(62));
}
}
https://short.example/1 -> https://javabytechie.com/java-tutorial https://short.example/2 -> https://javabytechie.com/spring-boot-tutorial https://short.example/1 -> https://javabytechie.com/java-tutorial 62nd URL code: 10
Time complexity: O(1) · Space complexity: O(N).
Approach 2: Random Codes With Collision Check
Codes cannot be guessed in sequence, which hides how many links exist. The loop almost never repeats while the table is far from full.
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class TinyUrlRandom {
private static final String BASE = "https://short.example/";
private static final String DIGITS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final Map<String, String> codeToUrl = new HashMap<>();
private final Map<String, String> urlToCode = new HashMap<>();
private final Random random;
TinyUrlRandom(Random random) {
this.random = random;
}
// A random 6-character code; a new code is drawn if it is already taken
String encode(String longUrl) {
String code = urlToCode.get(longUrl);
while (code == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
sb.append(DIGITS.charAt(random.nextInt(DIGITS.length())));
}
if (!codeToUrl.containsKey(sb.toString())) {
code = sb.toString();
urlToCode.put(longUrl, code);
codeToUrl.put(code, longUrl);
}
}
return BASE + code;
}
String decode(String shortUrl) {
return codeToUrl.get(shortUrl.substring(BASE.length()));
}
public static void main(String[] args) {
TinyUrlRandom codec = new TinyUrlRandom(new Random(42)); // fixed seed so the output is repeatable
String[] urls = {"https://javabytechie.com/java-tutorial", "https://javabytechie.com/spring-boot-tutorial",
"https://javabytechie.com/java-tutorial"};
for (String url : urls) {
String shortUrl = codec.encode(url);
System.out.println(shortUrl + " -> " + codec.decode(shortUrl));
}
}
}
https://short.example/6FyS2X -> https://javabytechie.com/java-tutorial https://short.example/3wn3y0 -> https://javabytechie.com/spring-boot-tutorial https://short.example/6FyS2X -> https://javabytechie.com/java-tutorial
Time complexity: O(1) expected · Space complexity: O(N).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Counter With Base-62 Codes | O(1) | O(N) |
| Random Codes With Collision Check | O(1) expected | O(N) |
Here N is the number of URLs stored. Both encode and decode are hash-map operations, so they take O(1) time on average; the maps hold every URL once in each direction.
Interview Tips and Recommended Approach
- Explain base 62. Using digits and both letter cases gives short, URL-safe codes.
- Discuss predictability. Sequential codes are short but reveal how many links exist and can be enumerated; random codes avoid that.
- Mention scaling. In a real service, the maps become a database table, and the counter becomes a distributed id generator.
- Validate on decode. An unknown code should return
nullor a not-found error rather than throwing.
Recommended Approach: Counter With Base-62 Codes
Why: it guarantees unique, short codes without any collision handling and keeps both operations at O(1). It is also the easiest version to explain before discussing scaling trade-offs.