Google interview question

How would you implement a URL shortener without a backend?

Interview Answers

Anonymous

19 Oct 2016

This depends on the definition of "backend." Taken typically to mean "some sort of database," this becomes problematic -- most compression algorithms will not work efficiently on such short strings. If allowed to use Unicode, however, this becomes trivial for extended ASCII URLs (this solution will not work for full UTF-8 URLs): Generate a list of all Unicode characters except those encompassed in extended ASCII. Given the formula x > 256^n + 256, where x is the number of characters in our Unicode minus ASCII set, find the maximum integral value of n. For all single extended ASCII characters and all extended ASCII strings of length n, generate a hash where the key is the ASCII character or string, and the value is one of your Unicode characters, where each Unicode character is used only once. Generate an identical hash, reversed, such that the keys are the Unicode characters and the values are the extended ASCII characters/strings. When shortening the URL, split it into strings of length n. For each resultant string of length n (the final string may be shorter than n), find the corresponding Unicode character and add it to your shortened URL string. For the final string, split it into single characters and find the corresponding Unicode character (this is an increase in memory usage, but on decode will result in less logic operations as opposed to leaving these as plain ASCII). Return this string to users. Use the reverse hash to decode. Note that you could identify a Unicode character to use as an escape character and likely support full UTF-8 URLs. The hash, of course, would be lost in the event of the application exiting, but could be rebuilt. You could also just cheat and use flat files instead of a database!

1

Anonymous

28 Sept 2019

A web server rewrite rule should be suffice

Anonymous

8 June 2016

With all the logic in the Frontend. JS can do this stuff.