702986. Design a tiny URL or URL shortener

Medium

Design a Tiny URL or URL Shortener

Summary

Create a URL shortener that takes in a long URL and returns a shorter version. The goal is to reduce the original URL's length while still allowing users to access the same content. This problem involves manipulating strings, arrays, and hashing techniques.

Detailed Explanation

The approach for this problem is to create a mapping of the original URLs to their shortened versions using a hash function. We'll use an array or hash map (e.g., HashMap in Java) to store these mappings.

Here's a step-by-step breakdown:

  1. Initialize an empty hash map (urlMap) to store the original URLs and their corresponding short IDs.
  2. Generate a unique ID for each original URL using a hashing algorithm (e.g., MD5 or SHA-256). This ID will be used as the shortened version of the URL.
  3. Store the original URL and its corresponding short ID in the urlMap.
  4. When a user wants to shorten an original URL, generate a new unique ID using the same hashing algorithm.
  5. Check if the generated ID already exists in the urlMap. If it does, increment the ID by 1 until we find a unique one.
  6. Store the original URL and its corresponding short ID in the urlMap.
  7. Return the shortened version of the URL (the generated ID).

Time complexity: O(1) for lookup operations and O(n) for generating new IDs (where n is the number of URLs). Space complexity: O(n) to store the mappings in the hash map.

Optimized Solutions

Java

View on GeeksforGeeks
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class URLShortener {
    private static final int SHORT_ID_LENGTH = 6; // adjustable length for shortened IDs
    private Map<String, String> urlMap = new HashMap<>();

    public String shortenURL(String originalURL) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashBytes = md.digest(originalURL.getBytes());
        StringBuilder shortID = new StringBuilder();
        for (byte b : hashBytes) {
            shortID.append(Integer.toHexString(b & 0xFF));
        }
        String shortenedURL = shorten(shortID.toString().substring(0, SHORT_ID_LENGTH));
        urlMap.put(originalURL, shortenedURL);
        return shortenedURL;
    }

    private String shorten(String shortID) {
        // you can add your own logic here to further shorten the ID if needed
        return shortID;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.