Encode and Decode TinyURL

  • 0

    Click here to see the full article post

  • 0

    Using a combination of System.nanoTime() and hashCode().
    It produces urls in this format https://tinyurl.com/596293762700519

    // Encodes a URL to a shortened URL.
    HashMap<String,String> tinyUrlMap = new HashMap<>();
    HashMap<String,String> longUrlMap = new HashMap<>();
    String tinyPrefix = "https://tinyurl.com/";

    public String encode(String longUrl) {
    if(longUrlMap.containsKey(longUrl)) return longUrlMap.get(longUrl);
    String tinyUrl = tinyPrefix+(longUrl.hashCode()+System.nanoTime());
    return tinyUrl;

    public String decode(String shortUrl) {
    return tinyUrlMap.get(shortUrl);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.