Implement a local URL shortener that runs on a single machine.
Design a small library or service with two core operations:
-
shorten(long_url) -> short_code
or
short_url
-
resolve(short_code) -> original_url
Requirements:
-
Validate that the input is a well-formed URL and reject invalid input.
-
Generate a short code using a hash-based or similar encoding strategy.
-
Handle hash collisions correctly so that no original URL mapping is lost.
-
Store the mapping between short codes and original URLs in memory using a hash map.
-
Persist the in-memory mapping to a JSON file, and reload that file when the program starts again.
-
If the same original URL is shortened multiple times, return the same shortened result instead of creating duplicates.
-
Handle edge cases such as extremely long URLs.
-
Write tests for invalid input, collision handling, duplicate requests, and long URLs, with strong line and branch coverage.
-
Be prepared to discuss how memory usage grows with the number of stored URLs and what changes you would make if the data no longer fits comfortably on one machine.
Assume this is a local-only implementation. Do not introduce external systems such as Redis or a database unless you can justify why they are necessary.