A simple Java solution

  • 0

    The idea is to avoid collision-based lookup but generate uniqueness between concurrent requests.

     private Map<String,String> map = new HashMap<>();
        private AtomicInteger count = new AtomicInteger(0);
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            String time = System.currentTimeMillis() + "" + count.getAndIncrement();
            String url = "http://tinyurl.com/" + Base64.getEncoder().encodeToString(time.getBytes());
            return url;
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return map.get(shortUrl);

Log in to reply

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