URL shortening involves generating abbreviated versions of long URLs, referred to as "short links." When users access these short links, they are automatically redirected to the original, longer URL. Short links offer various benefits, such as saving space in display, print, messages, or tweets. Furthermore, shorter URLs decrease the likelihood of users making typing errors.
import java.util.* class URLShortener { private val idToUrlMap = HashMap<String, String>() private val urlToIdMap = HashMap<String, String>() private val BASE_URL = "http://short.url/" private val ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" fun shortenURL(longURL: String): String { if (urlToIdMap.containsKey(longURL)) { return BASE_URL + urlToIdMap[longURL] } val id = generateID() idToUrlMap[id] = longURL urlToIdMap[longURL] = id return BASE_URL + id } fun expandURL(shortURL: String): String { val id = shortURL.substring(BASE_URL.length) return idToUrlMap[id] ?: "URL not found" } private fun generateID(): String { val random = Random() val sb = StringBuilder() repeat(6) { sb.append(ALPHABET[random.nextInt(ALPHABET.length)]) } return sb.toString() } } fun main() { val urlShortener = URLShortener() val longURL = "https://www.example.com" val shortURL = urlShortener.shortenURL(longURL) println("Shortened URL: $shortURL") val expandedURL = urlShortener.expandURL(shortURL) println("Expanded URL: $expandedURL") }
Details of above code with explanation
idToUrlMap
: This HashMap maps shortened IDs (generated by the shortening process) to their corresponding original URLs. It facilitates the expansion process.urlToIdMap
: This HashMap maps original URLs to their corresponding shortened IDs. It helps avoid duplication of shortened URLs for the same original URL.BASE_URL
: This constant string represents the base URL for the shortened URLs. All shortened URLs generated by this URL shortener will start with this base URL.ALPHABET
: This string contains the characters used to generate the random alphanumeric IDs for shortening URLs.shortenURL(longURL: String)
: This method takes a long URL as input and generates a shortened URL for it. If the long URL has already been shortened before, it retrieves the existing shortened URL. Otherwise, it generates a new shortened ID, maps it to the long URL, and returns the shortened URL.expandURL(shortURL: String)
: This method takes a shortened URL as input and returns the corresponding original URL. It extracts the ID from the shortened URL and looks it up in theidToUrlMap
. If the ID exists in the map, it returns the corresponding original URL; otherwise, it indicates that the URL is not found.generateID()
: This private method generates a random alphanumeric ID of length 6 using characters from theALPHABET
string. It ensures uniqueness for each shortened URL.
Happy Coding ✌